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 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 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.
34 using System.Collections;
35 using System.Collections.Specialized;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Security;
41 using System.Security.Permissions;
44 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
45 using XmlElement = System.Object;
50 using Mono.CompilerServices.SymbolWriter;
52 namespace Mono.CSharp {
64 /// This is the base class for structs and classes.
66 public abstract class TypeContainer : DeclSpace, IMemberContainer {
68 public class MemberCoreArrayList: ArrayList
71 /// Defines the MemberCore objects that are in this array
73 public virtual void DefineContainerMembers ()
75 foreach (MemberCore mc in this) {
78 } catch (Exception e) {
79 throw new InternalErrorException (mc, e);
84 public virtual void Emit ()
86 foreach (MemberCore mc in this)
91 public class OperatorArrayList: MemberCoreArrayList
93 TypeContainer container;
95 public OperatorArrayList (TypeContainer container)
97 this.container = container;
101 // Checks that some operators come in pairs:
107 // They are matched based on the return type and the argument types
109 void CheckPairedOperators ()
111 bool has_equality_or_inequality = false;
112 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
113 bool [] has_pair = new bool [operators.Length];
115 for (int i = 0; i < Count; ++i) {
116 if (operators [i] == null)
119 Operator o_a = operators [i];
120 Operator.OpType o_type = o_a.OperatorType;
121 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
122 has_equality_or_inequality = true;
124 Operator.OpType matching_type = o_a.GetMatchingOperator ();
125 if (matching_type == Operator.OpType.TOP) {
126 operators [i] = null;
130 for (int ii = 0; ii < Count; ++ii) {
131 Operator o_b = operators [ii];
132 if (o_b == null || o_b.OperatorType != matching_type)
135 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
138 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
141 operators [i] = null;
144 // Used to ignore duplicate user conversions
146 has_pair [ii] = true;
150 for (int i = 0; i < Count; ++i) {
151 if (operators [i] == null || has_pair [i])
154 Operator o = operators [i];
155 Report.Error (216, o.Location,
156 "The operator `{0}' requires a matching operator `{1}' to also be defined",
157 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
160 if (has_equality_or_inequality && Report.WarningLevel > 2) {
161 if (container.Methods == null || !container.HasEquals)
162 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
164 if (container.Methods == null || !container.HasGetHashCode)
165 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
169 public override void DefineContainerMembers ()
171 base.DefineContainerMembers ();
172 CheckPairedOperators ();
180 GetHashCode = 1 << 1,
181 HasStaticFieldInitializer = 1 << 2
185 // Whether this is a struct, class or interface
186 public readonly Kind Kind;
188 // Holds a list of classes and structures
189 protected ArrayList types;
191 MemberCoreArrayList ordered_explicit_member_list;
192 MemberCoreArrayList ordered_member_list;
194 // Holds the list of properties
195 MemberCoreArrayList properties;
197 // Holds the list of delegates
198 MemberCoreArrayList delegates;
200 // Holds the list of constructors
201 protected MemberCoreArrayList instance_constructors;
203 // Holds the list of fields
204 MemberCoreArrayList fields;
206 // Holds a list of fields that have initializers
207 protected ArrayList initialized_fields;
209 // Holds a list of static fields that have initializers
210 protected ArrayList initialized_static_fields;
212 // Holds the list of constants
213 protected MemberCoreArrayList constants;
215 // Holds the methods.
216 MemberCoreArrayList methods;
219 protected MemberCoreArrayList events;
221 // Holds the indexers
224 // Holds the operators
225 MemberCoreArrayList operators;
227 // Holds the compiler generated classes
228 ArrayList compiler_generated;
231 // Pointers to the default constructor and the default static constructor
233 protected Constructor default_constructor;
234 protected Constructor default_static_constructor;
237 // Points to the first non-static field added to the container.
239 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
240 // and the first one's as good as any.
242 FieldBase first_nonstatic_field = null;
245 // This one is computed after we can distinguish interfaces
246 // from classes from the arraylist `type_bases'
249 TypeExpr[] iface_exprs;
252 protected ArrayList type_bases;
254 bool members_resolved;
255 bool members_resolved_ok;
256 protected bool members_defined;
257 bool members_defined_ok;
259 // The interfaces we implement.
260 protected Type[] ifaces;
262 // The base member cache and our member cache
263 MemberCache base_cache;
264 protected MemberCache member_cache;
266 public const string DefaultIndexerName = "Item";
268 private bool seen_normal_indexers = false;
269 private string indexer_name = DefaultIndexerName;
271 private CachedMethods cached_method;
273 ArrayList partial_parts;
276 /// The pending methods that need to be implemented
277 // (interfaces or abstract methods)
279 PendingImplementation pending;
281 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
282 Attributes attrs, Kind kind)
283 : base (ns, parent, name, attrs)
285 if (parent != null && parent.NamespaceEntry != ns)
286 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
289 this.PartialContainer = this;
292 public bool AddMember (MemberCore symbol)
294 return AddToContainer (symbol, symbol.MemberName.MethodName);
297 protected virtual bool AddMemberType (DeclSpace ds)
299 return AddToContainer (ds, ds.Basename);
302 public void AddConstant (Const constant)
304 if (!AddMember (constant))
307 if (constants == null)
308 constants = new MemberCoreArrayList ();
310 constants.Add (constant);
313 public TypeContainer AddTypeContainer (TypeContainer tc)
315 if (!AddMemberType (tc))
319 types = new MemberCoreArrayList ();
325 public virtual TypeContainer AddPartial (TypeContainer next_part)
327 return AddPartial (next_part, next_part.Basename);
330 protected TypeContainer AddPartial (TypeContainer next_part, string name)
332 next_part.ModFlags |= Modifiers.PARTIAL;
333 TypeContainer tc = defined_names [name] as TypeContainer;
336 return AddTypeContainer (next_part);
338 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
339 Report.SymbolRelatedToPreviousError (next_part);
340 Error_MissingPartialModifier (tc);
343 if (tc.Kind != next_part.Kind) {
344 Report.SymbolRelatedToPreviousError (tc);
345 Report.Error (261, next_part.Location,
346 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
347 next_part.GetSignatureForError ());
350 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
351 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
352 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
353 Report.SymbolRelatedToPreviousError (tc);
354 Report.Error (262, next_part.Location,
355 "Partial declarations of `{0}' have conflicting accessibility modifiers",
356 next_part.GetSignatureForError ());
359 if (tc.partial_parts == null)
360 tc.partial_parts = new ArrayList (1);
362 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
363 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
364 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
365 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
366 tc.ModFlags |= next_part.ModFlags;
368 tc.ModFlags |= next_part.ModFlags;
371 if (next_part.attributes != null) {
372 if (tc.attributes == null)
373 tc.attributes = next_part.attributes;
375 tc.attributes.AddAttributes (next_part.attributes.Attrs);
378 next_part.PartialContainer = tc;
379 tc.partial_parts.Add (next_part);
383 public void AddDelegate (Delegate d)
385 if (!AddMemberType (d))
388 if (delegates == null)
389 delegates = new MemberCoreArrayList ();
394 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
396 if (ordered_explicit_member_list == null) {
397 ordered_explicit_member_list = new MemberCoreArrayList ();
398 ordered_member_list = new MemberCoreArrayList ();
402 ordered_explicit_member_list.Add (mc);
403 alist.Insert (0, mc);
406 ordered_member_list.Add (mc);
412 public void AddMethod (Method method)
414 MemberName mn = method.MemberName;
415 if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
419 methods = new MemberCoreArrayList ();
421 if (method.MemberName.Left != null)
422 AddMemberToList (method, methods, true);
424 AddMemberToList (method, methods, false);
427 public void RemoveMethod (Method method)
429 methods.Remove (method);
430 if (method.IsExplicitImpl)
431 ordered_explicit_member_list.Remove (method);
433 ordered_member_list.Remove (method);
437 // Do not use this method: use AddMethod.
439 // This is only used by iterators.
441 public void AppendMethod (Method method)
443 if (!AddMember (method))
447 methods = new MemberCoreArrayList ();
449 AddMemberToList (method, methods, false);
452 public void AddConstructor (Constructor c)
454 if (c.Name != MemberName.Name) {
455 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
458 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
459 if (!AddToContainer (c, is_static ?
460 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
463 if (is_static && c.Parameters.Empty){
464 if (default_static_constructor != null) {
465 Report.SymbolRelatedToPreviousError (default_static_constructor);
466 Report.Error (111, c.Location,
467 "A member `{0}' is already defined. Rename this member or use different parameter types",
468 c.GetSignatureForError ());
472 default_static_constructor = c;
474 if (c.Parameters.Empty)
475 default_constructor = c;
477 if (instance_constructors == null)
478 instance_constructors = new MemberCoreArrayList ();
480 instance_constructors.Add (c);
484 public bool AddField (FieldBase field)
486 if (!AddMember (field))
490 fields = new MemberCoreArrayList ();
494 if ((field.ModFlags & Modifiers.STATIC) != 0)
497 if (first_nonstatic_field == null) {
498 first_nonstatic_field = field;
502 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
503 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
504 Report.Warning (282, 3, field.Location,
505 "struct instance field `{0}' found in different declaration from instance field `{1}'",
506 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
511 public void AddProperty (Property prop)
513 if (!AddMember (prop) ||
514 !AddMember (prop.Get) || !AddMember (prop.Set))
517 if (properties == null)
518 properties = new MemberCoreArrayList ();
520 if (prop.MemberName.Left != null)
521 AddMemberToList (prop, properties, true);
523 AddMemberToList (prop, properties, false);
526 public void AddEvent (Event e)
531 if (e is EventProperty) {
532 if (!AddMember (e.Add))
535 if (!AddMember (e.Remove))
540 events = new MemberCoreArrayList ();
546 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
548 public void AddIndexer (Indexer i)
550 if (indexers == null)
551 indexers = new ArrayList ();
553 if (i.IsExplicitImpl)
554 AddMemberToList (i, indexers, true);
556 AddMemberToList (i, indexers, false);
559 public void AddOperator (Operator op)
564 if (operators == null)
565 operators = new OperatorArrayList (this);
570 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
572 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
574 if (compiler_generated == null)
575 compiler_generated = new ArrayList ();
577 compiler_generated.Add (c);
580 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
582 if (a.Type == TypeManager.default_member_type) {
583 if (Indexers != null) {
584 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
589 base.ApplyAttributeBuilder (a, cb);
592 public override AttributeTargets AttributeTargets {
594 throw new NotSupportedException ();
598 public ArrayList Types {
604 public MemberCoreArrayList Methods {
610 public ArrayList Constants {
616 protected Type BaseType {
618 return TypeBuilder.BaseType;
622 public ArrayList Fields {
628 public ArrayList InstanceConstructors {
630 return instance_constructors;
634 public ArrayList Properties {
640 public ArrayList Events {
646 public ArrayList Indexers {
652 public ArrayList Operators {
658 public ArrayList Delegates {
664 protected override TypeAttributes TypeAttr {
666 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
670 public string IndexerName {
672 return indexers == null ? DefaultIndexerName : indexer_name;
676 public bool IsComImport {
678 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
681 return OptAttributes.Contains (TypeManager.comimport_attr_type);
685 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
687 if ((field.ModFlags & Modifiers.STATIC) != 0){
688 if (initialized_static_fields == null) {
689 PartialContainer.HasStaticFieldInitializer = true;
690 initialized_static_fields = new ArrayList (4);
693 initialized_static_fields.Add (expression);
695 if (initialized_fields == null)
696 initialized_fields = new ArrayList (4);
698 initialized_fields.Add (expression);
702 public void ResolveFieldInitializers (EmitContext ec)
704 // Field initializers are tricky for partial classes. They have to
705 // share same costructor (block) but they have they own resolve scope.
706 DeclSpace orig = ec.DeclContainer;
708 if (partial_parts != null) {
709 foreach (TypeContainer part in partial_parts) {
710 ec.DeclContainer = part;
711 part.DoResolveFieldInitializers (ec);
714 ec.DeclContainer = PartialContainer;
715 DoResolveFieldInitializers (ec);
716 ec.DeclContainer = orig;
719 void DoResolveFieldInitializers (EmitContext ec)
722 if (initialized_static_fields == null)
725 bool has_complex_initializer = false;
726 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
727 foreach (FieldInitializer fi in initialized_static_fields) {
728 fi.ResolveStatement (ec);
729 if (!fi.IsComplexInitializer)
732 has_complex_initializer = true;
735 // Need special check to not optimize code like this
736 // static int a = b = 5;
738 if (!has_complex_initializer && RootContext.Optimize) {
739 for (int i = 0; i < initialized_static_fields.Count; ++i) {
740 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
741 if (fi.IsDefaultInitializer) {
742 initialized_static_fields.RemoveAt (i);
752 if (initialized_fields == null)
755 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
756 for (int i = 0; i < initialized_fields.Count; ++i) {
757 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
758 fi.ResolveStatement (ec);
759 if (fi.IsDefaultInitializer && RootContext.Optimize) {
760 // Field is re-initialized to its default value => removed
761 initialized_fields.RemoveAt (i);
769 // Emits the instance field initializers
771 public bool EmitFieldInitializers (EmitContext ec)
773 if (partial_parts != null) {
774 foreach (TypeContainer part in partial_parts)
775 part.EmitFieldInitializers (ec);
781 fields = initialized_static_fields;
783 fields = initialized_fields;
789 foreach (FieldInitializer f in fields) {
790 f.EmitStatement (ec);
795 public override string DocComment {
807 public PendingImplementation PendingImplementations {
808 get { return pending; }
811 public override bool GetClsCompliantAttributeValue ()
813 if (PartialContainer != this)
814 return PartialContainer.GetClsCompliantAttributeValue ();
816 return base.GetClsCompliantAttributeValue ();
819 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
821 // FIXME: get rid of partial_parts and store lists of bases of each part here
822 // assumed, not verified: 'part' is in 'partial_parts'
823 ((TypeContainer) part).type_bases = bases;
826 TypeExpr[] GetNormalBases (out TypeExpr base_class)
829 if (type_bases == null)
832 int count = type_bases.Count;
835 if (Kind == Kind.Class){
836 TypeExpr name = ((Expression) type_bases [0]).ResolveAsBaseTerminal (this, false);
842 if (!name.IsInterface) {
843 // base_class could be a class, struct, enum, delegate.
844 // This is validated in GetClassBases.
850 TypeExpr [] ifaces = new TypeExpr [count-start];
852 for (i = start, j = 0; i < count; i++, j++){
853 TypeExpr resolved = ((Expression) type_bases [i]).ResolveAsBaseTerminal (this, false);
854 if (resolved == null) {
858 ifaces [j] = resolved;
861 return ifaces.Length == 0 ? null : ifaces;
865 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
867 ArrayList ifaces = new ArrayList (0);
868 if (iface_exprs != null)
869 ifaces.AddRange (iface_exprs);
871 foreach (TypeContainer part in partial_parts) {
872 TypeExpr new_base_class;
873 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
874 if (new_base_class != TypeManager.system_object_expr) {
875 if (base_class == TypeManager.system_object_expr)
876 base_class = new_base_class;
878 if (new_base_class != null && !new_base_class.Equals (base_class)) {
879 Report.SymbolRelatedToPreviousError (base_class.Location, "");
880 Report.Error (263, part.Location,
881 "Partial declarations of `{0}' must not specify different base classes",
882 part.GetSignatureForError ());
889 if (new_ifaces == null)
892 foreach (TypeExpr iface in new_ifaces) {
893 if (ifaces.Contains (iface))
900 if (ifaces.Count == 0)
903 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
907 /// This function computes the Base class and also the
908 /// list of interfaces that the class or struct @c implements.
910 /// The return value is an array (might be null) of
911 /// interfaces implemented (as Types).
913 /// The @base_class argument is set to the base object or null
914 /// if this is `System.Object'.
916 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
918 TypeExpr[] ifaces = GetNormalBases (out base_class);
923 int count = ifaces.Length;
925 for (int i = 0; i < count; i++) {
926 TypeExpr iface = (TypeExpr) ifaces [i];
928 if (!iface.IsInterface) {
929 if (Kind != Kind.Class) {
930 // TODO: location of symbol related ....
931 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
933 else if (base_class != null)
934 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
935 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
937 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
938 GetSignatureForError (), iface.GetSignatureForError ());
943 for (int x = 0; x < i; x++) {
944 if (iface.Equals (ifaces [x])) {
945 Report.Error (528, Location,
946 "`{0}' is already listed in " +
947 "interface list", iface.GetSignatureForError ());
952 if ((Kind == Kind.Interface) &&
953 !iface.AsAccessible (this)) {
954 Report.Error (61, Location,
955 "Inconsistent accessibility: base " +
956 "interface `{0}' is less accessible " +
957 "than interface `{1}'", iface.GetSignatureForError (),
965 bool CheckGenericInterfaces (Type[] ifaces)
968 ArrayList already_checked = new ArrayList ();
970 for (int i = 0; i < ifaces.Length; i++) {
971 Type iface = ifaces [i];
972 foreach (Type t in already_checked) {
976 Type[] inferred = new Type [CountTypeParameters];
977 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
980 Report.Error (695, Location,
981 "`{0}' cannot implement both `{1}' and `{2}' " +
982 "because they may unify for some type parameter substitutions",
983 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
984 TypeManager.CSharpName (t));
988 already_checked.Add (iface);
997 protected void Error_TypeInListIsNotInterface (Location loc, string type)
999 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1002 bool CreateTypeBuilder ()
1005 Type default_parent = null;
1006 if (Kind == Kind.Struct)
1007 default_parent = TypeManager.value_type;
1008 else if (Kind == Kind.Enum)
1009 default_parent = TypeManager.enum_type;
1012 if (TypeManager.NamespaceClash (Name, Location)) {
1016 ModuleBuilder builder = CodeGen.Module.Builder;
1017 TypeBuilder = builder.DefineType (
1018 Name, TypeAttr, default_parent, null);
1020 TypeBuilder builder = Parent.TypeBuilder;
1022 TypeBuilder = builder.DefineNestedType (
1023 Basename, TypeAttr, default_parent, null);
1025 } catch (ArgumentException) {
1026 Report.RuntimeMissingSupport (Location, "static classes");
1030 TypeManager.AddUserType (this);
1034 string[] param_names = new string [TypeParameters.Length];
1035 for (int i = 0; i < TypeParameters.Length; i++)
1036 param_names [i] = TypeParameters [i].Name;
1038 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
1040 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1041 for (int i = offset; i < gen_params.Length; i++)
1042 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1049 bool DefineBaseTypes ()
1051 iface_exprs = GetClassBases (out base_type);
1052 if (partial_parts != null) {
1053 iface_exprs = GetNormalPartialBases (ref base_type);
1057 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1058 // which in turn should have called DefineType()s on base types if necessary.
1060 // None of the code below should trigger DefineType()s on classes that we depend on.
1061 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1063 // Let's do it as soon as possible, since code below can call DefineType() on classes
1064 // that depend on us to be populated before they are.
1066 if (!(this is CompilerGeneratedClass))
1067 RootContext.RegisterOrder (this);
1069 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1070 Report.Error (698, base_type.Location,
1071 "A generic type cannot derive from `{0}' because it is an attribute class",
1072 base_type.GetSignatureForError ());
1076 if (!CheckRecursiveDefinition (this))
1079 if (base_type != null && base_type.Type != null) {
1080 TypeBuilder.SetParent (base_type.Type);
1082 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1083 if (obsolete_attr != null && !IsInObsoleteScope)
1084 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1087 // add interfaces that were not added at type creation
1088 if (iface_exprs != null) {
1089 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1093 foreach (Type itype in ifaces)
1094 TypeBuilder.AddInterfaceImplementation (itype);
1096 foreach (TypeExpr ie in iface_exprs) {
1097 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1098 if ((oa != null) && !IsInObsoleteScope)
1099 AttributeTester.Report_ObsoleteMessage (
1100 oa, ie.GetSignatureForError (), Location);
1103 if (!CheckGenericInterfaces (ifaces))
1106 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1113 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1115 public TypeBuilder CreateType ()
1117 if (TypeBuilder != null)
1123 if (!CreateTypeBuilder ()) {
1128 if (partial_parts != null) {
1129 foreach (TypeContainer part in partial_parts)
1130 part.TypeBuilder = TypeBuilder;
1133 if (Types != null) {
1134 foreach (TypeContainer tc in Types) {
1135 if (tc.CreateType () == null) {
1147 public override TypeBuilder DefineType ()
1154 type_defined = true;
1156 if (CreateType () == null) {
1161 if (!DefineBaseTypes ()) {
1166 if (!ResolveMembers ()) {
1171 if (!DefineNestedTypes ()) {
1179 bool ResolveMembers ()
1181 if (members_resolved)
1182 return members_resolved_ok;
1184 members_resolved_ok = DoResolveMembers ();
1185 members_resolved = true;
1187 return members_resolved_ok;
1190 protected virtual bool DoResolveMembers ()
1192 if (methods != null) {
1193 foreach (Method method in methods) {
1194 if (!method.ResolveMembers ())
1199 // TODO: this is not really needed
1200 if (operators != null) {
1201 foreach (Operator o in operators) {
1202 if (!o.ResolveMembers ())
1210 public override void SetParameterInfo (ArrayList constraints_list)
1212 base.SetParameterInfo (constraints_list);
1214 if (!is_generic || PartialContainer == this)
1217 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1218 for (int i = 0; i < tc_names.Length; ++i) {
1219 if (tc_names [i].Name != type_params [i].Name) {
1220 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1221 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1222 GetSignatureForError ());
1228 void UpdateTypeParameterConstraints (TypeContainer part)
1230 TypeParameter[] current_params = CurrentTypeParameters;
1231 for (int i = 0; i < current_params.Length; i++) {
1232 Constraints c = part.CurrentTypeParameters [i].Constraints;
1236 if (current_params [i].UpdateConstraints (part, c))
1239 Report.SymbolRelatedToPreviousError (Location, "");
1240 Report.Error (265, part.Location,
1241 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1242 GetSignatureForError (), current_params [i].GetSignatureForError ());
1246 public bool ResolveType ()
1248 if (!DoResolveType ())
1251 if (compiler_generated != null) {
1252 foreach (CompilerGeneratedClass c in compiler_generated)
1253 if (!c.ResolveType ())
1260 protected virtual bool DoResolveType ()
1262 if ((base_type != null) &&
1263 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1271 if (PartialContainer != this)
1272 throw new InternalErrorException ();
1274 TypeExpr current_type = null;
1276 foreach (TypeParameter type_param in CurrentTypeParameters) {
1277 if (!type_param.Resolve (this)) {
1283 if (partial_parts != null && is_generic) {
1284 foreach (TypeContainer part in partial_parts)
1285 UpdateTypeParameterConstraints (part);
1288 foreach (TypeParameter type_param in TypeParameters) {
1289 if (!type_param.DefineType (this)) {
1295 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1297 foreach (TypeParameter type_param in TypeParameters)
1298 if (!type_param.CheckDependencies ()) {
1303 if (current_type != null) {
1304 current_type = current_type.ResolveAsTypeTerminal (this, false);
1305 if (current_type == null) {
1310 CurrentType = current_type.Type;
1316 protected virtual bool DefineNestedTypes ()
1318 if (Types != null) {
1319 foreach (TypeContainer tc in Types)
1320 if (tc.DefineType () == null)
1324 if (Delegates != null) {
1325 foreach (Delegate d in Delegates)
1326 if (d.DefineType () == null)
1333 TypeContainer InTransit;
1335 protected bool CheckRecursiveDefinition (TypeContainer tc)
1337 if (InTransit != null) {
1338 Report.SymbolRelatedToPreviousError (this);
1339 if (this is Interface)
1341 529, tc.Location, "Inherited interface `{0}' causes a " +
1342 "cycle in the interface hierarchy of `{1}'",
1343 GetSignatureForError (), tc.GetSignatureForError ());
1346 146, tc.Location, "Circular base class dependency " +
1347 "involving `{0}' and `{1}'",
1348 tc.GetSignatureForError (), GetSignatureForError ());
1354 if (base_type != null && base_type.Type != null) {
1355 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1356 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1357 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1361 if (iface_exprs != null) {
1362 foreach (TypeExpr iface in iface_exprs) {
1363 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1364 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1365 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1370 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1377 public static void Error_KeywordNotAllowed (Location loc)
1379 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1383 /// Populates our TypeBuilder with fields and methods
1385 public override bool DefineMembers ()
1387 if (members_defined)
1388 return members_defined_ok;
1390 if (!base.DefineMembers ())
1393 members_defined_ok = DoDefineMembers ();
1394 members_defined = true;
1396 return members_defined_ok;
1399 protected virtual bool DoDefineMembers ()
1401 if (iface_exprs != null) {
1402 foreach (TypeExpr iface in iface_exprs) {
1403 ConstructedType ct = iface as ConstructedType;
1404 if ((ct != null) && !ct.CheckConstraints (this))
1409 if (base_type != null) {
1410 ConstructedType ct = base_type as ConstructedType;
1411 if ((ct != null) && !ct.CheckConstraints (this))
1414 member_cache = new MemberCache (base_type.Type, this);
1415 } else if (Kind == Kind.Interface) {
1416 member_cache = new MemberCache (null, this);
1417 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1418 for (int i = 0; i < ifaces.Length; ++i)
1419 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1421 member_cache = new MemberCache (null, this);
1425 foreach (TypeContainer tc in types)
1426 member_cache.AddNestedType (tc);
1428 if (delegates != null)
1429 foreach (Delegate d in delegates)
1430 member_cache.AddNestedType (d);
1432 if (partial_parts != null) {
1433 foreach (TypeContainer part in partial_parts)
1434 part.member_cache = member_cache;
1438 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1439 if (conflict_symbol == null) {
1440 if ((ModFlags & Modifiers.NEW) != 0)
1441 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1443 if ((ModFlags & Modifiers.NEW) == 0) {
1444 Report.SymbolRelatedToPreviousError (conflict_symbol);
1445 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1446 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1451 DefineContainerMembers (constants);
1452 DefineContainerMembers (fields);
1454 if (Kind == Kind.Struct || Kind == Kind.Class) {
1455 pending = PendingImplementation.GetPendingImplementations (this);
1459 // Constructors are not in the defined_names array
1461 DefineContainerMembers (instance_constructors);
1463 DefineContainerMembers (events);
1464 DefineContainerMembers (ordered_explicit_member_list);
1465 DefineContainerMembers (ordered_member_list);
1467 DefineContainerMembers (operators);
1468 DefineContainerMembers (delegates);
1470 ComputeIndexerName();
1471 CheckEqualsAndGetHashCode();
1473 if (CurrentType != null) {
1474 GenericType = CurrentType;
1479 // FIXME: This hack is needed because member cache does not work
1480 // with generic types, we rely on runtime to inflate dynamic types.
1481 // TODO: This hack requires member cache refactoring to be removed
1483 if (TypeBuilder.IsGenericType)
1484 member_cache = new MemberCache (this);
1490 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1493 mcal.DefineContainerMembers ();
1496 protected virtual void ComputeIndexerName ()
1498 if (indexers == null)
1501 string class_indexer_name = null;
1504 // If there's both an explicit and an implicit interface implementation, the
1505 // explicit one actually implements the interface while the other one is just
1506 // a normal indexer. See bug #37714.
1509 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1510 foreach (Indexer i in indexers) {
1511 if (i.InterfaceType != null) {
1512 if (seen_normal_indexers)
1513 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1517 seen_normal_indexers = true;
1519 if (class_indexer_name == null) {
1520 class_indexer_name = i.ShortName;
1524 if (i.ShortName != class_indexer_name)
1525 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");
1528 if (class_indexer_name != null)
1529 indexer_name = class_indexer_name;
1532 protected virtual void EmitIndexerName ()
1534 if (!seen_normal_indexers)
1537 if (TypeManager.default_member_ctor == null) {
1538 if (TypeManager.default_member_type == null) {
1539 TypeManager.default_member_type = TypeManager.CoreLookupType (
1540 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1542 if (TypeManager.default_member_type == null)
1546 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1547 TypeManager.default_member_type, Location, TypeManager.string_type);
1549 if (TypeManager.default_member_ctor == null)
1553 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1554 TypeBuilder.SetCustomAttribute (cb);
1557 protected virtual void CheckEqualsAndGetHashCode ()
1559 if (methods == null)
1562 if (HasEquals && !HasGetHashCode) {
1563 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1567 public override bool Define ()
1569 CheckProtectedModifier ();
1573 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1575 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1579 /// This function is based by a delegate to the FindMembers routine
1581 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1587 /// This filter is used by FindMembers, and we just keep
1588 /// a global for the filter to `AlwaysAccept'
1590 static MemberFilter accepting_filter;
1593 static TypeContainer ()
1595 accepting_filter = new MemberFilter (AlwaysAccept);
1598 public MethodInfo[] GetMethods ()
1600 ArrayList members = new ArrayList ();
1604 if (methods != null) {
1605 int len = methods.Count;
1606 for (int i = 0; i < len; i++) {
1607 Method m = (Method) methods [i];
1609 members.Add (m.MethodBuilder);
1613 if (operators != null) {
1614 int len = operators.Count;
1615 for (int i = 0; i < len; i++) {
1616 Operator o = (Operator) operators [i];
1618 members.Add (o.MethodBuilder);
1622 if (properties != null) {
1623 int len = properties.Count;
1624 for (int i = 0; i < len; i++) {
1625 Property p = (Property) properties [i];
1627 if (p.GetBuilder != null)
1628 members.Add (p.GetBuilder);
1629 if (p.SetBuilder != null)
1630 members.Add (p.SetBuilder);
1634 if (indexers != null) {
1635 int len = indexers.Count;
1636 for (int i = 0; i < len; i++) {
1637 Indexer ix = (Indexer) indexers [i];
1639 if (ix.GetBuilder != null)
1640 members.Add (ix.GetBuilder);
1641 if (ix.SetBuilder != null)
1642 members.Add (ix.SetBuilder);
1646 if (events != null) {
1647 int len = events.Count;
1648 for (int i = 0; i < len; i++) {
1649 Event e = (Event) events [i];
1651 if (e.AddBuilder != null)
1652 members.Add (e.AddBuilder);
1653 if (e.RemoveBuilder != null)
1654 members.Add (e.RemoveBuilder);
1658 MethodInfo[] retMethods = new MethodInfo [members.Count];
1659 members.CopyTo (retMethods, 0);
1663 // Indicated whether container has StructLayout attribute set Explicit
1664 public bool HasExplicitLayout {
1665 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1666 set { caching_flags |= Flags.HasExplicitLayout; }
1670 // Return the nested type with name @name. Ensures that the nested type
1671 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1673 public Type FindNestedType (string name)
1675 if (PartialContainer != this)
1676 throw new InternalErrorException ("should not happen");
1678 ArrayList [] lists = { types, delegates };
1680 for (int j = 0; j < lists.Length; ++j) {
1681 ArrayList list = lists [j];
1685 int len = list.Count;
1686 for (int i = 0; i < len; ++i) {
1687 DeclSpace ds = (DeclSpace) list [i];
1688 if (ds.Basename == name) {
1689 return ds.DefineType ();
1697 private void FindMembers_NestedTypes (int modflags,
1698 BindingFlags bf, MemberFilter filter, object criteria,
1699 ref ArrayList members)
1701 ArrayList [] lists = { types, delegates };
1703 for (int j = 0; j < lists.Length; ++j) {
1704 ArrayList list = lists [j];
1708 int len = list.Count;
1709 for (int i = 0; i < len; i++) {
1710 DeclSpace ds = (DeclSpace) list [i];
1712 if ((ds.ModFlags & modflags) == 0)
1715 TypeBuilder tb = ds.TypeBuilder;
1717 if (!(criteria is string) || ds.Basename.Equals (criteria))
1718 tb = ds.DefineType ();
1721 if (tb != null && (filter (tb, criteria) == true)) {
1722 if (members == null)
1723 members = new ArrayList ();
1732 /// This method returns the members of this type just like Type.FindMembers would
1733 /// Only, we need to use this for types which are _being_ defined because MS'
1734 /// implementation can't take care of that.
1737 // FIXME: return an empty static array instead of null, that cleans up
1738 // some code and is consistent with some coding conventions I just found
1742 // Notice that in various cases we check if our field is non-null,
1743 // something that would normally mean that there was a bug elsewhere.
1745 // The problem happens while we are defining p-invoke methods, as those
1746 // will trigger a FindMembers, but this happens before things are defined
1748 // Since the whole process is a no-op, it is fine to check for null here.
1750 // TODO: This approach will be one day completely removed, it's already
1751 // used at few places only
1754 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1755 MemberFilter filter, object criteria)
1757 ArrayList members = null;
1760 if ((bf & BindingFlags.Public) != 0)
1761 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1763 if ((bf & BindingFlags.NonPublic) != 0)
1764 modflags |= Modifiers.PRIVATE;
1766 int static_mask = 0, static_flags = 0;
1767 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1768 case BindingFlags.Static:
1769 static_mask = static_flags = Modifiers.STATIC;
1772 case BindingFlags.Instance:
1773 static_mask = Modifiers.STATIC;
1778 static_mask = static_flags = 0;
1782 Timer.StartTimer (TimerType.TcFindMembers);
1785 filter = accepting_filter;
1787 if ((mt & MemberTypes.Field) != 0) {
1788 if (fields != null) {
1789 int len = fields.Count;
1790 for (int i = 0; i < len; i++) {
1791 FieldBase f = (FieldBase) fields [i];
1793 if ((f.ModFlags & modflags) == 0)
1795 if ((f.ModFlags & static_mask) != static_flags)
1798 FieldBuilder fb = f.FieldBuilder;
1799 if (fb != null && filter (fb, criteria) == true) {
1800 if (members == null)
1801 members = new ArrayList ();
1808 if (constants != null) {
1809 int len = constants.Count;
1810 for (int i = 0; i < len; i++) {
1811 Const con = (Const) constants [i];
1813 if ((con.ModFlags & modflags) == 0)
1815 if ((con.ModFlags & static_mask) != static_flags)
1818 FieldBuilder fb = con.FieldBuilder;
1821 fb = con.FieldBuilder;
1823 if (fb != null && filter (fb, criteria) == true) {
1824 if (members == null)
1825 members = new ArrayList ();
1833 if ((mt & MemberTypes.Method) != 0) {
1834 if (methods != null) {
1835 int len = methods.Count;
1836 for (int i = 0; i < len; i++) {
1837 Method m = (Method) methods [i];
1839 if ((m.ModFlags & modflags) == 0)
1841 if ((m.ModFlags & static_mask) != static_flags)
1844 MethodBuilder mb = m.MethodBuilder;
1846 if (mb != null && filter (mb, criteria) == true) {
1847 if (members == null)
1848 members = new ArrayList ();
1855 if (operators != null) {
1856 int len = operators.Count;
1857 for (int i = 0; i < len; i++) {
1858 Operator o = (Operator) operators [i];
1860 if ((o.ModFlags & modflags) == 0)
1862 if ((o.ModFlags & static_mask) != static_flags)
1865 MethodBuilder ob = o.MethodBuilder;
1866 if (ob != null && filter (ob, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1875 if (events != null) {
1876 foreach (Event e in events) {
1877 if ((e.ModFlags & modflags) == 0)
1879 if ((e.ModFlags & static_mask) != static_flags)
1882 MethodBuilder b = e.AddBuilder;
1883 if (b != null && filter (b, criteria)) {
1884 if (members == null)
1885 members = new ArrayList (4);
1890 b = e.RemoveBuilder;
1891 if (b != null && filter (b, criteria)) {
1892 if (members == null)
1893 members = new ArrayList (4);
1900 if (properties != null) {
1901 int len = properties.Count;
1902 for (int i = 0; i < len; i++) {
1903 Property p = (Property) properties [i];
1905 if ((p.ModFlags & modflags) == 0)
1907 if ((p.ModFlags & static_mask) != static_flags)
1913 if (b != null && filter (b, criteria) == true) {
1914 if (members == null)
1915 members = new ArrayList ();
1921 if (b != null && filter (b, criteria) == true) {
1922 if (members == null)
1923 members = new ArrayList ();
1930 if (indexers != null) {
1931 int len = indexers.Count;
1932 for (int i = 0; i < len; i++) {
1933 Indexer ix = (Indexer) indexers [i];
1935 if ((ix.ModFlags & modflags) == 0)
1937 if ((ix.ModFlags & static_mask) != static_flags)
1943 if (b != null && filter (b, criteria) == true) {
1944 if (members == null)
1945 members = new ArrayList ();
1951 if (b != null && filter (b, criteria) == true) {
1952 if (members == null)
1953 members = new ArrayList ();
1961 if ((mt & MemberTypes.Event) != 0) {
1962 if (events != null) {
1963 int len = events.Count;
1964 for (int i = 0; i < len; i++) {
1965 Event e = (Event) events [i];
1967 if ((e.ModFlags & modflags) == 0)
1969 if ((e.ModFlags & static_mask) != static_flags)
1972 MemberInfo eb = e.EventBuilder;
1973 if (eb != null && filter (eb, criteria) == true) {
1974 if (members == null)
1975 members = new ArrayList ();
1977 members.Add (e.EventBuilder);
1983 if ((mt & MemberTypes.Property) != 0){
1984 if (properties != null) {
1985 int len = properties.Count;
1986 for (int i = 0; i < len; i++) {
1987 Property p = (Property) properties [i];
1989 if ((p.ModFlags & modflags) == 0)
1991 if ((p.ModFlags & static_mask) != static_flags)
1994 MemberInfo pb = p.PropertyBuilder;
1995 if (pb != null && filter (pb, criteria) == true) {
1996 if (members == null)
1997 members = new ArrayList ();
1999 members.Add (p.PropertyBuilder);
2004 if (indexers != null) {
2005 int len = indexers.Count;
2006 for (int i = 0; i < len; i++) {
2007 Indexer ix = (Indexer) indexers [i];
2009 if ((ix.ModFlags & modflags) == 0)
2011 if ((ix.ModFlags & static_mask) != static_flags)
2014 MemberInfo ib = ix.PropertyBuilder;
2015 if (ib != null && filter (ib, criteria) == true) {
2016 if (members == null)
2017 members = new ArrayList ();
2019 members.Add (ix.PropertyBuilder);
2025 if ((mt & MemberTypes.NestedType) != 0)
2026 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2028 if ((mt & MemberTypes.Constructor) != 0){
2029 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2030 int len = instance_constructors.Count;
2031 for (int i = 0; i < len; i++) {
2032 Constructor c = (Constructor) instance_constructors [i];
2034 ConstructorBuilder cb = c.ConstructorBuilder;
2035 if (cb != null && filter (cb, criteria) == true) {
2036 if (members == null)
2037 members = new ArrayList ();
2044 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2045 ConstructorBuilder cb =
2046 default_static_constructor.ConstructorBuilder;
2048 if (cb != null && filter (cb, criteria) == true) {
2049 if (members == null)
2050 members = new ArrayList ();
2058 // Lookup members in base if requested.
2060 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2061 if (TypeBuilder.BaseType != null) {
2062 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2063 if (list.Count > 0) {
2064 if (members == null)
2065 members = new ArrayList ();
2067 members.AddRange (list);
2072 Timer.StopTimer (TimerType.TcFindMembers);
2074 if (members == null)
2075 return MemberList.Empty;
2077 return new MemberList (members);
2080 public override MemberCache MemberCache {
2082 return member_cache;
2086 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2087 MemberFilter filter, object criteria)
2089 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2092 return ds.FindMembers (mt, bf, filter, criteria);
2094 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2098 /// Emits the values for the constants
2100 public void EmitConstants ()
2102 if (constants != null)
2103 foreach (Const con in constants)
2108 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2113 foreach (MemberCore mc in al) {
2114 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2117 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2118 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2123 public virtual void VerifyMembers ()
2126 // Check for internal or private fields that were never assigned
2128 if (Report.WarningLevel >= 3) {
2129 CheckMemberUsage (properties, "property");
2130 CheckMemberUsage (methods, "method");
2131 CheckMemberUsage (constants, "constant");
2133 if (fields != null){
2134 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2135 foreach (FieldBase f in fields) {
2136 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2137 if (is_type_exposed)
2140 f.SetMemberIsUsed ();
2144 if ((f.caching_flags & Flags.IsAssigned) == 0)
2145 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2148 const int error_code = 414;
2150 const int error_code = 169;
2152 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2153 f.GetSignatureForError ());
2159 // Only report 649 on level 4
2161 if (Report.WarningLevel < 4)
2164 if ((f.caching_flags & Flags.IsAssigned) != 0)
2167 Constant c = New.Constantify (f.MemberType);
2168 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2169 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2175 // TODO: move to ClassOrStruct
2176 void EmitConstructors ()
2178 if (instance_constructors == null)
2181 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2182 bool has_compliant_args = false;
2184 foreach (Constructor c in instance_constructors) {
2188 catch (Exception e) {
2189 throw new InternalErrorException (c, e);
2192 if (has_compliant_args)
2195 has_compliant_args = c.HasCompliantArgs;
2197 if (!has_compliant_args)
2198 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2200 foreach (Constructor c in instance_constructors) {
2204 catch (Exception e) {
2205 throw new InternalErrorException (c, e);
2212 /// Emits the code, this step is performed after all
2213 /// the types, enumerations, constructors
2215 public virtual void EmitType ()
2217 if (OptAttributes != null)
2218 OptAttributes.Emit ();
2221 // Structs with no fields need to have at least one byte.
2222 // The right thing would be to set the PackingSize in a DefineType
2223 // but there are no functions that allow interfaces *and* the size to
2227 if (Kind == Kind.Struct && first_nonstatic_field == null){
2228 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2229 FieldAttributes.Private);
2231 if (HasExplicitLayout){
2232 object [] ctor_args = new object [] { 0 };
2234 if (TypeManager.field_offset_attribute_ctor == null) {
2236 if (TypeManager.field_offset_attribute_type == null) {
2237 TypeManager.field_offset_attribute_type = TypeManager.CoreLookupType (
2238 "System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, true);
2241 TypeManager.field_offset_attribute_ctor = TypeManager.GetPredefinedConstructor (
2242 TypeManager.field_offset_attribute_type, Location, TypeManager.int32_type);
2245 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2246 TypeManager.field_offset_attribute_ctor, ctor_args);
2247 fb.SetCustomAttribute (cba);
2253 EmitConstructors ();
2255 // Can not continue if constants are broken
2257 if (Report.Errors > 0)
2260 if (default_static_constructor != null)
2261 default_static_constructor.Emit ();
2263 if (operators != null)
2264 foreach (Operator o in operators)
2267 if (properties != null)
2268 foreach (Property p in properties)
2271 if (indexers != null) {
2272 foreach (Indexer indx in indexers)
2277 if (events != null){
2278 foreach (Event e in Events)
2282 if (methods != null) {
2283 for (int i = 0; i < methods.Count; ++i)
2284 ((Method) methods [i]).Emit ();
2288 foreach (FieldBase f in fields)
2291 if (delegates != null) {
2292 foreach (Delegate d in Delegates) {
2297 if (pending != null)
2298 if (pending.VerifyPendingMethods ())
2301 if (Report.Errors > 0)
2304 if (compiler_generated != null) {
2305 foreach (CompilerGeneratedClass c in compiler_generated)
2310 public override void CloseType ()
2312 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2316 caching_flags |= Flags.CloseTypeCreated;
2317 TypeBuilder.CreateType ();
2318 } catch (TypeLoadException){
2320 // This is fine, the code still created the type
2322 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2323 // Console.WriteLine (e.Message);
2324 } catch (Exception e) {
2325 throw new InternalErrorException (this, e);
2329 foreach (TypeContainer tc in Types)
2330 if (tc.Kind == Kind.Struct)
2333 foreach (TypeContainer tc in Types)
2334 if (tc.Kind != Kind.Struct)
2338 if (Delegates != null)
2339 foreach (Delegate d in Delegates)
2342 if (compiler_generated != null)
2343 foreach (CompilerGeneratedClass c in compiler_generated)
2350 initialized_fields = null;
2351 initialized_static_fields = null;
2353 ordered_explicit_member_list = null;
2354 ordered_member_list = null;
2359 compiler_generated = null;
2360 default_constructor = null;
2361 default_static_constructor = null;
2363 OptAttributes = null;
2366 member_cache = null;
2370 // Performs the validation on a Method's modifiers (properties have
2371 // the same properties).
2373 public bool MethodModifiersValid (MemberCore mc)
2375 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2376 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2377 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2379 int flags = mc.ModFlags;
2382 // At most one of static, virtual or override
2384 if ((flags & Modifiers.STATIC) != 0){
2385 if ((flags & vao) != 0){
2386 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2387 mc.GetSignatureForError ());
2392 if (Kind == Kind.Struct){
2393 if ((flags & va) != 0){
2394 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2399 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2400 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2401 mc.GetSignatureForError ());
2406 // If the declaration includes the abstract modifier, then the
2407 // declaration does not include static, virtual or extern
2409 if ((flags & Modifiers.ABSTRACT) != 0){
2410 if ((flags & Modifiers.EXTERN) != 0){
2412 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2416 if ((flags & Modifiers.SEALED) != 0) {
2417 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2421 if ((flags & Modifiers.VIRTUAL) != 0){
2422 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2426 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2427 Report.SymbolRelatedToPreviousError (this);
2428 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2429 mc.GetSignatureForError (), GetSignatureForError ());
2434 if ((flags & Modifiers.PRIVATE) != 0){
2435 if ((flags & vao) != 0){
2436 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2441 if ((flags & Modifiers.SEALED) != 0){
2442 if ((flags & Modifiers.OVERRIDE) == 0){
2443 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2451 public Constructor DefaultStaticConstructor {
2452 get { return default_static_constructor; }
2455 protected override bool VerifyClsCompliance ()
2457 if (!base.VerifyClsCompliance ())
2462 Type base_type = TypeBuilder.BaseType;
2463 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2464 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2471 /// Checks whether container name is CLS Compliant
2473 void VerifyClsName ()
2475 Hashtable base_members = base_cache == null ?
2477 base_cache.GetPublicMembers ();
2478 Hashtable this_members = new Hashtable ();
2480 foreach (DictionaryEntry entry in defined_names) {
2481 MemberCore mc = (MemberCore)entry.Value;
2482 if (!mc.IsClsComplianceRequired ())
2485 string name = (string) entry.Key;
2486 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2488 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2489 object found = base_members [lcase];
2490 if (found == null) {
2491 found = this_members [lcase];
2492 if (found == null) {
2493 this_members.Add (lcase, mc);
2498 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2501 if (found is MemberInfo) {
2502 if (basename == ((MemberInfo) found).Name)
2504 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2506 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2509 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2511 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2518 /// Performs checks for an explicit interface implementation. First it
2519 /// checks whether the `interface_type' is a base inteface implementation.
2520 /// Then it checks whether `name' exists in the interface type.
2522 public bool VerifyImplements (InterfaceMemberBase mb)
2524 if (ifaces != null) {
2525 foreach (Type t in ifaces){
2526 if (TypeManager.IsEqual (t, mb.InterfaceType))
2531 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2532 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2533 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2537 public override Type LookupAnyGeneric (string typeName)
2539 if (types != null) {
2540 foreach (TypeContainer tc in types) {
2544 int pos = tc.Basename.LastIndexOf ('`');
2545 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2546 return tc.TypeBuilder;
2550 return base.LookupAnyGeneric (typeName);
2553 public void Mark_HasEquals ()
2555 cached_method |= CachedMethods.Equals;
2558 public void Mark_HasGetHashCode ()
2560 cached_method |= CachedMethods.GetHashCode;
2564 /// Method container contains Equals method
2566 public bool HasEquals {
2568 return (cached_method & CachedMethods.Equals) != 0;
2573 /// Method container contains GetHashCode method
2575 public bool HasGetHashCode {
2577 return (cached_method & CachedMethods.GetHashCode) != 0;
2581 public bool HasStaticFieldInitializer {
2583 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2587 cached_method |= CachedMethods.HasStaticFieldInitializer;
2589 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2597 string IMemberContainer.Name {
2603 Type IMemberContainer.Type {
2609 bool IMemberContainer.IsInterface {
2611 return Kind == Kind.Interface;
2615 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2617 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2619 if (GenericType != null)
2620 return TypeManager.FindMembers (GenericType, mt, new_bf,
2623 return FindMembers (mt, new_bf, null, null);
2627 // Generates xml doc comments (if any), and if required,
2628 // handle warning report.
2630 internal override void GenerateDocComment (DeclSpace ds)
2632 DocUtil.GenerateTypeDocComment (this, ds);
2635 public override string DocCommentHeader {
2636 get { return "T:"; }
2639 public MemberCache BaseCache {
2641 if (base_cache != null)
2643 if (TypeBuilder.BaseType != null)
2644 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2645 if (TypeBuilder.IsInterface)
2646 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2652 public abstract class ClassOrStruct : TypeContainer {
2653 ListDictionary declarative_security;
2655 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2656 MemberName name, Attributes attrs, Kind kind)
2657 : base (ns, parent, name, attrs, kind)
2661 protected override bool AddToContainer (MemberCore symbol, string name)
2663 if (name == MemberName.Name) {
2664 if (symbol is TypeParameter) {
2665 Report.Error (694, symbol.Location,
2666 "Type parameter `{0}' has same name as " +
2667 "containing type, or method", name);
2671 Report.SymbolRelatedToPreviousError (this);
2672 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2673 symbol.GetSignatureForError ());
2677 return base.AddToContainer (symbol, name);
2680 public override void VerifyMembers ()
2682 base.VerifyMembers ();
2684 if ((events != null) && Report.WarningLevel >= 3) {
2685 foreach (Event e in events){
2686 // Note: The event can be assigned from same class only, so we can report
2687 // this warning for all accessibility modes
2688 if ((e.caching_flags & Flags.IsUsed) == 0)
2689 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2694 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2696 if (a.IsValidSecurityAttribute ()) {
2697 if (declarative_security == null)
2698 declarative_security = new ListDictionary ();
2700 a.ExtractSecurityPermissionSet (declarative_security);
2704 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2705 PartialContainer.HasExplicitLayout = true;
2708 base.ApplyAttributeBuilder (a, cb);
2712 /// Defines the default constructors
2714 protected void DefineDefaultConstructor (bool is_static)
2716 // The default instance constructor is public
2717 // If the class is abstract, the default constructor is protected
2718 // The default static constructor is private
2722 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2724 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2727 Constructor c = new Constructor (this, MemberName.Name, mods,
2728 Parameters.EmptyReadOnlyParameters,
2729 new GeneratedBaseInitializer (Location),
2733 c.Block = new ToplevelBlock (null, Location);
2736 public override bool Define ()
2738 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2739 DefineDefaultConstructor (true);
2741 if (default_static_constructor != null)
2742 default_static_constructor.Define ();
2744 return base.Define ();
2747 public override void Emit ()
2751 if (declarative_security != null) {
2752 foreach (DictionaryEntry de in declarative_security) {
2753 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2758 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2760 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2763 protected override TypeAttributes TypeAttr {
2765 if (default_static_constructor == null)
2766 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2768 return base.TypeAttr;
2774 // TODO: should be sealed
2775 public class Class : ClassOrStruct {
2776 const int AllowedModifiers =
2779 Modifiers.PROTECTED |
2780 Modifiers.INTERNAL |
2782 Modifiers.ABSTRACT |
2787 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2789 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2791 : base (ns, parent, name, attrs, Kind.Class)
2793 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2794 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2796 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2797 Report.FeatureIsNotAvailable (Location, "static classes");
2801 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2803 if (part.Name == "System.Object")
2804 Report.Error (537, part.Location,
2805 "The class System.Object cannot have a base class or implement an interface.");
2806 base.AddBasesForPart (part, bases);
2809 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2811 if (a.Type == TypeManager.attribute_usage_type) {
2812 if (!TypeManager.IsAttributeType (BaseType) &&
2813 TypeBuilder.FullName != "System.Attribute") {
2814 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2818 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2819 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2823 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2824 !attributes.Contains (TypeManager.guid_attr_type)) {
2825 a.Error_MissingGuidAttribute ();
2829 if (a.Type == TypeManager.extension_attribute_type) {
2830 a.Error_MisusedExtensionAttribute ();
2834 if (AttributeTester.IsAttributeExcluded (a.Type))
2837 base.ApplyAttributeBuilder (a, cb);
2840 public override AttributeTargets AttributeTargets {
2842 return AttributeTargets.Class;
2846 protected override void DefineContainerMembers (MemberCoreArrayList list)
2852 base.DefineContainerMembers (list);
2856 foreach (MemberCore m in list) {
2857 if (m is Operator) {
2858 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2862 if (m is Destructor) {
2863 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2867 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2868 m.CheckProtectedModifier ();
2873 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2877 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2880 if (m is Constructor) {
2881 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2885 Method method = m as Method;
2886 if (method != null && method.Parameters.HasExtensionMethodType) {
2887 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2891 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2894 base.DefineContainerMembers (list);
2897 public override TypeBuilder DefineType ()
2899 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2900 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2904 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2905 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2909 return base.DefineType ();
2912 protected override bool DoDefineMembers ()
2914 if (InstanceConstructors == null && !IsStatic)
2915 DefineDefaultConstructor (false);
2917 return base.DoDefineMembers ();
2920 public override void Emit ()
2925 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2926 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2930 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2932 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2934 if (base_class == null) {
2935 if (RootContext.StdLib)
2936 base_class = TypeManager.system_object_expr;
2937 else if (Name != "System.Object")
2938 base_class = TypeManager.system_object_expr;
2940 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2942 689, base_class.Location,
2943 "Cannot derive from `{0}' because it is a type parameter",
2944 base_class.GetSignatureForError ());
2948 if (base_class.IsSealed){
2949 Report.SymbolRelatedToPreviousError (base_class.Type);
2950 if (base_class.Type.IsAbstract) {
2951 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2952 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2954 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2955 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2960 if (!base_class.CanInheritFrom ()){
2961 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2962 GetSignatureForError (), base_class.GetSignatureForError ());
2966 if (!base_class.AsAccessible (this)) {
2967 Report.SymbolRelatedToPreviousError (base_class.Type);
2968 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2969 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2973 if (PartialContainer.IsStaticClass) {
2974 if (base_class.Type != TypeManager.object_type) {
2975 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2976 GetSignatureForError (), base_class.GetSignatureForError ());
2980 if (ifaces != null) {
2981 foreach (TypeExpr t in ifaces)
2982 Report.SymbolRelatedToPreviousError (t.Type);
2983 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2990 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2991 /// Valid only for attribute classes.
2992 public bool IsExcluded ()
2994 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2995 return (caching_flags & Flags.Excluded) != 0;
2997 caching_flags &= ~Flags.Excluded_Undetected;
2999 if (OptAttributes == null)
3002 if (TypeManager.conditional_attribute_type == null)
3005 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3010 foreach (Attribute a in attrs) {
3011 string condition = a.GetConditionalAttributeValue ();
3012 if (RootContext.AllDefines.Contains (condition))
3016 caching_flags |= Flags.Excluded;
3022 return (ModFlags & Modifiers.STATIC) != 0;
3027 // FIXME: How do we deal with the user specifying a different
3030 protected override TypeAttributes TypeAttr {
3032 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3034 ta |= StaticClassAttribute;
3040 public sealed class Struct : ClassOrStruct {
3042 // Modifiers allowed in a struct declaration
3044 const int AllowedModifiers =
3047 Modifiers.PROTECTED |
3048 Modifiers.INTERNAL |
3052 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3053 int mod, Attributes attrs)
3054 : base (ns, parent, name, attrs, Kind.Struct)
3058 if (parent.Parent == null)
3059 accmods = Modifiers.INTERNAL;
3061 accmods = Modifiers.PRIVATE;
3063 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3065 this.ModFlags |= Modifiers.SEALED;
3068 public override AttributeTargets AttributeTargets {
3070 return AttributeTargets.Struct;
3074 const TypeAttributes DefaultTypeAttributes =
3075 TypeAttributes.SequentialLayout |
3076 TypeAttributes.Sealed |
3077 TypeAttributes.BeforeFieldInit;
3080 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3082 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3084 // If we are compiling our runtime,
3085 // and we are defining ValueType, then our
3086 // base is `System.Object'.
3088 if (base_class == null) {
3089 if (!RootContext.StdLib && Name == "System.ValueType")
3090 base_class = TypeManager.system_object_expr;
3092 base_class = TypeManager.system_valuetype_expr;
3099 // FIXME: Allow the user to specify a different set of attributes
3100 // in some cases (Sealed for example is mandatory for a class,
3101 // but what SequentialLayout can be changed
3103 protected override TypeAttributes TypeAttr {
3105 return base.TypeAttr | DefaultTypeAttributes;
3109 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3111 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3112 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3113 field.GetSignatureForError ());
3116 base.RegisterFieldForInitialization (field, expression);
3124 public sealed class Interface : TypeContainer, IMemberContainer {
3127 /// Modifiers allowed in a class declaration
3129 public const int AllowedModifiers =
3132 Modifiers.PROTECTED |
3133 Modifiers.INTERNAL |
3137 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3139 : base (ns, parent, name, attrs, Kind.Interface)
3143 if (parent.Parent == null)
3144 accmods = Modifiers.INTERNAL;
3146 accmods = Modifiers.PRIVATE;
3148 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3151 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3153 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3154 !attributes.Contains (TypeManager.guid_attr_type)) {
3155 a.Error_MissingGuidAttribute ();
3158 base.ApplyAttributeBuilder (a, cb);
3162 public override AttributeTargets AttributeTargets {
3164 return AttributeTargets.Interface;
3168 const TypeAttributes DefaultTypeAttributes =
3169 TypeAttributes.AutoLayout |
3170 TypeAttributes.Abstract |
3171 TypeAttributes.Interface;
3173 protected override TypeAttributes TypeAttr {
3175 return base.TypeAttr | DefaultTypeAttributes;
3179 protected override bool VerifyClsCompliance ()
3181 if (!base.VerifyClsCompliance ())
3184 if (ifaces != null) {
3185 foreach (Type t in ifaces) {
3186 if (AttributeTester.IsClsCompliant (t))
3189 Report.SymbolRelatedToPreviousError (t);
3190 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3191 GetSignatureForError (), TypeManager.CSharpName (t));
3199 // It is used as a base class for all property based members
3200 // This includes properties, indexers, and events
3201 public abstract class PropertyBasedMember : InterfaceMemberBase
3203 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3204 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3205 MemberName name, Attributes attrs)
3206 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3210 protected override bool VerifyClsCompliance ()
3212 if (!base.VerifyClsCompliance ())
3215 if (!AttributeTester.IsClsCompliant (MemberType)) {
3216 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3217 GetSignatureForError ());
3225 public abstract class MethodCore : InterfaceMemberBase
3227 public readonly Parameters Parameters;
3228 protected ToplevelBlock block;
3230 public MethodCore (DeclSpace parent, GenericMethod generic,
3231 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3232 MemberName name, Attributes attrs, Parameters parameters)
3233 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3235 Parameters = parameters;
3239 // Returns the System.Type array for the parameters of this method
3241 public Type [] ParameterTypes {
3243 return Parameters.Types;
3247 public Parameters ParameterInfo
3254 public ToplevelBlock Block {
3264 protected override bool CheckBase ()
3266 // Check whether arguments were correct.
3267 if (!DefineParameters (Parameters))
3270 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3271 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3272 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3275 // TODO: Find a better way how to check reserved accessors collision
3276 Method m = this as Method;
3278 if (!m.CheckForDuplications ())
3283 if (!base.CheckBase ())
3290 // Returns a string that represents the signature for this
3291 // member which should be used in XML documentation.
3293 public override string GetDocCommentName (DeclSpace ds)
3295 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3299 // Raised (and passed an XmlElement that contains the comment)
3300 // when GenerateDocComment is writing documentation expectedly.
3302 // FIXME: with a few effort, it could be done with XmlReader,
3303 // that means removal of DOM use.
3305 internal override void OnGenerateDocComment (XmlElement el)
3307 DocUtil.OnMethodGenerateDocComment (this, el);
3311 // Represents header string for documentation comment.
3313 public override string DocCommentHeader
3315 get { return "M:"; }
3318 public override bool EnableOverloadChecks (MemberCore overload)
3320 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3321 caching_flags |= Flags.MethodOverloadsExist;
3328 protected override bool VerifyClsCompliance ()
3330 if (!base.VerifyClsCompliance ())
3333 if (Parameters.HasArglist) {
3334 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3337 if (!AttributeTester.IsClsCompliant (MemberType)) {
3338 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3339 GetSignatureForError ());
3342 Parameters.VerifyClsCompliance ();
3348 public abstract class InterfaceMemberBase : MemberBase {
3350 // Whether this is an interface member.
3352 public bool IsInterface;
3355 // If true, this is an explicit interface implementation
3357 public bool IsExplicitImpl;
3359 protected bool is_external_implementation;
3362 // The interface type we are explicitly implementing
3364 public Type InterfaceType;
3367 // The method we're overriding if this is an override method.
3369 protected MethodInfo base_method;
3371 readonly int explicit_mod_flags;
3372 public MethodAttributes flags;
3374 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3375 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3376 MemberName name, Attributes attrs)
3377 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3380 IsInterface = is_iface;
3381 IsExplicitImpl = (MemberName.Left != null);
3382 explicit_mod_flags = mod;
3385 protected override bool CheckBase ()
3387 if (!base.CheckBase ())
3393 // Is null for System.Object while compiling corlib and base interfaces
3394 if (Parent.PartialContainer.BaseCache == null) {
3395 if ((ModFlags & Modifiers.NEW) != 0) {
3396 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3401 Type base_ret_type = null;
3402 base_method = FindOutBaseMethod (ref base_ret_type);
3404 // method is override
3405 if (base_method != null) {
3406 if (!CheckMethodAgainstBase (base_ret_type))
3409 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3410 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3412 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3413 Report.SymbolRelatedToPreviousError (base_method);
3414 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3415 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3418 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3419 Report.SymbolRelatedToPreviousError (base_method);
3420 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3421 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3428 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3429 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3430 if (conflict_symbol != null) {
3431 Report.SymbolRelatedToPreviousError (conflict_symbol);
3433 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3434 else if (this is PropertyBase)
3435 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3437 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3439 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3440 GetSignatureForError (), SimpleName.GetMemberType (this));
3445 if (conflict_symbol == null) {
3446 if ((ModFlags & Modifiers.NEW) != 0) {
3447 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3452 if ((ModFlags & Modifiers.NEW) == 0) {
3453 if (this is Method && conflict_symbol is MethodBase)
3456 Report.SymbolRelatedToPreviousError (conflict_symbol);
3457 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3458 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3465 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3466 // that have been defined.
3468 // `name' is the user visible name for reporting errors (this is used to
3469 // provide the right name regarding method names and properties)
3471 bool CheckMethodAgainstBase (Type base_method_type)
3475 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3476 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3477 Report.Error (506, Location,
3478 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3479 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3483 // Now we check that the overriden method is not final
3485 if (base_method.IsFinal) {
3486 Report.SymbolRelatedToPreviousError (base_method);
3487 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3488 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3492 // Check that the permissions are not being changed
3494 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3495 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3497 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3498 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3502 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3503 Report.SymbolRelatedToPreviousError (base_method);
3504 if (this is PropertyBasedMember) {
3505 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3506 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3509 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3510 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3516 if ((ModFlags & Modifiers.NEW) == 0) {
3517 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3518 ModFlags |= Modifiers.NEW;
3519 Report.SymbolRelatedToPreviousError (base_method);
3520 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3521 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",
3522 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3524 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3525 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3529 if (base_method.IsAbstract && !IsInterface) {
3530 Report.SymbolRelatedToPreviousError (base_method);
3531 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3532 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3540 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3542 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3544 // when overriding protected internal, the method can be declared
3545 // protected internal only within the same assembly or assembly
3546 // which has InternalsVisibleTo
3548 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3549 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3550 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3552 // if it's not "protected internal", it must be "protected"
3556 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3558 // protected within the same assembly - an error
3561 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3562 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3564 // protected ok, but other attributes differ - report an error
3570 return (thisp == base_classp);
3574 protected bool DefineParameters (Parameters parameters)
3576 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3578 if (!parameters.Resolve (rc))
3582 foreach (Parameter p in parameters.FixedParameters) {
3583 if (p.CheckAccessibility (this))
3586 Report.SymbolRelatedToPreviousError (p.ParameterType);
3587 if (this is Indexer)
3588 Report.Error (55, Location,
3589 "Inconsistent accessibility: parameter type `" +
3590 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3591 "accessible than indexer `" + GetSignatureForError () + "'");
3592 else if (this is Operator)
3593 Report.Error (57, Location,
3594 "Inconsistent accessibility: parameter type `" +
3595 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3596 "accessible than operator `" + GetSignatureForError () + "'");
3598 Report.Error (51, Location,
3599 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3600 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3606 protected override bool DoDefine()
3608 if (!base.DoDefine ())
3611 if (IsExplicitImpl) {
3612 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3616 InterfaceType = texpr.Type;
3618 if (!InterfaceType.IsInterface) {
3619 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3623 if (!Parent.PartialContainer.VerifyImplements (this))
3630 protected bool DoDefineBase ()
3633 throw new InternalErrorException ();
3636 ModFlags = Modifiers.PUBLIC |
3637 Modifiers.ABSTRACT |
3638 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3640 flags = MethodAttributes.Public |
3641 MethodAttributes.Abstract |
3642 MethodAttributes.HideBySig |
3643 MethodAttributes.NewSlot |
3644 MethodAttributes.Virtual;
3646 if (!Parent.PartialContainer.MethodModifiersValid (this))
3649 flags = Modifiers.MethodAttr (ModFlags);
3652 if (IsExplicitImpl) {
3653 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3654 if (iface_texpr == null)
3657 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3658 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3659 GetSignatureForError ());
3663 InterfaceType = iface_texpr.Type;
3665 if (!InterfaceType.IsInterface) {
3666 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3670 if (!Parent.PartialContainer.VerifyImplements (this))
3673 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3679 public override void Emit()
3681 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3682 // We are more strict than Microsoft and report CS0626 as error
3683 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3684 Report.Error (626, Location,
3685 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3686 GetSignatureForError ());
3692 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3694 Report.SymbolRelatedToPreviousError (base_method);
3695 string base_name = TypeManager.GetFullNameSignature (base_method);
3696 string this_name = GetSignatureForError ();
3697 if (suffix != null) {
3698 base_name += suffix;
3699 this_name += suffix;
3702 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3703 this_name, Modifiers.GetDescription (ma), base_name);
3706 protected static string Error722 {
3708 return "`{0}': static types cannot be used as return types";
3713 /// Gets base method and its return type
3715 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3718 // The "short" name of this property / indexer / event. This is the
3719 // name without the explicit interface.
3721 public string ShortName
3723 get { return MemberName.Name; }
3724 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3727 public string GetFullName (MemberName name)
3729 if (!IsExplicitImpl)
3732 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3735 protected override bool VerifyClsCompliance ()
3737 if (!base.VerifyClsCompliance ()) {
3738 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3739 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3742 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3743 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3748 if (GenericMethod != null)
3749 GenericMethod.VerifyClsCompliance ();
3754 public override bool IsUsed
3756 get { return IsExplicitImpl || base.IsUsed; }
3761 public abstract class MethodOrOperator : MethodCore, IMethodData
3763 public MethodBuilder MethodBuilder;
3764 ReturnParameter return_attributes;
3765 ListDictionary declarative_security;
3766 protected MethodData MethodData;
3768 static string[] attribute_targets = new string [] { "method", "return" };
3770 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3771 int allowed_mod, bool is_interface, MemberName name,
3772 Attributes attrs, Parameters parameters)
3773 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3778 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3780 if (a.Target == AttributeTargets.ReturnValue) {
3781 if (return_attributes == null)
3782 return_attributes = new ReturnParameter (MethodBuilder, Location);
3784 return_attributes.ApplyAttributeBuilder (a, cb);
3788 if (a.IsInternalMethodImplAttribute) {
3789 is_external_implementation = true;
3792 if (a.Type == TypeManager.dllimport_type) {
3793 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3794 if ((ModFlags & extern_static) != extern_static) {
3795 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3797 is_external_implementation = true;
3800 if (a.IsValidSecurityAttribute ()) {
3801 if (declarative_security == null)
3802 declarative_security = new ListDictionary ();
3803 a.ExtractSecurityPermissionSet (declarative_security);
3807 if (MethodBuilder != null)
3808 MethodBuilder.SetCustomAttribute (cb);
3811 public override AttributeTargets AttributeTargets {
3813 return AttributeTargets.Method;
3817 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3819 return new EmitContext (
3820 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3823 protected bool DefineGenericMethod ()
3825 if (!DoDefineBase ())
3829 if (GenericMethod != null) {
3830 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3831 if (!GenericMethod.Define (MethodBuilder, block))
3839 public bool ResolveMembers ()
3841 if (!DefineGenericMethod ())
3847 public override bool Define ()
3852 if (!CheckAbstractAndExtern (block != null))
3855 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3856 for (int i = 0; i < Parameters.Count; ++i ) {
3857 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
3858 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3859 GetSignatureForError ());
3868 if (block != null && block.IsIterator && !(Parent is IteratorStorey))
3869 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3871 if (IsPartialDefinition) {
3872 caching_flags &= ~Flags.Excluded_Undetected;
3873 caching_flags |= Flags.Excluded;
3874 // Add to member cache only when a partial method implementation is not there
3875 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3876 MethodBase mb = new PartialMethodDefinitionInfo (this);
3877 Parent.MemberCache.AddMember (mb, this);
3878 TypeManager.AddMethod (mb, this);
3884 MethodData = new MethodData (
3885 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3887 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3890 MethodBuilder = MethodData.MethodBuilder;
3893 if (MethodBuilder.IsGenericMethod)
3894 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3897 Parent.MemberCache.AddMember (MethodBuilder, this);
3899 if (!TypeManager.IsGenericParameter (MemberType)) {
3900 if (MemberType.IsAbstract && MemberType.IsSealed) {
3901 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3909 public override void Emit ()
3912 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3913 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3914 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3915 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3917 if (OptAttributes != null)
3918 OptAttributes.Emit ();
3920 if (declarative_security != null) {
3921 foreach (DictionaryEntry de in declarative_security) {
3922 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3929 protected void Error_ConditionalAttributeIsNotValid ()
3931 Report.Error (577, Location,
3932 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3933 GetSignatureForError ());
3936 public bool IsPartialDefinition {
3938 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3942 public bool IsPartialImplementation {
3944 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3948 public override string[] ValidAttributeTargets {
3950 return attribute_targets;
3954 #region IMethodData Members
3956 public CallingConventions CallingConventions {
3958 CallingConventions cc = Parameters.CallingConvention;
3960 if ((ModFlags & Modifiers.STATIC) == 0)
3961 cc |= CallingConventions.HasThis;
3963 // FIXME: How is `ExplicitThis' used in C#?
3969 public Type ReturnType {
3975 public MemberName MethodName {
3981 protected override bool CheckBase ()
3983 if (!base.CheckBase ())
3986 // TODO: Destructor should derive from MethodCore
3987 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3988 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3989 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3997 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3999 public bool IsExcluded () {
4000 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4001 return (caching_flags & Flags.Excluded) != 0;
4003 caching_flags &= ~Flags.Excluded_Undetected;
4005 if (base_method == null) {
4006 if (OptAttributes == null)
4009 if (TypeManager.conditional_attribute_type == null)
4012 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4017 foreach (Attribute a in attrs) {
4018 string condition = a.GetConditionalAttributeValue ();
4019 if (condition == null)
4022 if (RootContext.AllDefines.Contains (condition))
4026 caching_flags |= Flags.Excluded;
4030 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4032 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4033 caching_flags |= Flags.Excluded;
4039 if (md.IsExcluded ()) {
4040 caching_flags |= Flags.Excluded;
4046 GenericMethod IMethodData.GenericMethod {
4048 return GenericMethod;
4052 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4059 public class SourceMethod : IMethodDef
4062 SourceMethodBuilder builder;
4064 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4066 this.method = method;
4068 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4071 public string Name {
4072 get { return method.Name; }
4077 if (method is MethodBuilder)
4078 return ((MethodBuilder) method).GetToken ().Token;
4079 else if (method is ConstructorBuilder)
4080 return ((ConstructorBuilder) method).GetToken ().Token;
4082 throw new NotSupportedException ();
4086 public void CloseMethod ()
4088 SymbolWriter.CloseMethod ();
4091 public void SetRealMethodName (string name)
4093 if (builder != null)
4094 builder.SetRealMethodName (name);
4097 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4099 if (!SymbolWriter.HasSymbolWriter)
4104 Location start_loc = block.StartLocation;
4105 if (start_loc.IsNull)
4108 ICompileUnit compile_unit = start_loc.CompilationUnit;
4109 if (compile_unit == null)
4112 return new SourceMethod (parent, method, compile_unit);
4116 public class Method : MethodOrOperator {
4119 /// Modifiers allowed in a class declaration
4121 const int AllowedModifiers =
4124 Modifiers.PROTECTED |
4125 Modifiers.INTERNAL |
4130 Modifiers.OVERRIDE |
4131 Modifiers.ABSTRACT |
4135 const int AllowedInterfaceModifiers =
4136 Modifiers.NEW | Modifiers.UNSAFE;
4139 // return_type can be "null" for VOID values.
4141 public Method (DeclSpace parent, GenericMethod generic,
4142 FullNamedExpression return_type, int mod, bool is_iface,
4143 MemberName name, Parameters parameters, Attributes attrs)
4144 : base (parent, generic, return_type, mod,
4145 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4146 is_iface, name, attrs, parameters)
4150 public override string GetSignatureForError()
4152 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4155 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4157 Report.Error (17, location,
4158 "Program `{0}' has more than one entry point defined: `{1}'",
4159 CodeGen.FileName, TypeManager.CSharpSignature(b));
4162 bool IsEntryPoint ()
4164 if (ReturnType != TypeManager.void_type &&
4165 ReturnType != TypeManager.int32_type)
4168 if (Parameters.Count == 0)
4171 if (Parameters.Count > 1)
4174 Type t = Parameters.ParameterType (0);
4175 return t.IsArray && t.GetArrayRank () == 1 &&
4176 TypeManager.GetElementType (t) == TypeManager.string_type &&
4177 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4180 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4182 if (a.Type == TypeManager.conditional_attribute_type) {
4183 if (IsExplicitImpl) {
4184 Error_ConditionalAttributeIsNotValid ();
4188 if (ReturnType != TypeManager.void_type) {
4189 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4193 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4194 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4199 Report.Error (582, Location, "Conditional not valid on interface members");
4203 if (MethodData.implementing != null) {
4204 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4205 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4206 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4210 for (int i = 0; i < Parameters.Count; ++i) {
4211 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4212 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4218 if (a.Type == TypeManager.extension_attribute_type) {
4219 a.Error_MisusedExtensionAttribute ();
4223 base.ApplyAttributeBuilder (a, cb);
4226 public bool CheckForDuplications ()
4228 ArrayList ar = Parent.PartialContainer.Properties;
4230 for (int i = 0; i < ar.Count; ++i) {
4231 PropertyBase pb = (PropertyBase) ar [i];
4232 if (pb.AreAccessorsDuplicateImplementation (this))
4237 ar = Parent.PartialContainer.Indexers;
4239 for (int i = 0; i < ar.Count; ++i) {
4240 PropertyBase pb = (PropertyBase) ar [i];
4241 if (pb.AreAccessorsDuplicateImplementation (this))
4252 public override bool Define ()
4254 if (!base.Define ())
4257 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4258 Error1599 (Location, ReturnType);
4262 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4263 Name == "Finalize" && !(this is Destructor)) {
4264 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4267 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4268 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4269 Parent.PartialContainer.Mark_HasEquals ();
4270 else if (Parameters.Empty && Name == "GetHashCode")
4271 Parent.PartialContainer.Mark_HasGetHashCode ();
4274 if ((ModFlags & Modifiers.STATIC) == 0)
4277 if (Parameters.HasExtensionMethodType) {
4278 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4279 if (!Parent.IsTopLevel)
4280 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4281 GetSignatureForError ());
4283 if (TypeManager.extension_attribute_type == null) {
4284 Report.Error (1110, Location,
4285 "`{0}': Extension methods cannot be declared without a reference to System.Core.dll assembly. Add the assembly reference or remove `this' modifer from the first parameter",
4286 GetSignatureForError ());
4287 } else if (TypeManager.extension_attribute_attr == null) {
4288 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4289 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4292 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4295 ModFlags |= Modifiers.METHOD_EXTENSION;
4296 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4297 CodeGen.Assembly.HasExtensionMethods = true;
4299 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4300 GetSignatureForError ());
4305 // This is used to track the Entry Point,
4307 if (RootContext.NeedsEntryPoint &&
4309 (RootContext.MainClass == null ||
4310 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4311 if (IsEntryPoint ()) {
4313 if (RootContext.EntryPoint == null) {
4314 if (Parent.IsGeneric || MemberName.IsGeneric) {
4315 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4316 GetSignatureForError ());
4318 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4319 md.SetMemberIsUsed ();
4321 RootContext.EntryPoint = MethodBuilder;
4322 RootContext.EntryPointLocation = Location;
4325 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4326 Error_DuplicateEntryPoint (MethodBuilder, Location);
4329 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4330 GetSignatureForError ());
4340 public override void Emit ()
4343 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4344 if (IsPartialDefinition) {
4346 // Do attribute checks only when partial implementation does not exist
4348 if (MethodBuilder == null)
4354 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4355 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4356 GetSignatureForError ());
4358 MethodData.Emit (Parent);
4362 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4363 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4369 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4370 Location, MethodBuilder);
4375 public override bool EnableOverloadChecks (MemberCore overload)
4377 // TODO: It can be deleted when members will be defined in correct order
4378 if (overload is Operator)
4379 return overload.EnableOverloadChecks (this);
4381 if (overload is Indexer)
4384 return base.EnableOverloadChecks (overload);
4387 public static void Error1599 (Location loc, Type t)
4389 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4392 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4394 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4395 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4400 if (mi.IsSpecialName)
4403 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4407 public void SetPartialDefinition (Method methodDefinition)
4409 caching_flags |= Flags.PartialDefinitionExists;
4410 methodDefinition.MethodBuilder = MethodBuilder;
4411 if (methodDefinition.attributes == null)
4414 if (attributes == null) {
4415 attributes = methodDefinition.attributes;
4417 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4421 protected override bool VerifyClsCompliance ()
4423 if (!base.VerifyClsCompliance ())
4426 if (ParameterInfo.Count > 0) {
4427 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4429 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4436 public abstract class ConstructorInitializer : ExpressionStatement
4438 ArrayList argument_list;
4439 MethodGroupExpr base_constructor_group;
4441 public ConstructorInitializer (ArrayList argument_list, Location loc)
4443 this.argument_list = argument_list;
4447 public ArrayList Arguments {
4449 return argument_list;
4453 public override Expression CreateExpressionTree (EmitContext ec)
4455 throw new NotSupportedException ("ET");
4458 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4460 if (argument_list != null){
4461 foreach (Argument a in argument_list){
4462 if (!a.Resolve (ec, loc))
4467 if (this is ConstructorBaseInitializer) {
4468 if (ec.ContainerType.BaseType == null)
4471 type = ec.ContainerType.BaseType;
4472 if (ec.ContainerType.IsValueType) {
4473 Report.Error (522, loc,
4474 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4479 // It is legal to have "this" initializers that take no arguments
4480 // in structs, they are just no-ops.
4482 // struct D { public D (int a) : this () {}
4484 if (ec.ContainerType.IsValueType && argument_list == null)
4487 type = ec.ContainerType;
4490 base_constructor_group = MemberLookupFinal (
4491 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4492 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4493 loc) as MethodGroupExpr;
4495 if (base_constructor_group == null)
4498 base_constructor_group = base_constructor_group.OverloadResolve (
4499 ec, ref argument_list, false, loc);
4501 if (base_constructor_group == null)
4504 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4506 if (base_ctor == caller_builder){
4507 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4513 public override Expression DoResolve (EmitContext ec)
4515 throw new NotSupportedException ();
4518 public override void Emit (EmitContext ec)
4520 // It can be null for static initializers
4521 if (base_constructor_group == null)
4524 ec.Mark (loc, false);
4526 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4528 base_constructor_group.EmitCall (ec, argument_list);
4531 public override void EmitStatement (EmitContext ec)
4537 public class ConstructorBaseInitializer : ConstructorInitializer {
4538 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4539 base (argument_list, l)
4544 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4545 public GeneratedBaseInitializer (Location loc):
4551 public class ConstructorThisInitializer : ConstructorInitializer {
4552 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4553 base (argument_list, l)
4558 public class Constructor : MethodCore, IMethodData {
4559 public ConstructorBuilder ConstructorBuilder;
4560 public ConstructorInitializer Initializer;
4561 ListDictionary declarative_security;
4562 bool has_compliant_args;
4565 // Modifiers allowed for a constructor.
4567 public const int AllowedModifiers =
4569 Modifiers.PROTECTED |
4570 Modifiers.INTERNAL |
4576 static readonly string[] attribute_targets = new string [] { "method" };
4579 // The spec claims that static is not permitted, but
4580 // my very own code has static constructors.
4582 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4583 ConstructorInitializer init, Location loc)
4584 : base (parent, null, null, mod, AllowedModifiers, false,
4585 new MemberName (name, loc), null, args)
4590 public bool HasCompliantArgs {
4591 get { return has_compliant_args; }
4594 public override AttributeTargets AttributeTargets {
4595 get { return AttributeTargets.Constructor; }
4599 // Returns true if this is a default constructor
4601 public bool IsDefault ()
4603 if ((ModFlags & Modifiers.STATIC) != 0)
4604 return Parameters.Empty;
4606 return Parameters.Empty &&
4607 (Initializer is ConstructorBaseInitializer) &&
4608 (Initializer.Arguments == null);
4611 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4613 if (a.IsValidSecurityAttribute ()) {
4614 if (declarative_security == null) {
4615 declarative_security = new ListDictionary ();
4617 a.ExtractSecurityPermissionSet (declarative_security);
4621 if (a.IsInternalMethodImplAttribute) {
4622 is_external_implementation = true;
4625 ConstructorBuilder.SetCustomAttribute (cb);
4628 protected override bool CheckBase ()
4630 if ((ModFlags & Modifiers.STATIC) != 0) {
4631 if (!Parameters.Empty) {
4632 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4633 GetSignatureForError ());
4637 // the rest can be ignored
4641 // Check whether arguments were correct.
4642 if (!DefineParameters (Parameters))
4645 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4646 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4649 if (Parent.PartialContainer.Kind == Kind.Struct) {
4650 if (ParameterTypes.Length == 0) {
4651 Report.Error (568, Location,
4652 "Structs cannot contain explicit parameterless constructors");
4657 CheckProtectedModifier ();
4663 // Creates the ConstructorBuilder
4665 public override bool Define ()
4667 if (ConstructorBuilder != null)
4670 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4671 MethodAttributes.SpecialName);
4673 if ((ModFlags & Modifiers.STATIC) != 0) {
4674 ca |= MethodAttributes.Static | MethodAttributes.Private;
4676 ca |= MethodAttributes.HideBySig;
4678 if ((ModFlags & Modifiers.PUBLIC) != 0)
4679 ca |= MethodAttributes.Public;
4680 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4681 if ((ModFlags & Modifiers.INTERNAL) != 0)
4682 ca |= MethodAttributes.FamORAssem;
4684 ca |= MethodAttributes.Family;
4685 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4686 ca |= MethodAttributes.Assembly;
4688 ca |= MethodAttributes.Private;
4691 if (!CheckAbstractAndExtern (block != null))
4694 // Check if arguments were correct.
4698 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4699 ca, CallingConventions,
4702 if (Parent.PartialContainer.IsComImport) {
4703 if (!IsDefault ()) {
4704 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4705 Parent.GetSignatureForError ());
4708 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4711 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4712 TypeManager.AddMethod (ConstructorBuilder, this);
4714 // It's here only to report an error
4715 if (block != null && block.IsIterator) {
4716 member_type = TypeManager.void_type;
4717 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4726 public override void Emit ()
4728 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4729 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4731 if (OptAttributes != null)
4732 OptAttributes.Emit ();
4736 EmitContext ec = CreateEmitContext (null, null);
4739 // If we use a "this (...)" constructor initializer, then
4740 // do not emit field initializers, they are initialized in the other constructor
4742 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4743 !(Initializer is ConstructorThisInitializer);
4745 if (emit_field_initializers)
4746 Parent.PartialContainer.ResolveFieldInitializers (ec);
4748 if (block != null) {
4749 // If this is a non-static `struct' constructor and doesn't have any
4750 // initializer, it must initialize all of the struct's fields.
4751 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4752 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4753 block.AddThisVariable (Parent, Location);
4755 if (!block.ResolveMeta (ec, ParameterInfo))
4758 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4759 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4760 Initializer = new GeneratedBaseInitializer (Location);
4763 // Spec mandates that Initializers will not have `this' access
4765 if (Initializer != null) {
4767 Initializer.Resolve (ConstructorBuilder, ec);
4768 ec.IsStatic = false;
4769 block.AddScopeStatement (new StatementExpression (Initializer));
4774 Parameters.ApplyAttributes (ConstructorBuilder);
4776 SourceMethod source = null;
4778 ec.OmitDebuggingInfo = true;
4780 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4782 bool unreachable = false;
4783 if (block != null) {
4784 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4787 ec.EmitMeta (block);
4789 if (Report.Errors > 0)
4792 if (emit_field_initializers)
4793 Parent.PartialContainer.EmitFieldInitializers (ec);
4795 ec.EmitResolvedTopBlock (block, unreachable);
4799 source.CloseMethod ();
4801 if (declarative_security != null) {
4802 foreach (DictionaryEntry de in declarative_security) {
4803 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4810 // Is never override
4811 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4816 public override string GetSignatureForError()
4818 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4821 public override string[] ValidAttributeTargets {
4823 return attribute_targets;
4827 protected override bool VerifyClsCompliance ()
4829 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4833 if (ParameterInfo.Count > 0) {
4834 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4836 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4838 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4839 foreach (Type param in ParameterTypes) {
4840 if (param.IsArray) {
4846 has_compliant_args = true;
4850 #region IMethodData Members
4852 public System.Reflection.CallingConventions CallingConventions {
4854 CallingConventions cc = Parameters.CallingConvention;
4856 if (Parent.PartialContainer.Kind == Kind.Class)
4857 if ((ModFlags & Modifiers.STATIC) == 0)
4858 cc |= CallingConventions.HasThis;
4860 // FIXME: How is `ExplicitThis' used in C#?
4866 public MemberName MethodName {
4872 public Type ReturnType {
4878 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4880 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4881 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4882 ec.CurrentBlock = block;
4886 public bool IsExcluded()
4891 GenericMethod IMethodData.GenericMethod {
4897 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4904 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4906 public interface IMethodData
4908 CallingConventions CallingConventions { get; }
4909 Location Location { get; }
4910 MemberName MethodName { get; }
4911 Type ReturnType { get; }
4912 GenericMethod GenericMethod { get; }
4913 Parameters ParameterInfo { get; }
4915 Attributes OptAttributes { get; }
4916 ToplevelBlock Block { get; set; }
4918 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4919 ObsoleteAttribute GetObsoleteAttribute ();
4920 string GetSignatureForError ();
4922 bool IsClsComplianceRequired ();
4923 void SetMemberIsUsed ();
4924 void EmitExtraSymbolInfo (SourceMethod source);
4928 // Encapsulates most of the Method's state
4930 public class MethodData {
4932 static FieldInfo methodbuilder_attrs_field;
4934 readonly IMethodData method;
4936 public readonly GenericMethod GenericMethod;
4939 // Are we implementing an interface ?
4941 public MethodInfo implementing;
4946 protected InterfaceMemberBase member;
4947 protected int modifiers;
4948 protected MethodAttributes flags;
4949 protected Type declaring_type;
4950 protected MethodInfo parent_method;
4952 MethodBuilder builder = null;
4953 public MethodBuilder MethodBuilder {
4959 public Type DeclaringType {
4961 return declaring_type;
4965 public MethodData (InterfaceMemberBase member,
4966 int modifiers, MethodAttributes flags, IMethodData method)
4968 this.member = member;
4969 this.modifiers = modifiers;
4972 this.method = method;
4975 public MethodData (InterfaceMemberBase member,
4976 int modifiers, MethodAttributes flags,
4977 IMethodData method, MethodBuilder builder,
4978 GenericMethod generic, MethodInfo parent_method)
4979 : this (member, modifiers, flags, method)
4981 this.builder = builder;
4982 this.GenericMethod = generic;
4983 this.parent_method = parent_method;
4986 public bool Define (DeclSpace parent, string method_full_name)
4988 string name = method.MethodName.Basename;
4990 TypeContainer container = parent.PartialContainer;
4992 PendingImplementation pending = container.PendingImplementations;
4993 if (pending != null){
4994 if (member is Indexer) // TODO: test it, but it should work without this IF
4995 implementing = pending.IsInterfaceIndexer (
4996 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4998 implementing = pending.IsInterfaceMethod (
4999 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5001 if (member.InterfaceType != null){
5002 if (implementing == null){
5003 if (member is PropertyBase) {
5004 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5005 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5006 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5009 Report.Error (539, method.Location,
5010 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5011 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5015 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5016 Report.SymbolRelatedToPreviousError (implementing);
5017 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5018 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5022 if (implementing != null) {
5023 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5024 if (prop_method == null) {
5025 if (TypeManager.IsSpecialMethod (implementing)) {
5026 Report.SymbolRelatedToPreviousError (implementing);
5027 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5028 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5029 implementing.Name.StartsWith ("get_") ? "get" : "set");
5031 } else if (implementing.DeclaringType.IsInterface) {
5032 if (!implementing.IsSpecialName) {
5033 Report.SymbolRelatedToPreviousError (implementing);
5034 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5035 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5038 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5039 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5040 Report.SymbolRelatedToPreviousError (implementing);
5041 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5042 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5051 // For implicit implementations, make sure we are public, for
5052 // explicit implementations, make sure we are private.
5054 if (implementing != null){
5056 // Setting null inside this block will trigger a more
5057 // verbose error reporting for missing interface implementations
5059 // The "candidate" function has been flagged already
5060 // but it wont get cleared
5062 if (member.IsExplicitImpl){
5063 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5064 Report.SymbolRelatedToPreviousError (implementing);
5065 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5066 method.GetSignatureForError ());
5070 if (implementing.DeclaringType.IsInterface) {
5072 // If this is an interface method implementation,
5073 // check for public accessibility
5075 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5077 implementing = null;
5079 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5080 // We may never be private.
5081 implementing = null;
5083 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5085 // We may be protected if we're overriding something.
5087 implementing = null;
5092 // Static is not allowed
5094 if ((modifiers & Modifiers.STATIC) != 0){
5095 implementing = null;
5100 // If implementing is still valid, set flags
5102 if (implementing != null){
5104 // When implementing interface methods, set NewSlot
5105 // unless, we are overwriting a method.
5107 if (implementing.DeclaringType.IsInterface){
5108 if ((modifiers & Modifiers.OVERRIDE) == 0)
5109 flags |= MethodAttributes.NewSlot;
5112 MethodAttributes.Virtual |
5113 MethodAttributes.HideBySig;
5115 // Set Final unless we're virtual, abstract or already overriding a method.
5116 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5117 flags |= MethodAttributes.Final;
5120 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5122 if (builder == null)
5125 if (container.CurrentType != null)
5126 declaring_type = container.CurrentType;
5128 declaring_type = container.TypeBuilder;
5130 if (implementing != null){
5132 // clear the pending implemntation flag
5134 if (member is Indexer) {
5135 pending.ImplementIndexer (
5136 member.InterfaceType, builder, method.ReturnType,
5137 method.ParameterInfo, member.IsExplicitImpl);
5139 pending.ImplementMethod (
5140 member.InterfaceType, name, method.ReturnType,
5141 method.ParameterInfo, member.IsExplicitImpl);
5143 if (member.IsExplicitImpl)
5144 container.TypeBuilder.DefineMethodOverride (
5145 builder, implementing);
5148 TypeManager.AddMethod (builder, method);
5150 if (GenericMethod != null) {
5151 bool is_override = member.IsExplicitImpl |
5152 ((modifiers & Modifiers.OVERRIDE) != 0);
5154 if (implementing != null)
5155 parent_method = implementing;
5157 EmitContext ec = method.CreateEmitContext (container, null);
5158 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5167 /// Create the MethodBuilder for the method
5169 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5171 if (builder == null) {
5172 builder = container.TypeBuilder.DefineMethod (
5173 method_name, flags, method.CallingConventions,
5174 method.ReturnType, ParameterTypes);
5180 // Generic method has been already defined to resolve method parameters
5181 // correctly when they use type parameters
5183 builder.SetParameters (ParameterTypes);
5184 builder.SetReturnType (method.ReturnType);
5186 if (builder.Attributes != flags) {
5188 if (methodbuilder_attrs_field == null)
5189 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5190 methodbuilder_attrs_field.SetValue (builder, flags);
5192 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5196 throw new InternalErrorException ();
5203 public void Emit (DeclSpace parent)
5205 ToplevelBlock block = method.Block;
5209 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5211 ec = method.CreateEmitContext (parent, null);
5213 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5215 if (GenericMethod != null)
5216 GenericMethod.EmitAttributes ();
5218 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5221 // Handle destructors specially
5223 // FIXME: This code generates buggy code
5225 if (member is Destructor)
5226 EmitDestructor (ec, block);
5228 ec.EmitTopBlock (method, block);
5230 if (source != null) {
5231 method.EmitExtraSymbolInfo (source);
5232 source.CloseMethod ();
5236 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5238 ILGenerator ig = ec.ig;
5240 Label finish = ig.DefineLabel ();
5242 block.SetDestructor ();
5244 ig.BeginExceptionBlock ();
5245 ec.ReturnLabel = finish;
5246 ec.HasReturnLabel = true;
5247 ec.EmitTopBlock (method, block);
5249 // ig.MarkLabel (finish);
5250 ig.BeginFinallyBlock ();
5252 if (ec.ContainerType.BaseType != null) {
5253 Expression member_lookup = Expression.MemberLookup (
5254 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5255 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5257 if (member_lookup != null){
5258 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5260 ig.Emit (OpCodes.Ldarg_0);
5261 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5265 ig.EndExceptionBlock ();
5266 //ig.MarkLabel (ec.ReturnLabel);
5267 ig.Emit (OpCodes.Ret);
5271 // TODO: Should derive from MethodCore
5272 public class Destructor : Method {
5274 static string[] attribute_targets = new string [] { "method" };
5276 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5277 string name, Parameters parameters, Attributes attrs,
5279 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5283 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5285 if (a.Type == TypeManager.conditional_attribute_type) {
5286 Error_ConditionalAttributeIsNotValid ();
5290 base.ApplyAttributeBuilder (a, cb);
5293 public override string GetSignatureForError ()
5295 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5298 public override string[] ValidAttributeTargets {
5300 return attribute_targets;
5305 abstract public class MemberBase : MemberCore {
5306 protected FullNamedExpression type_name;
5307 public readonly DeclSpace ds;
5308 public readonly GenericMethod GenericMethod;
5311 // The type of this property / indexer / event
5313 protected Type member_type;
5314 public Type MemberType {
5316 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5317 if (member_type == null && type_name != null) {
5318 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5319 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5320 if (type_name != null) {
5321 member_type = type_name.Type;
5329 // The constructor is only exposed to our children
5331 protected MemberBase (DeclSpace parent, GenericMethod generic,
5332 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5333 MemberName name, Attributes attrs)
5334 : base (parent, name, attrs)
5336 this.ds = generic != null ? generic : (DeclSpace) parent;
5337 this.type_name = type;
5338 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5339 GenericMethod = generic;
5340 if (GenericMethod != null)
5341 GenericMethod.ModFlags = ModFlags;
5344 protected virtual bool CheckBase ()
5346 CheckProtectedModifier ();
5351 protected virtual bool DoDefine ()
5353 if (MemberType == null)
5356 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5357 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5358 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5359 GetSignatureForError (), Parent.GetSignatureForError ());
5363 // verify accessibility
5364 if (!IsAccessibleAs (MemberType)) {
5365 Report.SymbolRelatedToPreviousError (MemberType);
5366 if (this is Property)
5367 Report.Error (53, Location,
5368 "Inconsistent accessibility: property type `" +
5369 TypeManager.CSharpName (MemberType) + "' is less " +
5370 "accessible than property `" + GetSignatureForError () + "'");
5371 else if (this is Indexer)
5372 Report.Error (54, Location,
5373 "Inconsistent accessibility: indexer return type `" +
5374 TypeManager.CSharpName (MemberType) + "' is less " +
5375 "accessible than indexer `" + GetSignatureForError () + "'");
5376 else if (this is MethodCore) {
5377 if (this is Operator)
5378 Report.Error (56, Location,
5379 "Inconsistent accessibility: return type `" +
5380 TypeManager.CSharpName (MemberType) + "' is less " +
5381 "accessible than operator `" + GetSignatureForError () + "'");
5383 Report.Error (50, Location,
5384 "Inconsistent accessibility: return type `" +
5385 TypeManager.CSharpName (MemberType) + "' is less " +
5386 "accessible than method `" + GetSignatureForError () + "'");
5388 Report.Error (52, Location,
5389 "Inconsistent accessibility: field type `" +
5390 TypeManager.CSharpName (MemberType) + "' is less " +
5391 "accessible than field `" + GetSignatureForError () + "'");
5399 protected bool IsTypePermitted ()
5401 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5402 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5410 // Abstract class for all fields
5412 abstract public class FieldBase : MemberBase {
5413 public FieldBuilder FieldBuilder;
5414 public Status status;
5415 protected Expression initializer;
5418 public enum Status : byte {
5419 HAS_OFFSET = 4 // Used by FieldMember.
5422 static readonly string[] attribute_targets = new string [] { "field" };
5424 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5425 int allowed_mod, MemberName name, Attributes attrs)
5426 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5429 if ((mod & Modifiers.ABSTRACT) != 0)
5430 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5433 public override AttributeTargets AttributeTargets {
5435 return AttributeTargets.Field;
5439 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5441 if (a.Type == TypeManager.field_offset_attribute_type) {
5442 status |= Status.HAS_OFFSET;
5444 if (!Parent.PartialContainer.HasExplicitLayout) {
5445 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5449 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5450 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5456 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5457 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5462 if (a.Type == TypeManager.marshal_as_attr_type) {
5463 UnmanagedMarshal marshal = a.GetMarshal (this);
5464 if (marshal != null) {
5465 FieldBuilder.SetMarshal (marshal);
5470 if ((a.HasSecurityAttribute)) {
5471 a.Error_InvalidSecurityParent ();
5475 FieldBuilder.SetCustomAttribute (cb);
5478 protected override bool CheckBase ()
5480 if (!base.CheckBase ())
5483 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5484 if (conflict_symbol == null) {
5485 if ((ModFlags & Modifiers.NEW) != 0) {
5486 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5491 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5492 Report.SymbolRelatedToPreviousError (conflict_symbol);
5493 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5494 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5500 public override bool Define()
5502 if (MemberType == null || member_type == null)
5505 if (TypeManager.IsGenericParameter (MemberType))
5508 if (MemberType == TypeManager.void_type) {
5509 // TODO: wrong location
5510 Expression.Error_VoidInvalidInTheContext (Location);
5514 if (MemberType.IsSealed && MemberType.IsAbstract) {
5515 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5525 if (!IsTypePermitted ())
5532 // Represents header string for documentation comment.
5534 public override string DocCommentHeader {
5535 get { return "F:"; }
5538 public override void Emit ()
5541 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5542 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5545 if (OptAttributes != null) {
5546 OptAttributes.Emit ();
5549 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5550 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5556 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5558 Report.SymbolRelatedToPreviousError (static_class);
5559 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5563 public Expression Initializer {
5565 if (value != null) {
5566 this.initializer = value;
5571 protected virtual bool IsFieldClsCompliant {
5573 if (FieldBuilder == null)
5576 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5580 public override string[] ValidAttributeTargets
5583 return attribute_targets;
5587 protected override bool VerifyClsCompliance ()
5589 if (!base.VerifyClsCompliance ())
5592 if (!IsFieldClsCompliant) {
5593 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5598 public void SetAssigned ()
5600 caching_flags |= Flags.IsAssigned;
5604 interface IFixedBuffer
5606 FieldInfo Element { get; }
5607 Type ElementType { get; }
5610 public class FixedFieldExternal: IFixedBuffer
5612 FieldInfo element_field;
5614 public FixedFieldExternal (FieldInfo fi)
5616 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5619 #region IFixedField Members
5621 public FieldInfo Element {
5623 return element_field;
5627 public Type ElementType {
5629 return element_field.FieldType;
5637 /// Fixed buffer implementation
5639 public class FixedField : FieldBase, IFixedBuffer
5641 public const string FixedElementName = "FixedElementField";
5642 static int GlobalCounter = 0;
5643 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5644 static FieldInfo[] fi;
5646 TypeBuilder fixed_buffer_type;
5647 FieldBuilder element;
5648 Expression size_expr;
5650 const int AllowedModifiers =
5653 Modifiers.PROTECTED |
5654 Modifiers.INTERNAL |
5657 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5658 Expression size_expr, Attributes attrs, Location loc):
5659 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5661 if (RootContext.Version == LanguageVersion.ISO_1)
5662 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5664 this.size_expr = size_expr;
5667 public override bool Define()
5669 if (!Parent.IsInUnsafeScope)
5670 Expression.UnsafeError (Location);
5672 if (!base.Define ())
5675 if (!TypeManager.IsPrimitiveType (MemberType)) {
5676 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",
5677 GetSignatureForError ());
5680 // Create nested fixed buffer container
5681 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5682 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5683 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5685 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5686 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5688 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5689 Parent.MemberCache.AddMember (FieldBuilder, this);
5690 TypeManager.RegisterFieldBase (FieldBuilder, this);
5695 public override void Emit()
5697 if (Parent.PartialContainer.Kind != Kind.Struct) {
5698 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5699 GetSignatureForError ());
5702 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5703 Constant c = size_expr.ResolveAsConstant (ec, this);
5707 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5708 if (buffer_size_const == null)
5711 int buffer_size = buffer_size_const.Value;
5713 if (buffer_size <= 0) {
5714 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5718 int type_size = Expression.GetTypeSize (MemberType);
5720 if (buffer_size > int.MaxValue / type_size) {
5721 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5722 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5726 buffer_size *= type_size;
5727 EmitFieldSize (buffer_size);
5731 void EmitFieldSize (int buffer_size)
5733 if (TypeManager.struct_layout_attribute_type == null) {
5734 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5735 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5737 if (TypeManager.struct_layout_attribute_type == null)
5742 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5744 object [] fi_val = new object [] { buffer_size };
5746 if (TypeManager.struct_layout_attribute_ctor == null) {
5747 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5748 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5749 if (TypeManager.struct_layout_attribute_ctor == null)
5753 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5754 ctor_args, fi, fi_val);
5755 fixed_buffer_type.SetCustomAttribute (cab);
5758 // Don't emit FixedBufferAttribute attribute for private types
5760 if ((ModFlags & Modifiers.PRIVATE) != 0)
5763 if (TypeManager.fixed_buffer_attr_ctor == null) {
5764 if (TypeManager.fixed_buffer_attr_type == null) {
5765 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5766 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5768 if (TypeManager.fixed_buffer_attr_type == null)
5772 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5773 Location, TypeManager.type_type, TypeManager.int32_type);
5775 if (TypeManager.fixed_buffer_attr_ctor == null)
5779 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5780 FieldBuilder.SetCustomAttribute (cab);
5783 protected override bool IsFieldClsCompliant {
5789 #region IFixedField Members
5791 public FieldInfo Element {
5797 public Type ElementType {
5807 // The Field class is used to represents class/struct fields during parsing.
5809 public class Field : FieldBase {
5811 // Modifiers allowed in a class declaration
5813 const int AllowedModifiers =
5816 Modifiers.PROTECTED |
5817 Modifiers.INTERNAL |
5820 Modifiers.VOLATILE |
5824 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5825 Attributes attrs, Location loc)
5826 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5831 bool CanBeVolatile ()
5833 if (TypeManager.IsReferenceType (MemberType))
5836 if (MemberType.IsEnum)
5839 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5840 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5841 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5842 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5843 MemberType == TypeManager.float_type)
5849 public override bool Define ()
5851 if (!base.Define ())
5854 if ((ModFlags & Modifiers.VOLATILE) != 0){
5855 if (!CanBeVolatile ()) {
5856 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5857 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5860 if ((ModFlags & Modifiers.READONLY) != 0){
5861 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5862 GetSignatureForError ());
5866 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5870 Type[] required_modifier = null;
5871 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5872 if (TypeManager.isvolatile_type == null)
5873 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5874 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5876 if (TypeManager.isvolatile_type != null)
5877 required_modifier = new Type [] { TypeManager.isvolatile_type };
5880 FieldBuilder = Parent.TypeBuilder.DefineField (
5881 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5883 FieldBuilder = Parent.TypeBuilder.DefineField (
5884 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5886 Parent.MemberCache.AddMember (FieldBuilder, this);
5887 TypeManager.RegisterFieldBase (FieldBuilder, this);
5889 catch (ArgumentException) {
5890 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5894 if (initializer != null)
5895 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5896 new FieldInitializer (FieldBuilder, initializer));
5898 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
5899 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
5900 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
5901 GetSignatureForError ());
5908 public override string GetSignatureForError ()
5910 string s = base.GetSignatureForError ();
5911 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5914 // Undecorate name mangling
5915 int l = s.LastIndexOf ('>');
5916 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5919 protected override bool VerifyClsCompliance ()
5921 if (!base.VerifyClsCompliance ())
5924 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5925 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5933 // `set' and `get' accessors are represented with an Accessor.
5935 public class Accessor {
5937 // Null if the accessor is empty, or a Block if not
5939 public const int AllowedModifiers =
5941 Modifiers.PROTECTED |
5942 Modifiers.INTERNAL |
5945 public ToplevelBlock Block;
5946 public Attributes Attributes;
5947 public Location Location;
5948 public int ModFlags;
5950 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5955 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5959 // Ooouh Martin, templates are missing here.
5960 // When it will be possible move here a lot of child code and template method type.
5961 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5962 protected MethodData method_data;
5963 protected ToplevelBlock block;
5964 protected ListDictionary declarative_security;
5966 // The accessor are created event if they are not wanted.
5967 // But we need them because their names are reserved.
5968 // Field says whether accessor will be emited or not
5969 public readonly bool IsDummy;
5971 protected readonly string prefix;
5973 ReturnParameter return_attributes;
5975 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5976 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5978 this.prefix = prefix;
5982 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5984 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5985 accessor.Attributes)
5987 this.prefix = prefix;
5988 this.block = accessor.Block;
5991 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5993 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5996 public void UpdateName (InterfaceMemberBase member)
5998 SetMemberName (SetupName (prefix, member, Location));
6001 #region IMethodData Members
6003 public ToplevelBlock Block {
6013 public CallingConventions CallingConventions {
6015 return CallingConventions.Standard;
6019 public bool IsExcluded ()
6024 GenericMethod IMethodData.GenericMethod {
6030 public MemberName MethodName {
6036 public Type[] ParameterTypes {
6038 return ParameterInfo.Types;
6042 public abstract Parameters ParameterInfo { get ; }
6043 public abstract Type ReturnType { get; }
6044 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6048 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6050 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6051 a.Type == TypeManager.conditional_attribute_type) {
6052 Report.Error (1667, a.Location,
6053 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6054 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6058 if (a.IsValidSecurityAttribute ()) {
6059 if (declarative_security == null)
6060 declarative_security = new ListDictionary ();
6061 a.ExtractSecurityPermissionSet (declarative_security);
6065 if (a.Target == AttributeTargets.Method) {
6066 method_data.MethodBuilder.SetCustomAttribute (cb);
6070 if (a.Target == AttributeTargets.ReturnValue) {
6071 if (return_attributes == null)
6072 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6074 return_attributes.ApplyAttributeBuilder (a, cb);
6078 ApplyToExtraTarget (a, cb);
6081 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6083 throw new NotSupportedException ("You forgot to define special attribute target handling");
6086 // It is not supported for the accessors
6087 public sealed override bool Define()
6089 throw new NotSupportedException ();
6092 public void Emit (DeclSpace parent)
6094 EmitMethod (parent);
6097 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6098 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6099 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6100 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6102 if (OptAttributes != null)
6103 OptAttributes.Emit ();
6105 if (declarative_security != null) {
6106 foreach (DictionaryEntry de in declarative_security) {
6107 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6114 protected virtual void EmitMethod (DeclSpace parent)
6116 method_data.Emit (parent);
6119 public override bool EnableOverloadChecks (MemberCore overload)
6121 // This can only happen with indexers and it will
6122 // be catched as indexer difference
6123 if (overload is AbstractPropertyEventMethod)
6126 if (overload is MethodCore) {
6127 caching_flags |= Flags.MethodOverloadsExist;
6133 public override bool IsClsComplianceRequired()
6138 public bool IsDuplicateImplementation (MethodCore method)
6140 if (!MemberName.Equals (method.MemberName))
6143 Type[] param_types = method.ParameterTypes;
6145 if (param_types == null || param_types.Length != ParameterTypes.Length)
6148 for (int i = 0; i < param_types.Length; i++)
6149 if (param_types [i] != ParameterTypes [i])
6152 Report.SymbolRelatedToPreviousError (method);
6153 Report.Error (82, Location, "A member `{0}' is already reserved",
6154 method.GetSignatureForError ());
6158 public override bool IsUsed
6169 // Represents header string for documentation comment.
6171 public override string DocCommentHeader {
6172 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6175 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6180 // Properties and Indexers both generate PropertyBuilders, we use this to share
6181 // their common bits.
6183 abstract public class PropertyBase : PropertyBasedMember {
6185 public class GetMethod : PropertyMethod
6187 static string[] attribute_targets = new string [] { "method", "return" };
6189 public GetMethod (PropertyBase method):
6190 base (method, "get_")
6194 public GetMethod (PropertyBase method, Accessor accessor):
6195 base (method, accessor, "get_")
6199 public override MethodBuilder Define (DeclSpace parent)
6201 if (!CheckForDuplications ())
6207 base.Define (parent);
6209 method_data = new MethodData (method, ModFlags, flags, this);
6211 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6214 return method_data.MethodBuilder;
6217 public override Type ReturnType {
6219 return method.MemberType;
6223 public override Parameters ParameterInfo {
6225 return Parameters.EmptyReadOnlyParameters;
6229 public override string[] ValidAttributeTargets {
6231 return attribute_targets;
6236 public class SetMethod : PropertyMethod {
6238 static string[] attribute_targets = new string [] { "method", "param", "return" };
6239 ImplicitParameter param_attr;
6240 protected Parameters parameters;
6242 public SetMethod (PropertyBase method):
6243 base (method, "set_")
6247 public SetMethod (PropertyBase method, Accessor accessor):
6248 base (method, accessor, "set_")
6252 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6254 if (a.Target == AttributeTargets.Parameter) {
6255 if (param_attr == null)
6256 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6258 param_attr.ApplyAttributeBuilder (a, cb);
6262 base.ApplyAttributeBuilder (a, cb);
6265 public override Parameters ParameterInfo {
6267 if (parameters == null)
6268 DefineParameters ();
6273 protected virtual void DefineParameters ()
6275 parameters = Parameters.CreateFullyResolved (
6276 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6279 public override MethodBuilder Define (DeclSpace parent)
6281 if (!CheckForDuplications ())
6287 base.Define (parent);
6289 method_data = new MethodData (method, ModFlags, flags, this);
6291 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6294 return method_data.MethodBuilder;
6297 public override Type ReturnType {
6299 return TypeManager.void_type;
6303 public override string[] ValidAttributeTargets {
6305 return attribute_targets;
6310 static string[] attribute_targets = new string [] { "property" };
6312 public abstract class PropertyMethod : AbstractPropertyEventMethod
6314 protected readonly PropertyBase method;
6315 protected MethodAttributes flags;
6317 public PropertyMethod (PropertyBase method, string prefix)
6318 : base (method, prefix)
6320 this.method = method;
6323 public PropertyMethod (PropertyBase method, Accessor accessor,
6325 : base (method, accessor, prefix)
6327 this.method = method;
6328 this.ModFlags = accessor.ModFlags;
6330 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6331 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6335 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6337 if (a.IsInternalMethodImplAttribute) {
6338 method.is_external_implementation = true;
6341 base.ApplyAttributeBuilder (a, cb);
6344 public override AttributeTargets AttributeTargets {
6346 return AttributeTargets.Method;
6350 public override bool IsClsComplianceRequired ()
6352 return method.IsClsComplianceRequired ();
6355 public virtual MethodBuilder Define (DeclSpace parent)
6357 TypeContainer container = parent.PartialContainer;
6360 // Check for custom access modifier
6362 if ((ModFlags & Modifiers.Accessibility) == 0) {
6363 ModFlags |= method.ModFlags;
6364 flags = method.flags;
6366 if (container.Kind == Kind.Interface)
6367 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6368 GetSignatureForError ());
6370 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6371 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6374 CheckModifiers (ModFlags);
6375 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6376 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6377 flags = Modifiers.MethodAttr (ModFlags);
6378 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6381 CheckAbstractAndExtern (block != null);
6383 if (block != null && block.IsIterator)
6384 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6389 public bool HasCustomAccessModifier
6392 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6396 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6398 return new EmitContext (method,
6399 ds, method.ds, method.Location, ig, ReturnType,
6400 method.ModFlags, false);
6403 public override ObsoleteAttribute GetObsoleteAttribute ()
6405 return method.GetObsoleteAttribute ();
6408 public override string GetSignatureForError()
6410 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6413 void CheckModifiers (int modflags)
6415 modflags &= Modifiers.Accessibility;
6417 int mflags = method.ModFlags & Modifiers.Accessibility;
6419 if ((mflags & Modifiers.PUBLIC) != 0) {
6420 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6422 else if ((mflags & Modifiers.PROTECTED) != 0) {
6423 if ((mflags & Modifiers.INTERNAL) != 0)
6424 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6426 flags |= Modifiers.PRIVATE;
6428 else if ((mflags & Modifiers.INTERNAL) != 0)
6429 flags |= Modifiers.PRIVATE;
6431 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6432 Report.Error (273, Location,
6433 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6434 GetSignatureForError (), method.GetSignatureForError ());
6438 protected bool CheckForDuplications ()
6440 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6443 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6447 public PropertyMethod Get, Set;
6448 public PropertyBuilder PropertyBuilder;
6449 public MethodBuilder GetBuilder, SetBuilder;
6451 protected bool define_set_first = false;
6453 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6454 int allowed_mod, bool is_iface, MemberName name,
6455 Attributes attrs, bool define_set_first)
6456 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6458 this.define_set_first = define_set_first;
6461 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6463 if (a.HasSecurityAttribute) {
6464 a.Error_InvalidSecurityParent ();
6468 PropertyBuilder.SetCustomAttribute (cb);
6471 public override AttributeTargets AttributeTargets {
6473 return AttributeTargets.Property;
6477 public override bool Define ()
6482 if (!IsTypePermitted ())
6488 protected override bool DoDefine ()
6490 if (!base.DoDefine ())
6494 // Accessors modifiers check
6496 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6497 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6498 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6499 GetSignatureForError ());
6503 if ((Get.IsDummy || Set.IsDummy)
6504 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6505 Report.Error (276, Location,
6506 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6507 GetSignatureForError ());
6512 if (MemberType.IsGenericParameter)
6516 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6517 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6526 GetBuilder = Get.Define (Parent);
6527 return (Get.IsDummy) ? true : GetBuilder != null;
6530 bool DefineSet (bool define)
6535 SetBuilder = Set.Define (Parent);
6536 return (Set.IsDummy) ? true : SetBuilder != null;
6539 protected bool DefineAccessors ()
6541 return DefineSet (define_set_first) &&
6543 DefineSet (!define_set_first);
6546 protected abstract PropertyInfo ResolveBaseProperty ();
6548 // TODO: rename to Resolve......
6549 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6551 PropertyInfo base_property = ResolveBaseProperty ();
6552 if (base_property == null)
6555 base_ret_type = base_property.PropertyType;
6556 MethodInfo get_accessor = base_property.GetGetMethod (true);
6557 MethodInfo set_accessor = base_property.GetSetMethod (true);
6558 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6561 // Check base property accessors conflict
6563 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6564 if (get_accessor == null) {
6565 if (Get != null && !Get.IsDummy) {
6566 Report.SymbolRelatedToPreviousError (base_property);
6567 Report.Error (545, Location,
6568 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6569 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6572 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6574 if (!Get.IsDummy && !CheckAccessModifiers (
6575 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6576 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6579 if (set_accessor == null) {
6580 if (Set != null && !Set.IsDummy) {
6581 Report.SymbolRelatedToPreviousError (base_property);
6582 Report.Error (546, Location,
6583 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6584 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6587 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6589 if (!Set.IsDummy && !CheckAccessModifiers (
6590 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6591 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6595 // When one accessor does not exist and property hides base one
6596 // we need to propagate this upwards
6597 if (set_accessor == null)
6598 set_accessor = get_accessor;
6601 // Get the less restrictive access
6603 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6606 public override void Emit ()
6609 // The PropertyBuilder can be null for explicit implementations, in that
6610 // case, we do not actually emit the ".property", so there is nowhere to
6611 // put the attribute
6613 if (PropertyBuilder != null && OptAttributes != null)
6614 OptAttributes.Emit ();
6626 /// Tests whether accessors are not in collision with some method (CS0111)
6628 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6630 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6633 public override bool IsUsed
6639 return Get.IsUsed | Set.IsUsed;
6643 protected override void SetMemberName (MemberName new_name)
6645 base.SetMemberName (new_name);
6647 Get.UpdateName (this);
6648 Set.UpdateName (this);
6651 public override string[] ValidAttributeTargets {
6653 return attribute_targets;
6658 // Represents header string for documentation comment.
6660 public override string DocCommentHeader {
6661 get { return "P:"; }
6665 public class Property : PropertyBase {
6666 const int AllowedModifiers =
6669 Modifiers.PROTECTED |
6670 Modifiers.INTERNAL |
6674 Modifiers.OVERRIDE |
6675 Modifiers.ABSTRACT |
6680 const int AllowedInterfaceModifiers =
6683 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6686 Field field = new Field (
6688 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6689 "<" + Name + ">k__BackingField", null, Location);
6690 ((TypeContainer)Parent).PartialContainer.AddField (field);
6693 get_block.Block = new ToplevelBlock (block, null, Location);
6694 Return r = new Return (new SimpleName(field.Name, Location), Location);
6695 get_block.Block.AddStatement (r);
6696 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6699 Parameters parameters = new Parameters (new Parameter (type_name, "value", Parameter.Modifier.NONE, null, Location));
6700 set_block.Block = new ToplevelBlock (block, parameters, Location);
6701 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6702 set_block.Block.AddStatement (new StatementExpression(a));
6703 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6706 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6707 MemberName name, Attributes attrs, Accessor get_block,
6708 Accessor set_block, bool define_set_first)
6709 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6710 define_set_first, null)
6714 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6715 MemberName name, Attributes attrs, Accessor get_block,
6716 Accessor set_block, bool define_set_first, Block current_block)
6717 : base (parent, type, mod,
6718 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6719 is_iface, name, attrs, define_set_first)
6721 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6722 get_block != null && get_block.Block == null &&
6723 set_block != null && set_block.Block == null) {
6724 if (RootContext.Version <= LanguageVersion.ISO_2)
6725 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6727 CreateAutomaticProperty (current_block, get_block, set_block);
6730 if (get_block == null)
6731 Get = new GetMethod (this);
6733 Get = new GetMethod (this, get_block);
6735 if (set_block == null)
6736 Set = new SetMethod (this);
6738 Set = new SetMethod (this, set_block);
6741 public override bool Define ()
6743 if (!DoDefineBase ())
6746 if (!base.Define ())
6749 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6751 if (!DefineAccessors ())
6757 // FIXME - PropertyAttributes.HasDefault ?
6759 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6760 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6763 PropertyBuilder.SetGetMethod (GetBuilder);
6764 Parent.MemberCache.AddMember (GetBuilder, Get);
6768 PropertyBuilder.SetSetMethod (SetBuilder);
6769 Parent.MemberCache.AddMember (SetBuilder, Set);
6772 TypeManager.RegisterProperty (PropertyBuilder, this);
6773 Parent.MemberCache.AddMember (PropertyBuilder, this);
6777 protected override PropertyInfo ResolveBaseProperty ()
6779 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6780 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6785 /// Gigantic workaround for lameness in SRE follows :
6786 /// This class derives from EventInfo and attempts to basically
6787 /// wrap around the EventBuilder so that FindMembers can quickly
6788 /// return this in it search for members
6790 public class MyEventBuilder : EventInfo {
6793 // We use this to "point" to our Builder which is
6794 // not really a MemberInfo
6796 EventBuilder MyBuilder;
6799 // We "catch" and wrap these methods
6801 MethodInfo raise, remove, add;
6803 EventAttributes attributes;
6804 Type declaring_type, reflected_type, event_type;
6809 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6811 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6813 // And now store the values in our own fields.
6815 declaring_type = type_builder;
6817 reflected_type = type_builder;
6819 attributes = event_attr;
6822 this.event_type = event_type;
6826 // Methods that you have to override. Note that you only need
6827 // to "implement" the variants that take the argument (those are
6828 // the "abstract" methods, the others (GetAddMethod()) are
6831 public override MethodInfo GetAddMethod (bool nonPublic)
6836 public override MethodInfo GetRemoveMethod (bool nonPublic)
6841 public override MethodInfo GetRaiseMethod (bool nonPublic)
6847 // These methods make "MyEventInfo" look like a Builder
6849 public void SetRaiseMethod (MethodBuilder raiseMethod)
6851 raise = raiseMethod;
6852 MyBuilder.SetRaiseMethod (raiseMethod);
6855 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6857 remove = removeMethod;
6858 MyBuilder.SetRemoveOnMethod (removeMethod);
6861 public void SetAddOnMethod (MethodBuilder addMethod)
6864 MyBuilder.SetAddOnMethod (addMethod);
6867 public void SetCustomAttribute (CustomAttributeBuilder cb)
6869 MyBuilder.SetCustomAttribute (cb);
6872 public override object [] GetCustomAttributes (bool inherit)
6874 // FIXME : There's nothing which can be seemingly done here because
6875 // we have no way of getting at the custom attribute objects of the
6880 public override object [] GetCustomAttributes (Type t, bool inherit)
6882 // FIXME : Same here !
6886 public override bool IsDefined (Type t, bool b)
6891 public override EventAttributes Attributes {
6897 public override string Name {
6903 public override Type DeclaringType {
6905 return declaring_type;
6909 public override Type ReflectedType {
6911 return reflected_type;
6915 public Type EventType {
6921 public void SetUsed ()
6923 if (my_event != null) {
6924 // my_event.SetAssigned ();
6925 my_event.SetMemberIsUsed ();
6931 /// For case when event is declared like property (with add and remove accessors).
6933 public class EventProperty: Event {
6934 abstract class AEventPropertyAccessor : AEventAccessor
6936 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6937 base (method, accessor, prefix)
6941 public override MethodBuilder Define (DeclSpace ds)
6943 CheckAbstractAndExtern (block != null);
6944 return base.Define (ds);
6947 public override string GetSignatureForError ()
6949 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6953 sealed class AddDelegateMethod: AEventPropertyAccessor
6955 public AddDelegateMethod (Event method, Accessor accessor):
6956 base (method, accessor, "add_")
6960 protected override MethodInfo DelegateMethodInfo {
6962 return TypeManager.delegate_combine_delegate_delegate;
6967 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6969 public RemoveDelegateMethod (Event method, Accessor accessor):
6970 base (method, accessor, "remove_")
6974 protected override MethodInfo DelegateMethodInfo {
6976 return TypeManager.delegate_remove_delegate_delegate;
6982 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6984 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6985 bool is_iface, MemberName name,
6986 Attributes attrs, Accessor add, Accessor remove)
6987 : base (parent, type, mod_flags, is_iface, name, attrs)
6989 Add = new AddDelegateMethod (this, add);
6990 Remove = new RemoveDelegateMethod (this, remove);
6993 public override bool Define()
6995 if (!base.Define ())
7002 public override string[] ValidAttributeTargets {
7004 return attribute_targets;
7010 /// Event is declared like field.
7012 public class EventField : Event {
7013 abstract class EventFieldAccessor : AEventAccessor
7015 protected EventFieldAccessor (Event method, string prefix)
7016 : base (method, prefix)
7020 protected override void EmitMethod(DeclSpace parent)
7022 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7025 MethodBuilder mb = method_data.MethodBuilder;
7026 ILGenerator ig = mb.GetILGenerator ();
7028 // TODO: because we cannot use generics yet
7029 FieldInfo field_info = ((EventField)method).FieldBuilder;
7031 if (parent is Class) {
7032 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7035 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7036 ig.Emit (OpCodes.Ldsfld, field_info);
7037 ig.Emit (OpCodes.Ldarg_0);
7038 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7039 ig.Emit (OpCodes.Castclass, method.MemberType);
7040 ig.Emit (OpCodes.Stsfld, field_info);
7042 ig.Emit (OpCodes.Ldarg_0);
7043 ig.Emit (OpCodes.Ldarg_0);
7044 ig.Emit (OpCodes.Ldfld, field_info);
7045 ig.Emit (OpCodes.Ldarg_1);
7046 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7047 ig.Emit (OpCodes.Castclass, method.MemberType);
7048 ig.Emit (OpCodes.Stfld, field_info);
7050 ig.Emit (OpCodes.Ret);
7054 sealed class AddDelegateMethod: EventFieldAccessor
7056 public AddDelegateMethod (Event method):
7057 base (method, "add_")
7061 protected override MethodInfo DelegateMethodInfo {
7063 return TypeManager.delegate_combine_delegate_delegate;
7068 sealed class RemoveDelegateMethod: EventFieldAccessor
7070 public RemoveDelegateMethod (Event method):
7071 base (method, "remove_")
7075 protected override MethodInfo DelegateMethodInfo {
7077 return TypeManager.delegate_remove_delegate_delegate;
7083 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7084 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7086 public FieldBuilder FieldBuilder;
7087 public Expression Initializer;
7089 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags,
7090 bool is_iface, MemberName name,
7092 : base (parent, type, mod_flags, is_iface, name, attrs)
7094 Add = new AddDelegateMethod (this);
7095 Remove = new RemoveDelegateMethod (this);
7098 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7100 if (a.Target == AttributeTargets.Field) {
7101 FieldBuilder.SetCustomAttribute (cb);
7105 if (a.Target == AttributeTargets.Method) {
7106 int errors = Report.Errors;
7107 Add.ApplyAttributeBuilder (a, cb);
7108 if (errors == Report.Errors)
7109 Remove.ApplyAttributeBuilder (a, cb);
7113 base.ApplyAttributeBuilder (a, cb);
7116 public override bool Define()
7118 if (!base.Define ())
7124 // FIXME: We are unable to detect whether generic event is used because
7125 // we are using FieldExpr instead of EventExpr for event access in that
7126 // case. When this issue will be fixed this hack can be removed.
7127 if (TypeManager.IsGenericType (MemberType))
7130 if (Add.IsInterfaceImplementation)
7133 FieldBuilder = Parent.TypeBuilder.DefineField (
7135 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7136 TypeManager.RegisterEventField (EventBuilder, this);
7138 if (Initializer != null) {
7139 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7140 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7141 GetSignatureForError ());
7145 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7146 new FieldInitializer (FieldBuilder, Initializer));
7152 public override string[] ValidAttributeTargets
7155 return IsInterface ? attribute_targets_interface : attribute_targets;
7160 public abstract class Event : PropertyBasedMember {
7161 public abstract class AEventAccessor : AbstractPropertyEventMethod
7163 protected readonly Event method;
7164 ImplicitParameter param_attr;
7166 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7168 protected AEventAccessor (Event method, string prefix)
7169 : base (method, prefix)
7171 this.method = method;
7172 this.ModFlags = method.ModFlags;
7175 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7176 : base (method, accessor, prefix)
7178 this.method = method;
7179 this.ModFlags = method.ModFlags;
7182 public bool IsInterfaceImplementation {
7183 get { return method_data.implementing != null; }
7186 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7188 if (a.IsInternalMethodImplAttribute) {
7189 method.is_external_implementation = true;
7192 base.ApplyAttributeBuilder (a, cb);
7195 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7197 if (a.Target == AttributeTargets.Parameter) {
7198 if (param_attr == null)
7199 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7201 param_attr.ApplyAttributeBuilder (a, cb);
7205 base.ApplyAttributeBuilder (a, cb);
7208 public override AttributeTargets AttributeTargets {
7210 return AttributeTargets.Method;
7214 public override bool IsClsComplianceRequired ()
7216 return method.IsClsComplianceRequired ();
7219 public virtual MethodBuilder Define (DeclSpace parent)
7221 method_data = new MethodData (method, method.ModFlags,
7222 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7224 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7227 MethodBuilder mb = method_data.MethodBuilder;
7228 ParameterInfo.ApplyAttributes (mb);
7232 protected abstract MethodInfo DelegateMethodInfo { get; }
7234 public override Type ReturnType {
7236 return TypeManager.void_type;
7240 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7242 return new EmitContext (
7243 this, method.Parent, Location, ig, ReturnType,
7244 method.ModFlags, false);
7247 public override ObsoleteAttribute GetObsoleteAttribute ()
7249 return method.GetObsoleteAttribute ();
7252 public override string[] ValidAttributeTargets {
7254 return attribute_targets;
7258 public override Parameters ParameterInfo {
7260 return method.parameters;
7266 const int AllowedModifiers =
7269 Modifiers.PROTECTED |
7270 Modifiers.INTERNAL |
7275 Modifiers.OVERRIDE |
7277 Modifiers.ABSTRACT |
7280 const int AllowedInterfaceModifiers =
7283 public AEventAccessor Add, Remove;
7284 public MyEventBuilder EventBuilder;
7285 public MethodBuilder AddBuilder, RemoveBuilder;
7287 Parameters parameters;
7289 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags,
7290 bool is_iface, MemberName name, Attributes attrs)
7291 : base (parent, null, type, mod_flags,
7292 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7297 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7299 if ((a.HasSecurityAttribute)) {
7300 a.Error_InvalidSecurityParent ();
7304 EventBuilder.SetCustomAttribute (cb);
7307 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7309 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7312 public override AttributeTargets AttributeTargets {
7314 return AttributeTargets.Event;
7318 public override bool Define ()
7320 if (!DoDefineBase ())
7326 if (!TypeManager.IsDelegateType (MemberType)) {
7327 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7331 parameters = Parameters.CreateFullyResolved (
7332 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7337 if (TypeManager.delegate_combine_delegate_delegate == null) {
7338 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7339 TypeManager.delegate_type, "Combine", Location,
7340 TypeManager.delegate_type, TypeManager.delegate_type);
7342 if (TypeManager.delegate_remove_delegate_delegate == null) {
7343 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7344 TypeManager.delegate_type, "Remove", Location,
7345 TypeManager.delegate_type, TypeManager.delegate_type);
7349 // Now define the accessors
7352 AddBuilder = Add.Define (Parent);
7353 if (AddBuilder == null)
7356 RemoveBuilder = Remove.Define (Parent);
7357 if (RemoveBuilder == null)
7360 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7361 EventBuilder.SetAddOnMethod (AddBuilder);
7362 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7364 Parent.MemberCache.AddMember (EventBuilder, this);
7365 Parent.MemberCache.AddMember (AddBuilder, Add);
7366 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7371 public override void Emit ()
7373 if (OptAttributes != null) {
7374 OptAttributes.Emit ();
7378 Remove.Emit (Parent);
7383 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7385 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7386 Parent.TypeBuilder, Name);
7391 ParameterData pd = TypeManager.GetParameterData (mi);
7392 base_ret_type = pd.ParameterType (0);
7397 // Represents header string for documentation comment.
7399 public override string DocCommentHeader {
7400 get { return "E:"; }
7405 public class Indexer : PropertyBase
7407 public class GetIndexerMethod : GetMethod
7409 Parameters parameters;
7411 public GetIndexerMethod (PropertyBase method):
7416 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7417 base (method, accessor)
7421 public override MethodBuilder Define (DeclSpace parent)
7424 // Clone indexer accessor parameters for localized capturing
7426 parameters = ((Indexer) method).parameters.Clone ();
7427 return base.Define (parent);
7430 public override bool EnableOverloadChecks (MemberCore overload)
7432 if (base.EnableOverloadChecks (overload)) {
7433 overload.caching_flags |= Flags.MethodOverloadsExist;
7440 public override Parameters ParameterInfo {
7447 public class SetIndexerMethod: SetMethod
7449 public SetIndexerMethod (PropertyBase method):
7454 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7455 base (method, accessor)
7459 protected override void DefineParameters ()
7461 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7462 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7465 public override bool EnableOverloadChecks (MemberCore overload)
7467 if (base.EnableOverloadChecks (overload)) {
7468 overload.caching_flags |= Flags.MethodOverloadsExist;
7476 const int AllowedModifiers =
7479 Modifiers.PROTECTED |
7480 Modifiers.INTERNAL |
7484 Modifiers.OVERRIDE |
7489 const int AllowedInterfaceModifiers =
7492 public readonly Parameters parameters;
7494 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7495 bool is_iface, Parameters parameters, Attributes attrs,
7496 Accessor get_block, Accessor set_block, bool define_set_first)
7497 : base (parent, type, mod,
7498 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7499 is_iface, name, attrs, define_set_first)
7501 if (type == TypeManager.system_void_expr)
7502 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7504 this.parameters = parameters;
7506 if (get_block == null)
7507 Get = new GetIndexerMethod (this);
7509 Get = new GetIndexerMethod (this, get_block);
7511 if (set_block == null)
7512 Set = new SetIndexerMethod (this);
7514 Set = new SetIndexerMethod (this, set_block);
7517 public override bool Define ()
7519 if (!DoDefineBase ())
7522 if (!base.Define ())
7525 if (!DefineParameters (parameters))
7528 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7529 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7530 if (indexer_attr != null) {
7531 // Remove the attribute from the list because it is not emitted
7532 OptAttributes.Attrs.Remove (indexer_attr);
7534 string name = indexer_attr.GetIndexerAttributeValue ();
7540 if (IsExplicitImpl) {
7541 Report.Error (415, indexer_attr.Location,
7542 "The `IndexerName' attribute is valid only on an " +
7543 "indexer that is not an explicit interface member declaration");
7547 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7548 Report.Error (609, indexer_attr.Location,
7549 "Cannot set the `IndexerName' attribute on an indexer marked override");
7555 if (InterfaceType != null) {
7556 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7557 if (base_IndexerName != Name)
7558 ShortName = base_IndexerName;
7561 if (!Parent.PartialContainer.AddMember (this) ||
7562 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7565 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7566 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7570 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7572 if (!DefineAccessors ())
7579 // Now name the parameters
7581 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7582 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7585 PropertyBuilder.SetGetMethod (GetBuilder);
7586 Parent.MemberCache.AddMember (GetBuilder, Get);
7590 PropertyBuilder.SetSetMethod (SetBuilder);
7591 Parent.MemberCache.AddMember (SetBuilder, Set);
7594 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7595 Parent.MemberCache.AddMember (PropertyBuilder, this);
7599 public override bool EnableOverloadChecks (MemberCore overload)
7601 if (overload is Indexer) {
7602 caching_flags |= Flags.MethodOverloadsExist;
7609 public override string GetDocCommentName (DeclSpace ds)
7611 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7614 public override string GetSignatureForError ()
7616 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7617 if (MemberName.Left != null) {
7619 sb.Append (MemberName.Left.GetSignatureForError ());
7622 sb.Append (".this");
7623 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7624 return sb.ToString ();
7627 protected override PropertyInfo ResolveBaseProperty ()
7629 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7630 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7633 protected override bool VerifyClsCompliance ()
7635 if (!base.VerifyClsCompliance ())
7638 parameters.VerifyClsCompliance ();
7643 public class Operator : MethodOrOperator {
7645 const int AllowedModifiers =
7651 public enum OpType : byte {
7661 // Unary and Binary operators
7684 // Implicit and Explicit
7688 // Just because of enum
7692 public readonly OpType OperatorType;
7694 static readonly string [] [] names;
7698 names = new string[(int)OpType.TOP][];
7699 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7700 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7701 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7702 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7703 names [(int) OpType.True] = new string [] { "true", "op_True" };
7704 names [(int) OpType.False] = new string [] { "false", "op_False" };
7705 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7706 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7707 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7708 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7709 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7710 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7711 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7712 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7713 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7714 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7715 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7716 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7717 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7718 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7719 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7720 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7721 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7722 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7723 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7724 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7727 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7728 int mod_flags, Parameters parameters,
7729 ToplevelBlock block, Attributes attrs, Location loc)
7730 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7731 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7733 OperatorType = type;
7737 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7739 if (a.Type == TypeManager.conditional_attribute_type) {
7740 Error_ConditionalAttributeIsNotValid ();
7744 base.ApplyAttributeBuilder (a, cb);
7747 public override bool Define ()
7749 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7750 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7751 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7755 if (!base.Define ())
7758 // imlicit and explicit operator of same types are not allowed
7759 if (OperatorType == OpType.Explicit)
7760 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7761 else if (OperatorType == OpType.Implicit)
7762 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7764 if (MemberType == TypeManager.void_type) {
7765 Report.Error (590, Location, "User-defined operators cannot return void");
7769 Type declaring_type = MethodData.DeclaringType;
7770 Type return_type = MemberType;
7771 Type first_arg_type = ParameterTypes [0];
7773 Type first_arg_type_unwrap = first_arg_type;
7774 if (TypeManager.IsNullableType (first_arg_type))
7775 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7777 Type return_type_unwrap = return_type;
7778 if (TypeManager.IsNullableType (return_type))
7779 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7782 // Rules for conversion operators
7784 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7785 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7786 Report.Error (555, Location,
7787 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7792 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7793 conv_type = first_arg_type;
7794 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7795 conv_type = return_type;
7797 Report.Error (556, Location,
7798 "User-defined conversion must convert to or from the enclosing type");
7803 // Because IsInterface and IsClass are not supported
7805 if (!TypeManager.IsGenericParameter (conv_type)) {
7806 if (conv_type.IsInterface) {
7807 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7808 GetSignatureForError ());
7812 if (conv_type.IsClass) {
7813 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7814 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7815 GetSignatureForError ());
7819 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7820 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7821 GetSignatureForError ());
7826 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7827 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7828 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");
7831 } else if (Parameters.Count == 1) {
7832 // Checks for Unary operators
7834 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7835 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7836 Report.Error (448, Location,
7837 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7840 if (first_arg_type != declaring_type) {
7842 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7847 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7848 Report.Error (562, Location,
7849 "The parameter type of a unary operator must be the containing type");
7853 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7854 if (return_type != TypeManager.bool_type){
7857 "The return type of operator True or False " +
7864 // Checks for Binary operators
7866 if (first_arg_type != declaring_type &&
7867 ParameterTypes [1] != declaring_type){
7870 "One of the parameters of a binary operator must " +
7871 "be the containing type");
7879 protected override bool DoDefine ()
7881 if (!base.DoDefine ())
7884 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7888 public override void Emit ()
7892 Parameters.ApplyAttributes (MethodBuilder);
7895 // abstract or extern methods have no bodies
7897 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7901 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7902 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7904 ec = CreateEmitContext (Parent, null);
7906 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7907 ec.EmitTopBlock (this, Block);
7910 source.CloseMethod ();
7915 // Operator cannot be override
7916 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7921 public static string GetName (OpType ot)
7923 return names [(int) ot] [0];
7926 public static string GetName (string metadata_name)
7928 for (int i = 0; i < names.Length; ++i) {
7929 if (names [i] [1] == metadata_name)
7930 return names [i] [0];
7935 public static string GetMetadataName (OpType ot)
7937 return names [(int) ot] [1];
7940 public static string GetMetadataName (string name)
7942 for (int i = 0; i < names.Length; ++i) {
7943 if (names [i] [0] == name)
7944 return names [i] [1];
7949 public OpType GetMatchingOperator ()
7951 switch (OperatorType) {
7952 case OpType.Equality:
7953 return OpType.Inequality;
7954 case OpType.Inequality:
7955 return OpType.Equality;
7957 return OpType.False;
7960 case OpType.GreaterThan:
7961 return OpType.LessThan;
7962 case OpType.LessThan:
7963 return OpType.GreaterThan;
7964 case OpType.GreaterThanOrEqual:
7965 return OpType.LessThanOrEqual;
7966 case OpType.LessThanOrEqual:
7967 return OpType.GreaterThanOrEqual;
7973 public override string GetSignatureForError ()
7975 StringBuilder sb = new StringBuilder ();
7976 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7977 sb.AppendFormat ("{0}.{1} operator {2}",
7978 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7981 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7984 sb.Append (Parameters.GetSignatureForError ());
7985 return sb.ToString ();
7990 // This is used to compare method signatures
7992 struct MethodSignature {
7994 public Type RetType;
7995 public Type [] Parameters;
7998 /// This delegate is used to extract methods which have the
7999 /// same signature as the argument
8001 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8003 public MethodSignature (string name, Type ret_type, Type [] parameters)
8008 if (parameters == null)
8009 Parameters = Type.EmptyTypes;
8011 Parameters = parameters;
8014 public override string ToString ()
8017 if (Parameters.Length != 0){
8018 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8019 for (int i = 0; i < Parameters.Length; i++){
8020 sb.Append (Parameters [i]);
8021 if (i+1 < Parameters.Length)
8024 pars = sb.ToString ();
8027 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8030 public override int GetHashCode ()
8032 return Name.GetHashCode ();
8035 public override bool Equals (Object o)
8037 MethodSignature other = (MethodSignature) o;
8039 if (other.Name != Name)
8042 if (other.RetType != RetType)
8045 if (Parameters == null){
8046 if (other.Parameters == null)
8051 if (other.Parameters == null)
8054 int c = Parameters.Length;
8055 if (other.Parameters.Length != c)
8058 for (int i = 0; i < c; i++)
8059 if (other.Parameters [i] != Parameters [i])
8065 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8067 MethodSignature sig = (MethodSignature) filter_criteria;
8069 if (m.Name != sig.Name)
8073 MethodInfo mi = m as MethodInfo;
8074 PropertyInfo pi = m as PropertyInfo;
8077 ReturnType = mi.ReturnType;
8078 else if (pi != null)
8079 ReturnType = pi.PropertyType;
8084 // we use sig.RetType == null to mean `do not check the
8085 // method return value.
8087 if (sig.RetType != null) {
8088 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8094 args = TypeManager.GetParameterData (mi).Types;
8096 args = TypeManager.GetArgumentTypes (pi);
8097 Type [] sigp = sig.Parameters;
8099 if (args.Length != sigp.Length)
8102 for (int i = args.Length - 1; i >= 0; i--)
8103 if (!TypeManager.IsEqual (args [i], sigp [i]))