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 public virtual void SetYields ()
3330 ModFlags |= Modifiers.METHOD_YIELDS;
3333 protected override bool VerifyClsCompliance ()
3335 if (!base.VerifyClsCompliance ())
3338 if (Parameters.HasArglist) {
3339 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3342 if (!AttributeTester.IsClsCompliant (MemberType)) {
3343 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3344 GetSignatureForError ());
3347 Parameters.VerifyClsCompliance ();
3353 public abstract class InterfaceMemberBase : MemberBase {
3355 // Whether this is an interface member.
3357 public bool IsInterface;
3360 // If true, this is an explicit interface implementation
3362 public bool IsExplicitImpl;
3364 protected bool is_external_implementation;
3367 // The interface type we are explicitly implementing
3369 public Type InterfaceType;
3372 // The method we're overriding if this is an override method.
3374 protected MethodInfo base_method;
3376 readonly int explicit_mod_flags;
3377 public MethodAttributes flags;
3379 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3380 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3381 MemberName name, Attributes attrs)
3382 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3385 IsInterface = is_iface;
3386 IsExplicitImpl = (MemberName.Left != null);
3387 explicit_mod_flags = mod;
3390 protected override bool CheckBase ()
3392 if (!base.CheckBase ())
3398 // Is null for System.Object while compiling corlib and base interfaces
3399 if (Parent.PartialContainer.BaseCache == null) {
3400 if ((ModFlags & Modifiers.NEW) != 0) {
3401 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3406 Type base_ret_type = null;
3407 base_method = FindOutBaseMethod (ref base_ret_type);
3409 // method is override
3410 if (base_method != null) {
3411 if (!CheckMethodAgainstBase (base_ret_type))
3414 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3415 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3417 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3418 Report.SymbolRelatedToPreviousError (base_method);
3419 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3420 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3423 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3424 Report.SymbolRelatedToPreviousError (base_method);
3425 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3426 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3433 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3434 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3435 if (conflict_symbol != null) {
3436 Report.SymbolRelatedToPreviousError (conflict_symbol);
3438 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3439 else if (this is PropertyBase)
3440 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3442 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3444 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3445 GetSignatureForError (), SimpleName.GetMemberType (this));
3450 if (conflict_symbol == null) {
3451 if ((ModFlags & Modifiers.NEW) != 0) {
3452 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3457 if ((ModFlags & Modifiers.NEW) == 0) {
3458 if (this is Method && conflict_symbol is MethodBase)
3461 Report.SymbolRelatedToPreviousError (conflict_symbol);
3462 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3463 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3470 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3471 // that have been defined.
3473 // `name' is the user visible name for reporting errors (this is used to
3474 // provide the right name regarding method names and properties)
3476 bool CheckMethodAgainstBase (Type base_method_type)
3480 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3481 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3482 Report.Error (506, Location,
3483 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3484 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3488 // Now we check that the overriden method is not final
3490 if (base_method.IsFinal) {
3491 Report.SymbolRelatedToPreviousError (base_method);
3492 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3493 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3497 // Check that the permissions are not being changed
3499 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3500 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3502 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3503 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3507 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3508 Report.SymbolRelatedToPreviousError (base_method);
3509 if (this is PropertyBasedMember) {
3510 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3511 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3514 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3515 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3521 if ((ModFlags & Modifiers.NEW) == 0) {
3522 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3523 ModFlags |= Modifiers.NEW;
3524 Report.SymbolRelatedToPreviousError (base_method);
3525 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3526 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",
3527 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3529 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3530 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3534 if (base_method.IsAbstract && !IsInterface) {
3535 Report.SymbolRelatedToPreviousError (base_method);
3536 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3537 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3545 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3547 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3549 // when overriding protected internal, the method can be declared
3550 // protected internal only within the same assembly or assembly
3551 // which has InternalsVisibleTo
3553 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3554 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3555 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3557 // if it's not "protected internal", it must be "protected"
3561 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3563 // protected within the same assembly - an error
3566 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3567 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3569 // protected ok, but other attributes differ - report an error
3575 return (thisp == base_classp);
3579 protected bool DefineParameters (Parameters parameters)
3581 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3583 if (!parameters.Resolve (rc))
3587 foreach (Parameter p in parameters.FixedParameters) {
3588 if (p.CheckAccessibility (this))
3591 Report.SymbolRelatedToPreviousError (p.ParameterType);
3592 if (this is Indexer)
3593 Report.Error (55, Location,
3594 "Inconsistent accessibility: parameter type `" +
3595 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3596 "accessible than indexer `" + GetSignatureForError () + "'");
3597 else if (this is Operator)
3598 Report.Error (57, Location,
3599 "Inconsistent accessibility: parameter type `" +
3600 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3601 "accessible than operator `" + GetSignatureForError () + "'");
3603 Report.Error (51, Location,
3604 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3605 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3611 protected override bool DoDefine()
3613 if (!base.DoDefine ())
3616 if (IsExplicitImpl) {
3617 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3621 InterfaceType = texpr.Type;
3623 if (!InterfaceType.IsInterface) {
3624 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3628 if (!Parent.PartialContainer.VerifyImplements (this))
3635 protected bool DoDefineBase ()
3638 throw new InternalErrorException ();
3641 ModFlags = Modifiers.PUBLIC |
3642 Modifiers.ABSTRACT |
3643 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3645 flags = MethodAttributes.Public |
3646 MethodAttributes.Abstract |
3647 MethodAttributes.HideBySig |
3648 MethodAttributes.NewSlot |
3649 MethodAttributes.Virtual;
3651 if (!Parent.PartialContainer.MethodModifiersValid (this))
3654 flags = Modifiers.MethodAttr (ModFlags);
3657 if (IsExplicitImpl) {
3658 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3659 if (iface_texpr == null)
3662 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3663 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3664 GetSignatureForError ());
3668 InterfaceType = iface_texpr.Type;
3670 if (!InterfaceType.IsInterface) {
3671 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3675 if (!Parent.PartialContainer.VerifyImplements (this))
3678 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3684 public override void Emit()
3686 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3687 // We are more strict than Microsoft and report CS0626 as error
3688 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3689 Report.Error (626, Location,
3690 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3691 GetSignatureForError ());
3697 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3699 Report.SymbolRelatedToPreviousError (base_method);
3700 string base_name = TypeManager.GetFullNameSignature (base_method);
3701 string this_name = GetSignatureForError ();
3702 if (suffix != null) {
3703 base_name += suffix;
3704 this_name += suffix;
3707 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3708 this_name, Modifiers.GetDescription (ma), base_name);
3711 protected static string Error722 {
3713 return "`{0}': static types cannot be used as return types";
3718 /// Gets base method and its return type
3720 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3723 // The "short" name of this property / indexer / event. This is the
3724 // name without the explicit interface.
3726 public string ShortName
3728 get { return MemberName.Name; }
3729 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3732 public string GetFullName (MemberName name)
3734 if (!IsExplicitImpl)
3737 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3740 protected override bool VerifyClsCompliance ()
3742 if (!base.VerifyClsCompliance ()) {
3743 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3744 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3747 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3748 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3753 if (GenericMethod != null)
3754 GenericMethod.VerifyClsCompliance ();
3759 public override bool IsUsed
3761 get { return IsExplicitImpl || base.IsUsed; }
3766 public abstract class MethodOrOperator : MethodCore, IMethodData
3768 public MethodBuilder MethodBuilder;
3769 ReturnParameter return_attributes;
3770 ListDictionary declarative_security;
3771 protected MethodData MethodData;
3773 static string[] attribute_targets = new string [] { "method", "return" };
3775 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3776 int allowed_mod, bool is_interface, MemberName name,
3777 Attributes attrs, Parameters parameters)
3778 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3783 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3785 if (a.Target == AttributeTargets.ReturnValue) {
3786 if (return_attributes == null)
3787 return_attributes = new ReturnParameter (MethodBuilder, Location);
3789 return_attributes.ApplyAttributeBuilder (a, cb);
3793 if (a.IsInternalMethodImplAttribute) {
3794 is_external_implementation = true;
3797 if (a.Type == TypeManager.dllimport_type) {
3798 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3799 if ((ModFlags & extern_static) != extern_static) {
3800 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3802 is_external_implementation = true;
3805 if (a.IsValidSecurityAttribute ()) {
3806 if (declarative_security == null)
3807 declarative_security = new ListDictionary ();
3808 a.ExtractSecurityPermissionSet (declarative_security);
3812 if (MethodBuilder != null)
3813 MethodBuilder.SetCustomAttribute (cb);
3816 public override AttributeTargets AttributeTargets {
3818 return AttributeTargets.Method;
3822 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3824 return new EmitContext (
3825 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3828 protected bool DefineGenericMethod ()
3830 if (!DoDefineBase ())
3834 if (GenericMethod != null) {
3835 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3836 if (!GenericMethod.Define (MethodBuilder, block))
3844 public bool ResolveMembers ()
3846 if (!DefineGenericMethod ())
3852 public override bool Define ()
3857 if (!CheckAbstractAndExtern (block != null))
3860 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3861 for (int i = 0; i < Parameters.Count; ++i ) {
3862 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
3863 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3864 GetSignatureForError ());
3873 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0)
3874 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3876 if (IsPartialDefinition) {
3877 caching_flags &= ~Flags.Excluded_Undetected;
3878 caching_flags |= Flags.Excluded;
3879 // Add to member cache only when a partial method implementation is not there
3880 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3881 MethodBase mb = new PartialMethodDefinitionInfo (this);
3882 Parent.MemberCache.AddMember (mb, this);
3883 TypeManager.AddMethod (mb, this);
3889 MethodData = new MethodData (
3890 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3892 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3895 MethodBuilder = MethodData.MethodBuilder;
3898 if (MethodBuilder.IsGenericMethod)
3899 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3902 Parent.MemberCache.AddMember (MethodBuilder, this);
3904 if (!TypeManager.IsGenericParameter (MemberType)) {
3905 if (MemberType.IsAbstract && MemberType.IsSealed) {
3906 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3914 public override void Emit ()
3917 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3918 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3919 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3920 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3922 if (OptAttributes != null)
3923 OptAttributes.Emit ();
3925 if (declarative_security != null) {
3926 foreach (DictionaryEntry de in declarative_security) {
3927 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3934 protected void Error_ConditionalAttributeIsNotValid ()
3936 Report.Error (577, Location,
3937 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3938 GetSignatureForError ());
3941 public bool IsPartialDefinition {
3943 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3947 public bool IsPartialImplementation {
3949 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3953 public override string[] ValidAttributeTargets {
3955 return attribute_targets;
3959 #region IMethodData Members
3961 public CallingConventions CallingConventions {
3963 CallingConventions cc = Parameters.CallingConvention;
3965 if ((ModFlags & Modifiers.STATIC) == 0)
3966 cc |= CallingConventions.HasThis;
3968 // FIXME: How is `ExplicitThis' used in C#?
3974 public Type ReturnType {
3980 public MemberName MethodName {
3986 protected override bool CheckBase ()
3988 if (!base.CheckBase ())
3991 // TODO: Destructor should derive from MethodCore
3992 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3993 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3994 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4002 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4004 public bool IsExcluded () {
4005 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4006 return (caching_flags & Flags.Excluded) != 0;
4008 caching_flags &= ~Flags.Excluded_Undetected;
4010 if (base_method == null) {
4011 if (OptAttributes == null)
4014 if (TypeManager.conditional_attribute_type == null)
4017 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4022 foreach (Attribute a in attrs) {
4023 string condition = a.GetConditionalAttributeValue ();
4024 if (condition == null)
4027 if (RootContext.AllDefines.Contains (condition))
4031 caching_flags |= Flags.Excluded;
4035 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4037 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4038 caching_flags |= Flags.Excluded;
4044 if (md.IsExcluded ()) {
4045 caching_flags |= Flags.Excluded;
4051 GenericMethod IMethodData.GenericMethod {
4053 return GenericMethod;
4057 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4064 public class SourceMethod : IMethodDef
4067 SourceMethodBuilder builder;
4069 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4071 this.method = method;
4073 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4076 public string Name {
4077 get { return method.Name; }
4082 if (method is MethodBuilder)
4083 return ((MethodBuilder) method).GetToken ().Token;
4084 else if (method is ConstructorBuilder)
4085 return ((ConstructorBuilder) method).GetToken ().Token;
4087 throw new NotSupportedException ();
4091 public void CloseMethod ()
4093 SymbolWriter.CloseMethod ();
4096 public void SetRealMethodName (string name)
4098 if (builder != null)
4099 builder.SetRealMethodName (name);
4102 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4104 if (!SymbolWriter.HasSymbolWriter)
4109 Location start_loc = block.StartLocation;
4110 if (start_loc.IsNull)
4113 ICompileUnit compile_unit = start_loc.CompilationUnit;
4114 if (compile_unit == null)
4117 return new SourceMethod (parent, method, compile_unit);
4121 public class Method : MethodOrOperator, IAnonymousHost {
4124 /// Modifiers allowed in a class declaration
4126 const int AllowedModifiers =
4129 Modifiers.PROTECTED |
4130 Modifiers.INTERNAL |
4135 Modifiers.OVERRIDE |
4136 Modifiers.ABSTRACT |
4138 Modifiers.METHOD_YIELDS |
4141 const int AllowedInterfaceModifiers =
4142 Modifiers.NEW | Modifiers.UNSAFE;
4145 // return_type can be "null" for VOID values.
4147 public Method (DeclSpace parent, GenericMethod generic,
4148 FullNamedExpression return_type, int mod, bool is_iface,
4149 MemberName name, Parameters parameters, Attributes attrs)
4150 : base (parent, generic, return_type, mod,
4151 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4152 is_iface, name, attrs, parameters)
4156 public override string GetSignatureForError()
4158 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4161 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4163 Report.Error (17, location,
4164 "Program `{0}' has more than one entry point defined: `{1}'",
4165 CodeGen.FileName, TypeManager.CSharpSignature(b));
4168 bool IsEntryPoint ()
4170 if (ReturnType != TypeManager.void_type &&
4171 ReturnType != TypeManager.int32_type)
4174 if (Parameters.Count == 0)
4177 if (Parameters.Count > 1)
4180 Type t = Parameters.ParameterType (0);
4181 return t.IsArray && t.GetArrayRank () == 1 &&
4182 TypeManager.GetElementType (t) == TypeManager.string_type &&
4183 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4186 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4188 if (a.Type == TypeManager.conditional_attribute_type) {
4189 if (IsExplicitImpl) {
4190 Error_ConditionalAttributeIsNotValid ();
4194 if (ReturnType != TypeManager.void_type) {
4195 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4199 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4200 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4205 Report.Error (582, Location, "Conditional not valid on interface members");
4209 if (MethodData.implementing != null) {
4210 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4211 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4212 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4216 for (int i = 0; i < Parameters.Count; ++i) {
4217 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4218 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4224 if (a.Type == TypeManager.extension_attribute_type) {
4225 a.Error_MisusedExtensionAttribute ();
4229 base.ApplyAttributeBuilder (a, cb);
4232 public bool CheckForDuplications ()
4234 ArrayList ar = Parent.PartialContainer.Properties;
4236 for (int i = 0; i < ar.Count; ++i) {
4237 PropertyBase pb = (PropertyBase) ar [i];
4238 if (pb.AreAccessorsDuplicateImplementation (this))
4243 ar = Parent.PartialContainer.Indexers;
4245 for (int i = 0; i < ar.Count; ++i) {
4246 PropertyBase pb = (PropertyBase) ar [i];
4247 if (pb.AreAccessorsDuplicateImplementation (this))
4258 public override bool Define ()
4260 if (!base.Define ())
4263 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4264 Error1599 (Location, ReturnType);
4268 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4269 Name == "Finalize" && !(this is Destructor)) {
4270 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4273 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4274 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4275 Parent.PartialContainer.Mark_HasEquals ();
4276 else if (Parameters.Empty && Name == "GetHashCode")
4277 Parent.PartialContainer.Mark_HasGetHashCode ();
4280 if ((ModFlags & Modifiers.STATIC) == 0)
4283 if (Parameters.HasExtensionMethodType) {
4284 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4285 if (!Parent.IsTopLevel)
4286 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4287 GetSignatureForError ());
4289 if (TypeManager.extension_attribute_type == null) {
4290 Report.Error (1110, Location,
4291 "`{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",
4292 GetSignatureForError ());
4293 } else if (TypeManager.extension_attribute_attr == null) {
4294 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4295 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4298 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4301 ModFlags |= Modifiers.METHOD_EXTENSION;
4302 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4303 CodeGen.Assembly.HasExtensionMethods = true;
4305 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4306 GetSignatureForError ());
4311 // This is used to track the Entry Point,
4313 if (RootContext.NeedsEntryPoint &&
4315 (RootContext.MainClass == null ||
4316 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4317 if (IsEntryPoint ()) {
4319 if (RootContext.EntryPoint == null) {
4320 if (Parent.IsGeneric || MemberName.IsGeneric) {
4321 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4322 GetSignatureForError ());
4324 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4325 md.SetMemberIsUsed ();
4327 RootContext.EntryPoint = MethodBuilder;
4328 RootContext.EntryPointLocation = Location;
4331 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4332 Error_DuplicateEntryPoint (MethodBuilder, Location);
4335 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4336 GetSignatureForError ());
4346 public override void Emit ()
4349 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4350 if (IsPartialDefinition) {
4352 // Do attribute checks only when partial implementation does not exist
4354 if (MethodBuilder == null)
4360 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4361 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4362 GetSignatureForError ());
4364 MethodData.Emit (Parent);
4368 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4369 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4375 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4376 Location, MethodBuilder);
4381 public override bool EnableOverloadChecks (MemberCore overload)
4383 // TODO: It can be deleted when members will be defined in correct order
4384 if (overload is Operator)
4385 return overload.EnableOverloadChecks (this);
4387 if (overload is Indexer)
4390 return base.EnableOverloadChecks (overload);
4393 public static void Error1599 (Location loc, Type t)
4395 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4398 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4400 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4401 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4406 if (mi.IsSpecialName)
4409 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4413 public void SetPartialDefinition (Method methodDefinition)
4415 caching_flags |= Flags.PartialDefinitionExists;
4416 methodDefinition.MethodBuilder = MethodBuilder;
4417 if (methodDefinition.attributes == null)
4420 if (attributes == null) {
4421 attributes = methodDefinition.attributes;
4423 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4427 protected override bool VerifyClsCompliance ()
4429 if (!base.VerifyClsCompliance ())
4432 if (ParameterInfo.Count > 0) {
4433 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4435 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4442 public abstract class ConstructorInitializer : ExpressionStatement
4444 ArrayList argument_list;
4445 MethodGroupExpr base_constructor_group;
4447 public ConstructorInitializer (ArrayList argument_list, Location loc)
4449 this.argument_list = argument_list;
4453 public ArrayList Arguments {
4455 return argument_list;
4459 public override Expression CreateExpressionTree (EmitContext ec)
4461 throw new NotSupportedException ("ET");
4464 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4466 if (argument_list != null){
4467 foreach (Argument a in argument_list){
4468 if (!a.Resolve (ec, loc))
4473 if (this is ConstructorBaseInitializer) {
4474 if (ec.ContainerType.BaseType == null)
4477 type = ec.ContainerType.BaseType;
4478 if (ec.ContainerType.IsValueType) {
4479 Report.Error (522, loc,
4480 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4485 // It is legal to have "this" initializers that take no arguments
4486 // in structs, they are just no-ops.
4488 // struct D { public D (int a) : this () {}
4490 if (ec.ContainerType.IsValueType && argument_list == null)
4493 type = ec.ContainerType;
4496 base_constructor_group = MemberLookupFinal (
4497 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4498 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4499 loc) as MethodGroupExpr;
4501 if (base_constructor_group == null)
4504 base_constructor_group = base_constructor_group.OverloadResolve (
4505 ec, ref argument_list, false, loc);
4507 if (base_constructor_group == null)
4510 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4512 if (base_ctor == caller_builder){
4513 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4519 public override Expression DoResolve (EmitContext ec)
4521 throw new NotSupportedException ();
4524 public override void Emit (EmitContext ec)
4526 // It can be null for static initializers
4527 if (base_constructor_group == null)
4530 ec.Mark (loc, false);
4532 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4534 base_constructor_group.EmitCall (ec, argument_list);
4537 public override void EmitStatement (EmitContext ec)
4543 public class ConstructorBaseInitializer : ConstructorInitializer {
4544 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4545 base (argument_list, l)
4550 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4551 public GeneratedBaseInitializer (Location loc):
4557 public class ConstructorThisInitializer : ConstructorInitializer {
4558 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4559 base (argument_list, l)
4564 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4565 public ConstructorBuilder ConstructorBuilder;
4566 public ConstructorInitializer Initializer;
4567 ListDictionary declarative_security;
4568 bool has_compliant_args;
4571 // Modifiers allowed for a constructor.
4573 public const int AllowedModifiers =
4575 Modifiers.PROTECTED |
4576 Modifiers.INTERNAL |
4582 static readonly string[] attribute_targets = new string [] { "method" };
4585 // The spec claims that static is not permitted, but
4586 // my very own code has static constructors.
4588 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4589 ConstructorInitializer init, Location loc)
4590 : base (parent, null, null, mod, AllowedModifiers, false,
4591 new MemberName (name, loc), null, args)
4596 public bool HasCompliantArgs {
4597 get { return has_compliant_args; }
4600 public override AttributeTargets AttributeTargets {
4601 get { return AttributeTargets.Constructor; }
4605 // Returns true if this is a default constructor
4607 public bool IsDefault ()
4609 if ((ModFlags & Modifiers.STATIC) != 0)
4610 return Parameters.Empty;
4612 return Parameters.Empty &&
4613 (Initializer is ConstructorBaseInitializer) &&
4614 (Initializer.Arguments == null);
4617 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4619 if (a.IsValidSecurityAttribute ()) {
4620 if (declarative_security == null) {
4621 declarative_security = new ListDictionary ();
4623 a.ExtractSecurityPermissionSet (declarative_security);
4627 if (a.IsInternalMethodImplAttribute) {
4628 is_external_implementation = true;
4631 ConstructorBuilder.SetCustomAttribute (cb);
4634 protected override bool CheckBase ()
4636 if ((ModFlags & Modifiers.STATIC) != 0) {
4637 if (!Parameters.Empty) {
4638 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4639 GetSignatureForError ());
4643 // the rest can be ignored
4647 // Check whether arguments were correct.
4648 if (!DefineParameters (Parameters))
4651 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4652 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4655 if (Parent.PartialContainer.Kind == Kind.Struct) {
4656 if (ParameterTypes.Length == 0) {
4657 Report.Error (568, Location,
4658 "Structs cannot contain explicit parameterless constructors");
4663 CheckProtectedModifier ();
4669 // Creates the ConstructorBuilder
4671 public override bool Define ()
4673 if (ConstructorBuilder != null)
4676 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4677 MethodAttributes.SpecialName);
4679 if ((ModFlags & Modifiers.STATIC) != 0) {
4680 ca |= MethodAttributes.Static | MethodAttributes.Private;
4682 ca |= MethodAttributes.HideBySig;
4684 if ((ModFlags & Modifiers.PUBLIC) != 0)
4685 ca |= MethodAttributes.Public;
4686 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4687 if ((ModFlags & Modifiers.INTERNAL) != 0)
4688 ca |= MethodAttributes.FamORAssem;
4690 ca |= MethodAttributes.Family;
4691 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4692 ca |= MethodAttributes.Assembly;
4694 ca |= MethodAttributes.Private;
4697 if (!CheckAbstractAndExtern (block != null))
4700 // Check if arguments were correct.
4704 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4705 ca, CallingConventions,
4708 if (Parent.PartialContainer.IsComImport) {
4709 if (!IsDefault ()) {
4710 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4711 Parent.GetSignatureForError ());
4714 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4717 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4718 TypeManager.AddMethod (ConstructorBuilder, this);
4720 // It's here only to report an error
4721 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4722 member_type = TypeManager.void_type;
4723 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4732 public override void Emit ()
4734 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4735 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4737 if (OptAttributes != null)
4738 OptAttributes.Emit ();
4742 EmitContext ec = CreateEmitContext (null, null);
4745 // If we use a "this (...)" constructor initializer, then
4746 // do not emit field initializers, they are initialized in the other constructor
4748 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4749 !(Initializer is ConstructorThisInitializer);
4751 if (emit_field_initializers)
4752 Parent.PartialContainer.ResolveFieldInitializers (ec);
4754 if (block != null) {
4755 // If this is a non-static `struct' constructor and doesn't have any
4756 // initializer, it must initialize all of the struct's fields.
4757 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4758 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4759 block.AddThisVariable (Parent, Location);
4761 if (!block.ResolveMeta (ec, ParameterInfo))
4764 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4765 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4766 Initializer = new GeneratedBaseInitializer (Location);
4769 // Spec mandates that Initializers will not have `this' access
4771 if (Initializer != null) {
4773 Initializer.Resolve (ConstructorBuilder, ec);
4774 ec.IsStatic = false;
4775 block.AddScopeStatement (new StatementExpression (Initializer));
4780 Parameters.ApplyAttributes (ConstructorBuilder);
4782 SourceMethod source = null;
4784 ec.OmitDebuggingInfo = true;
4786 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4788 bool unreachable = false;
4789 if (block != null) {
4790 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4793 ec.EmitMeta (block);
4795 if (Report.Errors > 0)
4798 if (emit_field_initializers)
4799 Parent.PartialContainer.EmitFieldInitializers (ec);
4801 ec.EmitResolvedTopBlock (block, unreachable);
4805 source.CloseMethod ();
4807 if (declarative_security != null) {
4808 foreach (DictionaryEntry de in declarative_security) {
4809 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4816 // Is never override
4817 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4822 public override string GetSignatureForError()
4824 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4827 public override string[] ValidAttributeTargets {
4829 return attribute_targets;
4833 protected override bool VerifyClsCompliance ()
4835 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4839 if (ParameterInfo.Count > 0) {
4840 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4842 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4844 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4845 foreach (Type param in ParameterTypes) {
4846 if (param.IsArray) {
4852 has_compliant_args = true;
4856 #region IMethodData Members
4858 public System.Reflection.CallingConventions CallingConventions {
4860 CallingConventions cc = Parameters.CallingConvention;
4862 if (Parent.PartialContainer.Kind == Kind.Class)
4863 if ((ModFlags & Modifiers.STATIC) == 0)
4864 cc |= CallingConventions.HasThis;
4866 // FIXME: How is `ExplicitThis' used in C#?
4872 public MemberName MethodName {
4878 public Type ReturnType {
4884 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4886 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4887 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4888 ec.CurrentBlock = block;
4892 public bool IsExcluded()
4897 GenericMethod IMethodData.GenericMethod {
4903 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4910 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4912 public interface IMethodData
4914 CallingConventions CallingConventions { get; }
4915 Location Location { get; }
4916 MemberName MethodName { get; }
4917 Type ReturnType { get; }
4918 GenericMethod GenericMethod { get; }
4919 Parameters ParameterInfo { get; }
4921 Attributes OptAttributes { get; }
4922 ToplevelBlock Block { get; set; }
4924 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4925 ObsoleteAttribute GetObsoleteAttribute ();
4926 string GetSignatureForError ();
4928 bool IsClsComplianceRequired ();
4929 void SetMemberIsUsed ();
4930 void EmitExtraSymbolInfo (SourceMethod source);
4934 // Encapsulates most of the Method's state
4936 public class MethodData {
4938 static FieldInfo methodbuilder_attrs_field;
4940 readonly IMethodData method;
4942 public readonly GenericMethod GenericMethod;
4945 // Are we implementing an interface ?
4947 public MethodInfo implementing;
4952 protected InterfaceMemberBase member;
4953 protected int modifiers;
4954 protected MethodAttributes flags;
4955 protected Type declaring_type;
4956 protected MethodInfo parent_method;
4958 MethodBuilder builder = null;
4959 public MethodBuilder MethodBuilder {
4965 public Type DeclaringType {
4967 return declaring_type;
4971 public MethodData (InterfaceMemberBase member,
4972 int modifiers, MethodAttributes flags, IMethodData method)
4974 this.member = member;
4975 this.modifiers = modifiers;
4978 this.method = method;
4981 public MethodData (InterfaceMemberBase member,
4982 int modifiers, MethodAttributes flags,
4983 IMethodData method, MethodBuilder builder,
4984 GenericMethod generic, MethodInfo parent_method)
4985 : this (member, modifiers, flags, method)
4987 this.builder = builder;
4988 this.GenericMethod = generic;
4989 this.parent_method = parent_method;
4992 public bool Define (DeclSpace parent, string method_full_name)
4994 string name = method.MethodName.Basename;
4996 TypeContainer container = parent.PartialContainer;
4998 PendingImplementation pending = container.PendingImplementations;
4999 if (pending != null){
5000 if (member is Indexer) // TODO: test it, but it should work without this IF
5001 implementing = pending.IsInterfaceIndexer (
5002 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5004 implementing = pending.IsInterfaceMethod (
5005 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5007 if (member.InterfaceType != null){
5008 if (implementing == null){
5009 if (member is PropertyBase) {
5010 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5011 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5012 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5015 Report.Error (539, method.Location,
5016 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5017 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5021 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5022 Report.SymbolRelatedToPreviousError (implementing);
5023 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5024 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5028 if (implementing != null) {
5029 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5030 if (prop_method == null) {
5031 if (TypeManager.IsSpecialMethod (implementing)) {
5032 Report.SymbolRelatedToPreviousError (implementing);
5033 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5034 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5035 implementing.Name.StartsWith ("get_") ? "get" : "set");
5037 } else if (implementing.DeclaringType.IsInterface) {
5038 if (!implementing.IsSpecialName) {
5039 Report.SymbolRelatedToPreviousError (implementing);
5040 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5041 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5044 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5045 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5046 Report.SymbolRelatedToPreviousError (implementing);
5047 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5048 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5057 // For implicit implementations, make sure we are public, for
5058 // explicit implementations, make sure we are private.
5060 if (implementing != null){
5062 // Setting null inside this block will trigger a more
5063 // verbose error reporting for missing interface implementations
5065 // The "candidate" function has been flagged already
5066 // but it wont get cleared
5068 if (member.IsExplicitImpl){
5069 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5070 Report.SymbolRelatedToPreviousError (implementing);
5071 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5072 method.GetSignatureForError ());
5076 if (implementing.DeclaringType.IsInterface) {
5078 // If this is an interface method implementation,
5079 // check for public accessibility
5081 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5083 implementing = null;
5085 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5086 // We may never be private.
5087 implementing = null;
5089 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5091 // We may be protected if we're overriding something.
5093 implementing = null;
5098 // Static is not allowed
5100 if ((modifiers & Modifiers.STATIC) != 0){
5101 implementing = null;
5106 // If implementing is still valid, set flags
5108 if (implementing != null){
5110 // When implementing interface methods, set NewSlot
5111 // unless, we are overwriting a method.
5113 if (implementing.DeclaringType.IsInterface){
5114 if ((modifiers & Modifiers.OVERRIDE) == 0)
5115 flags |= MethodAttributes.NewSlot;
5118 MethodAttributes.Virtual |
5119 MethodAttributes.HideBySig;
5121 // Set Final unless we're virtual, abstract or already overriding a method.
5122 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5123 flags |= MethodAttributes.Final;
5126 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5128 if (builder == null)
5131 if (container.CurrentType != null)
5132 declaring_type = container.CurrentType;
5134 declaring_type = container.TypeBuilder;
5136 if (implementing != null){
5138 // clear the pending implemntation flag
5140 if (member is Indexer) {
5141 pending.ImplementIndexer (
5142 member.InterfaceType, builder, method.ReturnType,
5143 method.ParameterInfo, member.IsExplicitImpl);
5145 pending.ImplementMethod (
5146 member.InterfaceType, name, method.ReturnType,
5147 method.ParameterInfo, member.IsExplicitImpl);
5149 if (member.IsExplicitImpl)
5150 container.TypeBuilder.DefineMethodOverride (
5151 builder, implementing);
5154 TypeManager.AddMethod (builder, method);
5156 if (GenericMethod != null) {
5157 bool is_override = member.IsExplicitImpl |
5158 ((modifiers & Modifiers.OVERRIDE) != 0);
5160 if (implementing != null)
5161 parent_method = implementing;
5163 EmitContext ec = method.CreateEmitContext (container, null);
5164 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5173 /// Create the MethodBuilder for the method
5175 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5177 if (builder == null) {
5178 builder = container.TypeBuilder.DefineMethod (
5179 method_name, flags, method.CallingConventions,
5180 method.ReturnType, ParameterTypes);
5186 // Generic method has been already defined to resolve method parameters
5187 // correctly when they use type parameters
5189 builder.SetParameters (ParameterTypes);
5190 builder.SetReturnType (method.ReturnType);
5192 if (builder.Attributes != flags) {
5194 if (methodbuilder_attrs_field == null)
5195 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5196 methodbuilder_attrs_field.SetValue (builder, flags);
5198 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5202 throw new InternalErrorException ();
5209 public void Emit (DeclSpace parent)
5211 ToplevelBlock block = method.Block;
5215 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5217 ec = method.CreateEmitContext (parent, null);
5219 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5221 if (GenericMethod != null)
5222 GenericMethod.EmitAttributes ();
5224 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5227 // Handle destructors specially
5229 // FIXME: This code generates buggy code
5231 if (member is Destructor)
5232 EmitDestructor (ec, block);
5234 ec.EmitTopBlock (method, block);
5236 if (source != null) {
5237 method.EmitExtraSymbolInfo (source);
5238 source.CloseMethod ();
5242 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5244 ILGenerator ig = ec.ig;
5246 Label finish = ig.DefineLabel ();
5248 block.SetDestructor ();
5250 ig.BeginExceptionBlock ();
5251 ec.ReturnLabel = finish;
5252 ec.HasReturnLabel = true;
5253 ec.EmitTopBlock (method, block);
5255 // ig.MarkLabel (finish);
5256 ig.BeginFinallyBlock ();
5258 if (ec.ContainerType.BaseType != null) {
5259 Expression member_lookup = Expression.MemberLookup (
5260 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5261 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5263 if (member_lookup != null){
5264 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5266 ig.Emit (OpCodes.Ldarg_0);
5267 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5271 ig.EndExceptionBlock ();
5272 //ig.MarkLabel (ec.ReturnLabel);
5273 ig.Emit (OpCodes.Ret);
5277 // TODO: Should derive from MethodCore
5278 public class Destructor : Method {
5280 static string[] attribute_targets = new string [] { "method" };
5282 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5283 string name, Parameters parameters, Attributes attrs,
5285 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5289 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5291 if (a.Type == TypeManager.conditional_attribute_type) {
5292 Error_ConditionalAttributeIsNotValid ();
5296 base.ApplyAttributeBuilder (a, cb);
5299 public override string GetSignatureForError ()
5301 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5304 public override string[] ValidAttributeTargets {
5306 return attribute_targets;
5311 abstract public class MemberBase : MemberCore {
5312 protected FullNamedExpression type_name;
5313 public readonly DeclSpace ds;
5314 public readonly GenericMethod GenericMethod;
5317 // The type of this property / indexer / event
5319 protected Type member_type;
5320 public Type MemberType {
5322 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5323 if (member_type == null && type_name != null) {
5324 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5325 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5326 if (type_name != null) {
5327 member_type = type_name.Type;
5335 // The constructor is only exposed to our children
5337 protected MemberBase (DeclSpace parent, GenericMethod generic,
5338 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5339 MemberName name, Attributes attrs)
5340 : base (parent, name, attrs)
5342 this.ds = generic != null ? generic : (DeclSpace) parent;
5343 this.type_name = type;
5344 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5345 GenericMethod = generic;
5346 if (GenericMethod != null)
5347 GenericMethod.ModFlags = ModFlags;
5350 protected virtual bool CheckBase ()
5352 CheckProtectedModifier ();
5357 protected virtual bool DoDefine ()
5359 if (MemberType == null)
5362 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5363 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5364 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5365 GetSignatureForError (), Parent.GetSignatureForError ());
5369 // verify accessibility
5370 if (!IsAccessibleAs (MemberType)) {
5371 Report.SymbolRelatedToPreviousError (MemberType);
5372 if (this is Property)
5373 Report.Error (53, Location,
5374 "Inconsistent accessibility: property type `" +
5375 TypeManager.CSharpName (MemberType) + "' is less " +
5376 "accessible than property `" + GetSignatureForError () + "'");
5377 else if (this is Indexer)
5378 Report.Error (54, Location,
5379 "Inconsistent accessibility: indexer return type `" +
5380 TypeManager.CSharpName (MemberType) + "' is less " +
5381 "accessible than indexer `" + GetSignatureForError () + "'");
5382 else if (this is MethodCore) {
5383 if (this is Operator)
5384 Report.Error (56, Location,
5385 "Inconsistent accessibility: return type `" +
5386 TypeManager.CSharpName (MemberType) + "' is less " +
5387 "accessible than operator `" + GetSignatureForError () + "'");
5389 Report.Error (50, Location,
5390 "Inconsistent accessibility: return type `" +
5391 TypeManager.CSharpName (MemberType) + "' is less " +
5392 "accessible than method `" + GetSignatureForError () + "'");
5394 Report.Error (52, Location,
5395 "Inconsistent accessibility: field type `" +
5396 TypeManager.CSharpName (MemberType) + "' is less " +
5397 "accessible than field `" + GetSignatureForError () + "'");
5405 protected bool IsTypePermitted ()
5407 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5408 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5416 // Abstract class for all fields
5418 abstract public class FieldBase : MemberBase {
5419 public FieldBuilder FieldBuilder;
5420 public Status status;
5421 protected Expression initializer;
5424 public enum Status : byte {
5425 HAS_OFFSET = 4 // Used by FieldMember.
5428 static readonly string[] attribute_targets = new string [] { "field" };
5430 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5431 int allowed_mod, MemberName name, Attributes attrs)
5432 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5435 if ((mod & Modifiers.ABSTRACT) != 0)
5436 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5439 public override AttributeTargets AttributeTargets {
5441 return AttributeTargets.Field;
5445 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5447 if (a.Type == TypeManager.field_offset_attribute_type) {
5448 status |= Status.HAS_OFFSET;
5450 if (!Parent.PartialContainer.HasExplicitLayout) {
5451 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5455 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5456 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5462 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5463 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5468 if (a.Type == TypeManager.marshal_as_attr_type) {
5469 UnmanagedMarshal marshal = a.GetMarshal (this);
5470 if (marshal != null) {
5471 FieldBuilder.SetMarshal (marshal);
5476 if ((a.HasSecurityAttribute)) {
5477 a.Error_InvalidSecurityParent ();
5481 FieldBuilder.SetCustomAttribute (cb);
5484 protected override bool CheckBase ()
5486 if (!base.CheckBase ())
5489 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5490 if (conflict_symbol == null) {
5491 if ((ModFlags & Modifiers.NEW) != 0) {
5492 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5497 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5498 Report.SymbolRelatedToPreviousError (conflict_symbol);
5499 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5500 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5506 public override bool Define()
5508 if (MemberType == null || member_type == null)
5511 if (TypeManager.IsGenericParameter (MemberType))
5514 if (MemberType == TypeManager.void_type) {
5515 // TODO: wrong location
5516 Expression.Error_VoidInvalidInTheContext (Location);
5520 if (MemberType.IsSealed && MemberType.IsAbstract) {
5521 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5531 if (!IsTypePermitted ())
5538 // Represents header string for documentation comment.
5540 public override string DocCommentHeader {
5541 get { return "F:"; }
5544 public override void Emit ()
5547 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5548 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5551 if (OptAttributes != null) {
5552 OptAttributes.Emit ();
5555 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5556 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5562 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5564 Report.SymbolRelatedToPreviousError (static_class);
5565 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5569 public Expression Initializer {
5571 if (value != null) {
5572 this.initializer = value;
5577 protected virtual bool IsFieldClsCompliant {
5579 if (FieldBuilder == null)
5582 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5586 public override string[] ValidAttributeTargets
5589 return attribute_targets;
5593 protected override bool VerifyClsCompliance ()
5595 if (!base.VerifyClsCompliance ())
5598 if (!IsFieldClsCompliant) {
5599 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5604 public void SetAssigned ()
5606 caching_flags |= Flags.IsAssigned;
5610 interface IFixedBuffer
5612 FieldInfo Element { get; }
5613 Type ElementType { get; }
5616 public class FixedFieldExternal: IFixedBuffer
5618 FieldInfo element_field;
5620 public FixedFieldExternal (FieldInfo fi)
5622 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5625 #region IFixedField Members
5627 public FieldInfo Element {
5629 return element_field;
5633 public Type ElementType {
5635 return element_field.FieldType;
5643 /// Fixed buffer implementation
5645 public class FixedField : FieldBase, IFixedBuffer
5647 public const string FixedElementName = "FixedElementField";
5648 static int GlobalCounter = 0;
5649 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5650 static FieldInfo[] fi;
5652 TypeBuilder fixed_buffer_type;
5653 FieldBuilder element;
5654 Expression size_expr;
5656 const int AllowedModifiers =
5659 Modifiers.PROTECTED |
5660 Modifiers.INTERNAL |
5663 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5664 Expression size_expr, Attributes attrs, Location loc):
5665 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5667 if (RootContext.Version == LanguageVersion.ISO_1)
5668 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5670 this.size_expr = size_expr;
5673 public override bool Define()
5675 if (!Parent.IsInUnsafeScope)
5676 Expression.UnsafeError (Location);
5678 if (!base.Define ())
5681 if (!TypeManager.IsPrimitiveType (MemberType)) {
5682 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",
5683 GetSignatureForError ());
5686 // Create nested fixed buffer container
5687 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5688 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5689 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5691 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5692 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5694 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5695 Parent.MemberCache.AddMember (FieldBuilder, this);
5696 TypeManager.RegisterFieldBase (FieldBuilder, this);
5701 public override void Emit()
5703 if (Parent.PartialContainer.Kind != Kind.Struct) {
5704 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5705 GetSignatureForError ());
5708 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5709 Constant c = size_expr.ResolveAsConstant (ec, this);
5713 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5714 if (buffer_size_const == null)
5717 int buffer_size = buffer_size_const.Value;
5719 if (buffer_size <= 0) {
5720 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5724 int type_size = Expression.GetTypeSize (MemberType);
5726 if (buffer_size > int.MaxValue / type_size) {
5727 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5728 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5732 buffer_size *= type_size;
5733 EmitFieldSize (buffer_size);
5737 void EmitFieldSize (int buffer_size)
5739 if (TypeManager.struct_layout_attribute_type == null) {
5740 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5741 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5743 if (TypeManager.struct_layout_attribute_type == null)
5748 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5750 object [] fi_val = new object [] { buffer_size };
5752 if (TypeManager.struct_layout_attribute_ctor == null) {
5753 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5754 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5755 if (TypeManager.struct_layout_attribute_ctor == null)
5759 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5760 ctor_args, fi, fi_val);
5761 fixed_buffer_type.SetCustomAttribute (cab);
5764 // Don't emit FixedBufferAttribute attribute for private types
5766 if ((ModFlags & Modifiers.PRIVATE) != 0)
5769 if (TypeManager.fixed_buffer_attr_ctor == null) {
5770 if (TypeManager.fixed_buffer_attr_type == null) {
5771 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5772 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5774 if (TypeManager.fixed_buffer_attr_type == null)
5778 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5779 Location, TypeManager.type_type, TypeManager.int32_type);
5781 if (TypeManager.fixed_buffer_attr_ctor == null)
5785 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5786 FieldBuilder.SetCustomAttribute (cab);
5789 protected override bool IsFieldClsCompliant {
5795 #region IFixedField Members
5797 public FieldInfo Element {
5803 public Type ElementType {
5813 // The Field class is used to represents class/struct fields during parsing.
5815 public class Field : FieldBase {
5817 // Modifiers allowed in a class declaration
5819 const int AllowedModifiers =
5822 Modifiers.PROTECTED |
5823 Modifiers.INTERNAL |
5826 Modifiers.VOLATILE |
5830 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5831 Attributes attrs, Location loc)
5832 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5837 bool CanBeVolatile ()
5839 if (TypeManager.IsReferenceType (MemberType))
5842 if (MemberType.IsEnum)
5845 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5846 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5847 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5848 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5849 MemberType == TypeManager.float_type)
5855 public override bool Define ()
5857 if (!base.Define ())
5860 if ((ModFlags & Modifiers.VOLATILE) != 0){
5861 if (!CanBeVolatile ()) {
5862 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5863 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5866 if ((ModFlags & Modifiers.READONLY) != 0){
5867 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5868 GetSignatureForError ());
5872 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5876 Type[] required_modifier = null;
5877 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5878 if (TypeManager.isvolatile_type == null)
5879 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5880 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5882 if (TypeManager.isvolatile_type != null)
5883 required_modifier = new Type [] { TypeManager.isvolatile_type };
5886 FieldBuilder = Parent.TypeBuilder.DefineField (
5887 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5889 FieldBuilder = Parent.TypeBuilder.DefineField (
5890 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5892 Parent.MemberCache.AddMember (FieldBuilder, this);
5893 TypeManager.RegisterFieldBase (FieldBuilder, this);
5895 catch (ArgumentException) {
5896 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5900 if (initializer != null)
5901 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5902 new FieldInitializer (FieldBuilder, initializer));
5904 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
5905 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
5906 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
5907 GetSignatureForError ());
5914 public override string GetSignatureForError ()
5916 string s = base.GetSignatureForError ();
5917 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5920 // Undecorate name mangling
5921 int l = s.LastIndexOf ('>');
5922 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5925 protected override bool VerifyClsCompliance ()
5927 if (!base.VerifyClsCompliance ())
5930 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5931 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5939 // `set' and `get' accessors are represented with an Accessor.
5941 public class Accessor : IAnonymousHost {
5943 // Null if the accessor is empty, or a Block if not
5945 public const int AllowedModifiers =
5947 Modifiers.PROTECTED |
5948 Modifiers.INTERNAL |
5951 public ToplevelBlock Block;
5952 public Attributes Attributes;
5953 public Location Location;
5954 public int ModFlags;
5957 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5962 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5965 public void SetYields ()
5971 // Ooouh Martin, templates are missing here.
5972 // When it will be possible move here a lot of child code and template method type.
5973 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5974 protected MethodData method_data;
5975 protected ToplevelBlock block;
5976 protected ListDictionary declarative_security;
5978 // The accessor are created event if they are not wanted.
5979 // But we need them because their names are reserved.
5980 // Field says whether accessor will be emited or not
5981 public readonly bool IsDummy;
5983 protected readonly string prefix;
5985 ReturnParameter return_attributes;
5987 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5988 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5990 this.prefix = prefix;
5994 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5996 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5997 accessor.Attributes)
5999 this.prefix = prefix;
6000 this.block = accessor.Block;
6003 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6005 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6008 public void UpdateName (InterfaceMemberBase member)
6010 SetMemberName (SetupName (prefix, member, Location));
6013 #region IMethodData Members
6015 public ToplevelBlock Block {
6025 public CallingConventions CallingConventions {
6027 return CallingConventions.Standard;
6031 public bool IsExcluded ()
6036 GenericMethod IMethodData.GenericMethod {
6042 public MemberName MethodName {
6048 public Type[] ParameterTypes {
6050 return ParameterInfo.Types;
6054 public abstract Parameters ParameterInfo { get ; }
6055 public abstract Type ReturnType { get; }
6056 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6060 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6062 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6063 a.Type == TypeManager.conditional_attribute_type) {
6064 Report.Error (1667, a.Location,
6065 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6066 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6070 if (a.IsValidSecurityAttribute ()) {
6071 if (declarative_security == null)
6072 declarative_security = new ListDictionary ();
6073 a.ExtractSecurityPermissionSet (declarative_security);
6077 if (a.Target == AttributeTargets.Method) {
6078 method_data.MethodBuilder.SetCustomAttribute (cb);
6082 if (a.Target == AttributeTargets.ReturnValue) {
6083 if (return_attributes == null)
6084 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6086 return_attributes.ApplyAttributeBuilder (a, cb);
6090 ApplyToExtraTarget (a, cb);
6093 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6095 throw new NotSupportedException ("You forgot to define special attribute target handling");
6098 // It is not supported for the accessors
6099 public sealed override bool Define()
6101 throw new NotSupportedException ();
6104 public void Emit (DeclSpace parent)
6106 EmitMethod (parent);
6109 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6110 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6111 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6112 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6114 if (OptAttributes != null)
6115 OptAttributes.Emit ();
6117 if (declarative_security != null) {
6118 foreach (DictionaryEntry de in declarative_security) {
6119 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6126 protected virtual void EmitMethod (DeclSpace parent)
6128 method_data.Emit (parent);
6131 public override bool EnableOverloadChecks (MemberCore overload)
6133 // This can only happen with indexers and it will
6134 // be catched as indexer difference
6135 if (overload is AbstractPropertyEventMethod)
6138 if (overload is MethodCore) {
6139 caching_flags |= Flags.MethodOverloadsExist;
6145 public override bool IsClsComplianceRequired()
6150 public bool IsDuplicateImplementation (MethodCore method)
6152 if (!MemberName.Equals (method.MemberName))
6155 Type[] param_types = method.ParameterTypes;
6157 if (param_types == null || param_types.Length != ParameterTypes.Length)
6160 for (int i = 0; i < param_types.Length; i++)
6161 if (param_types [i] != ParameterTypes [i])
6164 Report.SymbolRelatedToPreviousError (method);
6165 Report.Error (82, Location, "A member `{0}' is already reserved",
6166 method.GetSignatureForError ());
6170 public override bool IsUsed
6181 // Represents header string for documentation comment.
6183 public override string DocCommentHeader {
6184 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6187 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6192 // Properties and Indexers both generate PropertyBuilders, we use this to share
6193 // their common bits.
6195 abstract public class PropertyBase : PropertyBasedMember {
6197 public class GetMethod : PropertyMethod
6199 static string[] attribute_targets = new string [] { "method", "return" };
6201 public GetMethod (PropertyBase method):
6202 base (method, "get_")
6206 public GetMethod (PropertyBase method, Accessor accessor):
6207 base (method, accessor, "get_")
6211 public override MethodBuilder Define (DeclSpace parent)
6213 if (!CheckForDuplications ())
6219 base.Define (parent);
6221 method_data = new MethodData (method, ModFlags, flags, this);
6223 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6226 return method_data.MethodBuilder;
6229 public override Type ReturnType {
6231 return method.MemberType;
6235 public override Parameters ParameterInfo {
6237 return Parameters.EmptyReadOnlyParameters;
6241 public override string[] ValidAttributeTargets {
6243 return attribute_targets;
6248 public class SetMethod : PropertyMethod {
6250 static string[] attribute_targets = new string [] { "method", "param", "return" };
6251 ImplicitParameter param_attr;
6252 protected Parameters parameters;
6254 public SetMethod (PropertyBase method):
6255 base (method, "set_")
6259 public SetMethod (PropertyBase method, Accessor accessor):
6260 base (method, accessor, "set_")
6264 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6266 if (a.Target == AttributeTargets.Parameter) {
6267 if (param_attr == null)
6268 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6270 param_attr.ApplyAttributeBuilder (a, cb);
6274 base.ApplyAttributeBuilder (a, cb);
6277 public override Parameters ParameterInfo {
6279 if (parameters == null)
6280 DefineParameters ();
6285 protected virtual void DefineParameters ()
6287 parameters = Parameters.CreateFullyResolved (
6288 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6291 public override MethodBuilder Define (DeclSpace parent)
6293 if (!CheckForDuplications ())
6299 base.Define (parent);
6301 method_data = new MethodData (method, ModFlags, flags, this);
6303 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6306 return method_data.MethodBuilder;
6309 public override Type ReturnType {
6311 return TypeManager.void_type;
6315 public override string[] ValidAttributeTargets {
6317 return attribute_targets;
6322 static string[] attribute_targets = new string [] { "property" };
6324 public abstract class PropertyMethod : AbstractPropertyEventMethod
6326 protected readonly PropertyBase method;
6327 protected MethodAttributes flags;
6330 public PropertyMethod (PropertyBase method, string prefix)
6331 : base (method, prefix)
6333 this.method = method;
6336 public PropertyMethod (PropertyBase method, Accessor accessor,
6338 : base (method, accessor, prefix)
6340 this.method = method;
6341 this.ModFlags = accessor.ModFlags;
6342 yields = accessor.Yields;
6344 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6345 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6349 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6351 if (a.IsInternalMethodImplAttribute) {
6352 method.is_external_implementation = true;
6355 base.ApplyAttributeBuilder (a, cb);
6358 public override AttributeTargets AttributeTargets {
6360 return AttributeTargets.Method;
6364 public override bool IsClsComplianceRequired ()
6366 return method.IsClsComplianceRequired ();
6369 public virtual MethodBuilder Define (DeclSpace parent)
6371 TypeContainer container = parent.PartialContainer;
6374 // Check for custom access modifier
6376 if ((ModFlags & Modifiers.Accessibility) == 0) {
6377 ModFlags |= method.ModFlags;
6378 flags = method.flags;
6380 if (container.Kind == Kind.Interface)
6381 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6382 GetSignatureForError ());
6384 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6385 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6388 CheckModifiers (ModFlags);
6389 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6390 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6391 flags = Modifiers.MethodAttr (ModFlags);
6392 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6395 CheckAbstractAndExtern (block != null);
6398 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6403 public bool HasCustomAccessModifier
6406 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6410 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6412 return new EmitContext (method,
6413 ds, method.ds, method.Location, ig, ReturnType,
6414 method.ModFlags, false);
6417 public override ObsoleteAttribute GetObsoleteAttribute ()
6419 return method.GetObsoleteAttribute ();
6422 public override string GetSignatureForError()
6424 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6427 void CheckModifiers (int modflags)
6429 modflags &= Modifiers.Accessibility;
6431 int mflags = method.ModFlags & Modifiers.Accessibility;
6433 if ((mflags & Modifiers.PUBLIC) != 0) {
6434 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6436 else if ((mflags & Modifiers.PROTECTED) != 0) {
6437 if ((mflags & Modifiers.INTERNAL) != 0)
6438 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6440 flags |= Modifiers.PRIVATE;
6442 else if ((mflags & Modifiers.INTERNAL) != 0)
6443 flags |= Modifiers.PRIVATE;
6445 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6446 Report.Error (273, Location,
6447 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6448 GetSignatureForError (), method.GetSignatureForError ());
6452 protected bool CheckForDuplications ()
6454 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6457 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6461 public PropertyMethod Get, Set;
6462 public PropertyBuilder PropertyBuilder;
6463 public MethodBuilder GetBuilder, SetBuilder;
6465 protected bool define_set_first = false;
6467 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6468 int allowed_mod, bool is_iface, MemberName name,
6469 Attributes attrs, bool define_set_first)
6470 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6472 this.define_set_first = define_set_first;
6475 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6477 if (a.HasSecurityAttribute) {
6478 a.Error_InvalidSecurityParent ();
6482 PropertyBuilder.SetCustomAttribute (cb);
6485 public override AttributeTargets AttributeTargets {
6487 return AttributeTargets.Property;
6491 public override bool Define ()
6496 if (!IsTypePermitted ())
6502 protected override bool DoDefine ()
6504 if (!base.DoDefine ())
6508 // Accessors modifiers check
6510 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6511 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6512 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6513 GetSignatureForError ());
6517 if ((Get.IsDummy || Set.IsDummy)
6518 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6519 Report.Error (276, Location,
6520 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6521 GetSignatureForError ());
6526 if (MemberType.IsGenericParameter)
6530 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6531 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6540 GetBuilder = Get.Define (Parent);
6541 return (Get.IsDummy) ? true : GetBuilder != null;
6544 bool DefineSet (bool define)
6549 SetBuilder = Set.Define (Parent);
6550 return (Set.IsDummy) ? true : SetBuilder != null;
6553 protected bool DefineAccessors ()
6555 return DefineSet (define_set_first) &&
6557 DefineSet (!define_set_first);
6560 protected abstract PropertyInfo ResolveBaseProperty ();
6562 // TODO: rename to Resolve......
6563 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6565 PropertyInfo base_property = ResolveBaseProperty ();
6566 if (base_property == null)
6569 base_ret_type = base_property.PropertyType;
6570 MethodInfo get_accessor = base_property.GetGetMethod (true);
6571 MethodInfo set_accessor = base_property.GetSetMethod (true);
6572 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6575 // Check base property accessors conflict
6577 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6578 if (get_accessor == null) {
6579 if (Get != null && !Get.IsDummy) {
6580 Report.SymbolRelatedToPreviousError (base_property);
6581 Report.Error (545, Location,
6582 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6583 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6586 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6588 if (!Get.IsDummy && !CheckAccessModifiers (
6589 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6590 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6593 if (set_accessor == null) {
6594 if (Set != null && !Set.IsDummy) {
6595 Report.SymbolRelatedToPreviousError (base_property);
6596 Report.Error (546, Location,
6597 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6598 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6601 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6603 if (!Set.IsDummy && !CheckAccessModifiers (
6604 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6605 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6609 // When one accessor does not exist and property hides base one
6610 // we need to propagate this upwards
6611 if (set_accessor == null)
6612 set_accessor = get_accessor;
6615 // Get the less restrictive access
6617 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6620 public override void Emit ()
6623 // The PropertyBuilder can be null for explicit implementations, in that
6624 // case, we do not actually emit the ".property", so there is nowhere to
6625 // put the attribute
6627 if (PropertyBuilder != null && OptAttributes != null)
6628 OptAttributes.Emit ();
6640 /// Tests whether accessors are not in collision with some method (CS0111)
6642 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6644 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6647 public override bool IsUsed
6653 return Get.IsUsed | Set.IsUsed;
6657 protected override void SetMemberName (MemberName new_name)
6659 base.SetMemberName (new_name);
6661 Get.UpdateName (this);
6662 Set.UpdateName (this);
6665 public override string[] ValidAttributeTargets {
6667 return attribute_targets;
6672 // Represents header string for documentation comment.
6674 public override string DocCommentHeader {
6675 get { return "P:"; }
6679 public class Property : PropertyBase {
6680 const int AllowedModifiers =
6683 Modifiers.PROTECTED |
6684 Modifiers.INTERNAL |
6688 Modifiers.OVERRIDE |
6689 Modifiers.ABSTRACT |
6692 Modifiers.METHOD_YIELDS |
6695 const int AllowedInterfaceModifiers =
6698 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6701 Field field = new Field (
6703 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6704 "<" + Name + ">k__BackingField", null, Location);
6705 ((TypeContainer)Parent).PartialContainer.AddField (field);
6708 get_block.Block = new ToplevelBlock (block, null, Location);
6709 Return r = new Return (new SimpleName(field.Name, Location), Location);
6710 get_block.Block.AddStatement (r);
6711 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6714 Parameters parameters = new Parameters (new Parameter (type_name, "value", Parameter.Modifier.NONE, null, Location));
6715 set_block.Block = new ToplevelBlock (block, parameters, Location);
6716 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6717 set_block.Block.AddStatement (new StatementExpression(a));
6718 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6721 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6722 MemberName name, Attributes attrs, Accessor get_block,
6723 Accessor set_block, bool define_set_first)
6724 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6725 define_set_first, null)
6729 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6730 MemberName name, Attributes attrs, Accessor get_block,
6731 Accessor set_block, bool define_set_first, Block current_block)
6732 : base (parent, type, mod,
6733 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6734 is_iface, name, attrs, define_set_first)
6736 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6737 get_block != null && get_block.Block == null &&
6738 set_block != null && set_block.Block == null) {
6739 if (RootContext.Version <= LanguageVersion.ISO_2)
6740 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6742 CreateAutomaticProperty (current_block, get_block, set_block);
6745 if (get_block == null)
6746 Get = new GetMethod (this);
6748 Get = new GetMethod (this, get_block);
6750 if (set_block == null)
6751 Set = new SetMethod (this);
6753 Set = new SetMethod (this, set_block);
6756 public override bool Define ()
6758 if (!DoDefineBase ())
6761 if (!base.Define ())
6764 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6766 if (!DefineAccessors ())
6772 // FIXME - PropertyAttributes.HasDefault ?
6774 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6775 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6778 PropertyBuilder.SetGetMethod (GetBuilder);
6779 Parent.MemberCache.AddMember (GetBuilder, Get);
6783 PropertyBuilder.SetSetMethod (SetBuilder);
6784 Parent.MemberCache.AddMember (SetBuilder, Set);
6787 TypeManager.RegisterProperty (PropertyBuilder, this);
6788 Parent.MemberCache.AddMember (PropertyBuilder, this);
6792 protected override PropertyInfo ResolveBaseProperty ()
6794 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6795 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6800 /// Gigantic workaround for lameness in SRE follows :
6801 /// This class derives from EventInfo and attempts to basically
6802 /// wrap around the EventBuilder so that FindMembers can quickly
6803 /// return this in it search for members
6805 public class MyEventBuilder : EventInfo {
6808 // We use this to "point" to our Builder which is
6809 // not really a MemberInfo
6811 EventBuilder MyBuilder;
6814 // We "catch" and wrap these methods
6816 MethodInfo raise, remove, add;
6818 EventAttributes attributes;
6819 Type declaring_type, reflected_type, event_type;
6824 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6826 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6828 // And now store the values in our own fields.
6830 declaring_type = type_builder;
6832 reflected_type = type_builder;
6834 attributes = event_attr;
6837 this.event_type = event_type;
6841 // Methods that you have to override. Note that you only need
6842 // to "implement" the variants that take the argument (those are
6843 // the "abstract" methods, the others (GetAddMethod()) are
6846 public override MethodInfo GetAddMethod (bool nonPublic)
6851 public override MethodInfo GetRemoveMethod (bool nonPublic)
6856 public override MethodInfo GetRaiseMethod (bool nonPublic)
6862 // These methods make "MyEventInfo" look like a Builder
6864 public void SetRaiseMethod (MethodBuilder raiseMethod)
6866 raise = raiseMethod;
6867 MyBuilder.SetRaiseMethod (raiseMethod);
6870 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6872 remove = removeMethod;
6873 MyBuilder.SetRemoveOnMethod (removeMethod);
6876 public void SetAddOnMethod (MethodBuilder addMethod)
6879 MyBuilder.SetAddOnMethod (addMethod);
6882 public void SetCustomAttribute (CustomAttributeBuilder cb)
6884 MyBuilder.SetCustomAttribute (cb);
6887 public override object [] GetCustomAttributes (bool inherit)
6889 // FIXME : There's nothing which can be seemingly done here because
6890 // we have no way of getting at the custom attribute objects of the
6895 public override object [] GetCustomAttributes (Type t, bool inherit)
6897 // FIXME : Same here !
6901 public override bool IsDefined (Type t, bool b)
6906 public override EventAttributes Attributes {
6912 public override string Name {
6918 public override Type DeclaringType {
6920 return declaring_type;
6924 public override Type ReflectedType {
6926 return reflected_type;
6930 public Type EventType {
6936 public void SetUsed ()
6938 if (my_event != null) {
6939 // my_event.SetAssigned ();
6940 my_event.SetMemberIsUsed ();
6946 /// For case when event is declared like property (with add and remove accessors).
6948 public class EventProperty: Event {
6949 abstract class AEventPropertyAccessor : AEventAccessor
6951 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6952 base (method, accessor, prefix)
6956 public override MethodBuilder Define (DeclSpace ds)
6958 CheckAbstractAndExtern (block != null);
6959 return base.Define (ds);
6962 public override string GetSignatureForError ()
6964 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6968 sealed class AddDelegateMethod: AEventPropertyAccessor
6970 public AddDelegateMethod (Event method, Accessor accessor):
6971 base (method, accessor, "add_")
6975 protected override MethodInfo DelegateMethodInfo {
6977 return TypeManager.delegate_combine_delegate_delegate;
6982 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6984 public RemoveDelegateMethod (Event method, Accessor accessor):
6985 base (method, accessor, "remove_")
6989 protected override MethodInfo DelegateMethodInfo {
6991 return TypeManager.delegate_remove_delegate_delegate;
6997 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6999 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7000 bool is_iface, MemberName name,
7001 Attributes attrs, Accessor add, Accessor remove)
7002 : base (parent, type, mod_flags, is_iface, name, attrs)
7004 Add = new AddDelegateMethod (this, add);
7005 Remove = new RemoveDelegateMethod (this, remove);
7008 public override bool Define()
7010 if (!base.Define ())
7017 public override string[] ValidAttributeTargets {
7019 return attribute_targets;
7025 /// Event is declared like field.
7027 public class EventField : Event {
7028 abstract class EventFieldAccessor : AEventAccessor
7030 protected EventFieldAccessor (Event method, string prefix)
7031 : base (method, prefix)
7035 protected override void EmitMethod(DeclSpace parent)
7037 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7040 MethodBuilder mb = method_data.MethodBuilder;
7041 ILGenerator ig = mb.GetILGenerator ();
7043 // TODO: because we cannot use generics yet
7044 FieldInfo field_info = ((EventField)method).FieldBuilder;
7046 if (parent is Class) {
7047 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7050 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7051 ig.Emit (OpCodes.Ldsfld, field_info);
7052 ig.Emit (OpCodes.Ldarg_0);
7053 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7054 ig.Emit (OpCodes.Castclass, method.MemberType);
7055 ig.Emit (OpCodes.Stsfld, field_info);
7057 ig.Emit (OpCodes.Ldarg_0);
7058 ig.Emit (OpCodes.Ldarg_0);
7059 ig.Emit (OpCodes.Ldfld, field_info);
7060 ig.Emit (OpCodes.Ldarg_1);
7061 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7062 ig.Emit (OpCodes.Castclass, method.MemberType);
7063 ig.Emit (OpCodes.Stfld, field_info);
7065 ig.Emit (OpCodes.Ret);
7069 sealed class AddDelegateMethod: EventFieldAccessor
7071 public AddDelegateMethod (Event method):
7072 base (method, "add_")
7076 protected override MethodInfo DelegateMethodInfo {
7078 return TypeManager.delegate_combine_delegate_delegate;
7083 sealed class RemoveDelegateMethod: EventFieldAccessor
7085 public RemoveDelegateMethod (Event method):
7086 base (method, "remove_")
7090 protected override MethodInfo DelegateMethodInfo {
7092 return TypeManager.delegate_remove_delegate_delegate;
7098 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7099 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7101 public FieldBuilder FieldBuilder;
7102 public Expression Initializer;
7104 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags,
7105 bool is_iface, MemberName name,
7107 : base (parent, type, mod_flags, is_iface, name, attrs)
7109 Add = new AddDelegateMethod (this);
7110 Remove = new RemoveDelegateMethod (this);
7113 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7115 if (a.Target == AttributeTargets.Field) {
7116 FieldBuilder.SetCustomAttribute (cb);
7120 if (a.Target == AttributeTargets.Method) {
7121 int errors = Report.Errors;
7122 Add.ApplyAttributeBuilder (a, cb);
7123 if (errors == Report.Errors)
7124 Remove.ApplyAttributeBuilder (a, cb);
7128 base.ApplyAttributeBuilder (a, cb);
7131 public override bool Define()
7133 if (!base.Define ())
7139 // FIXME: We are unable to detect whether generic event is used because
7140 // we are using FieldExpr instead of EventExpr for event access in that
7141 // case. When this issue will be fixed this hack can be removed.
7142 if (TypeManager.IsGenericType (MemberType))
7145 if (Add.IsInterfaceImplementation)
7148 FieldBuilder = Parent.TypeBuilder.DefineField (
7150 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7151 TypeManager.RegisterEventField (EventBuilder, this);
7153 if (Initializer != null) {
7154 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7155 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7156 GetSignatureForError ());
7160 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7161 new FieldInitializer (FieldBuilder, Initializer));
7167 public override string[] ValidAttributeTargets
7170 return IsInterface ? attribute_targets_interface : attribute_targets;
7175 public abstract class Event : PropertyBasedMember {
7176 public abstract class AEventAccessor : AbstractPropertyEventMethod
7178 protected readonly Event method;
7179 ImplicitParameter param_attr;
7181 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7183 protected AEventAccessor (Event method, string prefix)
7184 : base (method, prefix)
7186 this.method = method;
7187 this.ModFlags = method.ModFlags;
7190 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7191 : base (method, accessor, prefix)
7193 this.method = method;
7194 this.ModFlags = method.ModFlags;
7197 public bool IsInterfaceImplementation {
7198 get { return method_data.implementing != null; }
7201 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7203 if (a.IsInternalMethodImplAttribute) {
7204 method.is_external_implementation = true;
7207 base.ApplyAttributeBuilder (a, cb);
7210 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7212 if (a.Target == AttributeTargets.Parameter) {
7213 if (param_attr == null)
7214 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7216 param_attr.ApplyAttributeBuilder (a, cb);
7220 base.ApplyAttributeBuilder (a, cb);
7223 public override AttributeTargets AttributeTargets {
7225 return AttributeTargets.Method;
7229 public override bool IsClsComplianceRequired ()
7231 return method.IsClsComplianceRequired ();
7234 public virtual MethodBuilder Define (DeclSpace parent)
7236 method_data = new MethodData (method, method.ModFlags,
7237 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7239 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7242 MethodBuilder mb = method_data.MethodBuilder;
7243 ParameterInfo.ApplyAttributes (mb);
7247 protected abstract MethodInfo DelegateMethodInfo { get; }
7249 public override Type ReturnType {
7251 return TypeManager.void_type;
7255 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7257 return new EmitContext (
7258 this, method.Parent, Location, ig, ReturnType,
7259 method.ModFlags, false);
7262 public override ObsoleteAttribute GetObsoleteAttribute ()
7264 return method.GetObsoleteAttribute ();
7267 public override string[] ValidAttributeTargets {
7269 return attribute_targets;
7273 public override Parameters ParameterInfo {
7275 return method.parameters;
7281 const int AllowedModifiers =
7284 Modifiers.PROTECTED |
7285 Modifiers.INTERNAL |
7290 Modifiers.OVERRIDE |
7292 Modifiers.ABSTRACT |
7295 const int AllowedInterfaceModifiers =
7298 public AEventAccessor Add, Remove;
7299 public MyEventBuilder EventBuilder;
7300 public MethodBuilder AddBuilder, RemoveBuilder;
7302 Parameters parameters;
7304 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags,
7305 bool is_iface, MemberName name, Attributes attrs)
7306 : base (parent, null, type, mod_flags,
7307 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7312 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7314 if ((a.HasSecurityAttribute)) {
7315 a.Error_InvalidSecurityParent ();
7319 EventBuilder.SetCustomAttribute (cb);
7322 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7324 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7327 public override AttributeTargets AttributeTargets {
7329 return AttributeTargets.Event;
7333 public override bool Define ()
7335 if (!DoDefineBase ())
7341 if (!TypeManager.IsDelegateType (MemberType)) {
7342 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7346 parameters = Parameters.CreateFullyResolved (
7347 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7352 if (TypeManager.delegate_combine_delegate_delegate == null) {
7353 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7354 TypeManager.delegate_type, "Combine", Location,
7355 TypeManager.delegate_type, TypeManager.delegate_type);
7357 if (TypeManager.delegate_remove_delegate_delegate == null) {
7358 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7359 TypeManager.delegate_type, "Remove", Location,
7360 TypeManager.delegate_type, TypeManager.delegate_type);
7364 // Now define the accessors
7367 AddBuilder = Add.Define (Parent);
7368 if (AddBuilder == null)
7371 RemoveBuilder = Remove.Define (Parent);
7372 if (RemoveBuilder == null)
7375 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7376 EventBuilder.SetAddOnMethod (AddBuilder);
7377 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7379 Parent.MemberCache.AddMember (EventBuilder, this);
7380 Parent.MemberCache.AddMember (AddBuilder, Add);
7381 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7386 public override void Emit ()
7388 if (OptAttributes != null) {
7389 OptAttributes.Emit ();
7393 Remove.Emit (Parent);
7398 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7400 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7401 Parent.TypeBuilder, Name);
7406 ParameterData pd = TypeManager.GetParameterData (mi);
7407 base_ret_type = pd.ParameterType (0);
7412 // Represents header string for documentation comment.
7414 public override string DocCommentHeader {
7415 get { return "E:"; }
7420 public class Indexer : PropertyBase
7422 public class GetIndexerMethod : GetMethod
7424 Parameters parameters;
7426 public GetIndexerMethod (PropertyBase method):
7431 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7432 base (method, accessor)
7436 public override MethodBuilder Define (DeclSpace parent)
7439 // Clone indexer accessor parameters for localized capturing
7441 parameters = ((Indexer) method).parameters.Clone ();
7442 return base.Define (parent);
7445 public override bool EnableOverloadChecks (MemberCore overload)
7447 if (base.EnableOverloadChecks (overload)) {
7448 overload.caching_flags |= Flags.MethodOverloadsExist;
7455 public override Parameters ParameterInfo {
7462 public class SetIndexerMethod: SetMethod
7464 public SetIndexerMethod (PropertyBase method):
7469 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7470 base (method, accessor)
7474 protected override void DefineParameters ()
7476 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7477 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7480 public override bool EnableOverloadChecks (MemberCore overload)
7482 if (base.EnableOverloadChecks (overload)) {
7483 overload.caching_flags |= Flags.MethodOverloadsExist;
7491 const int AllowedModifiers =
7494 Modifiers.PROTECTED |
7495 Modifiers.INTERNAL |
7499 Modifiers.OVERRIDE |
7504 const int AllowedInterfaceModifiers =
7507 public readonly Parameters parameters;
7509 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7510 bool is_iface, Parameters parameters, Attributes attrs,
7511 Accessor get_block, Accessor set_block, bool define_set_first)
7512 : base (parent, type, mod,
7513 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7514 is_iface, name, attrs, define_set_first)
7516 if (type == TypeManager.system_void_expr)
7517 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7519 this.parameters = parameters;
7521 if (get_block == null)
7522 Get = new GetIndexerMethod (this);
7524 Get = new GetIndexerMethod (this, get_block);
7526 if (set_block == null)
7527 Set = new SetIndexerMethod (this);
7529 Set = new SetIndexerMethod (this, set_block);
7532 public override bool Define ()
7534 if (!DoDefineBase ())
7537 if (!base.Define ())
7540 if (!DefineParameters (parameters))
7543 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7544 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7545 if (indexer_attr != null) {
7546 // Remove the attribute from the list because it is not emitted
7547 OptAttributes.Attrs.Remove (indexer_attr);
7549 string name = indexer_attr.GetIndexerAttributeValue ();
7555 if (IsExplicitImpl) {
7556 Report.Error (415, indexer_attr.Location,
7557 "The `IndexerName' attribute is valid only on an " +
7558 "indexer that is not an explicit interface member declaration");
7562 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7563 Report.Error (609, indexer_attr.Location,
7564 "Cannot set the `IndexerName' attribute on an indexer marked override");
7570 if (InterfaceType != null) {
7571 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7572 if (base_IndexerName != Name)
7573 ShortName = base_IndexerName;
7576 if (!Parent.PartialContainer.AddMember (this) ||
7577 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7580 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7581 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7585 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7587 if (!DefineAccessors ())
7594 // Now name the parameters
7596 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7597 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7600 PropertyBuilder.SetGetMethod (GetBuilder);
7601 Parent.MemberCache.AddMember (GetBuilder, Get);
7605 PropertyBuilder.SetSetMethod (SetBuilder);
7606 Parent.MemberCache.AddMember (SetBuilder, Set);
7609 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7610 Parent.MemberCache.AddMember (PropertyBuilder, this);
7614 public override bool EnableOverloadChecks (MemberCore overload)
7616 if (overload is Indexer) {
7617 caching_flags |= Flags.MethodOverloadsExist;
7624 public override string GetDocCommentName (DeclSpace ds)
7626 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7629 public override string GetSignatureForError ()
7631 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7632 if (MemberName.Left != null) {
7634 sb.Append (MemberName.Left.GetSignatureForError ());
7637 sb.Append (".this");
7638 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7639 return sb.ToString ();
7642 protected override PropertyInfo ResolveBaseProperty ()
7644 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7645 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7648 protected override bool VerifyClsCompliance ()
7650 if (!base.VerifyClsCompliance ())
7653 parameters.VerifyClsCompliance ();
7658 public class Operator : MethodOrOperator, IAnonymousHost {
7660 const int AllowedModifiers =
7666 public enum OpType : byte {
7676 // Unary and Binary operators
7699 // Implicit and Explicit
7703 // Just because of enum
7707 public readonly OpType OperatorType;
7709 static readonly string [] [] names;
7713 names = new string[(int)OpType.TOP][];
7714 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7715 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7716 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7717 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7718 names [(int) OpType.True] = new string [] { "true", "op_True" };
7719 names [(int) OpType.False] = new string [] { "false", "op_False" };
7720 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7721 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7722 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7723 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7724 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7725 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7726 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7727 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7728 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7729 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7730 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7731 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7732 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7733 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7734 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7735 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7736 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7737 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7738 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7739 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7742 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7743 int mod_flags, Parameters parameters,
7744 ToplevelBlock block, Attributes attrs, Location loc)
7745 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7746 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7748 OperatorType = type;
7752 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7754 if (a.Type == TypeManager.conditional_attribute_type) {
7755 Error_ConditionalAttributeIsNotValid ();
7759 base.ApplyAttributeBuilder (a, cb);
7762 public override bool Define ()
7764 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7765 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7766 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7770 if (!base.Define ())
7773 // imlicit and explicit operator of same types are not allowed
7774 if (OperatorType == OpType.Explicit)
7775 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7776 else if (OperatorType == OpType.Implicit)
7777 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7779 if (MemberType == TypeManager.void_type) {
7780 Report.Error (590, Location, "User-defined operators cannot return void");
7784 Type declaring_type = MethodData.DeclaringType;
7785 Type return_type = MemberType;
7786 Type first_arg_type = ParameterTypes [0];
7788 Type first_arg_type_unwrap = first_arg_type;
7789 if (TypeManager.IsNullableType (first_arg_type))
7790 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7792 Type return_type_unwrap = return_type;
7793 if (TypeManager.IsNullableType (return_type))
7794 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7797 // Rules for conversion operators
7799 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7800 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7801 Report.Error (555, Location,
7802 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7807 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7808 conv_type = first_arg_type;
7809 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7810 conv_type = return_type;
7812 Report.Error (556, Location,
7813 "User-defined conversion must convert to or from the enclosing type");
7818 // Because IsInterface and IsClass are not supported
7820 if (!TypeManager.IsGenericParameter (conv_type)) {
7821 if (conv_type.IsInterface) {
7822 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7823 GetSignatureForError ());
7827 if (conv_type.IsClass) {
7828 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7829 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7830 GetSignatureForError ());
7834 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7835 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7836 GetSignatureForError ());
7841 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7842 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7843 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");
7846 } else if (Parameters.Count == 1) {
7847 // Checks for Unary operators
7849 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7850 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7851 Report.Error (448, Location,
7852 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7855 if (first_arg_type != declaring_type) {
7857 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7862 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7863 Report.Error (562, Location,
7864 "The parameter type of a unary operator must be the containing type");
7868 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7869 if (return_type != TypeManager.bool_type){
7872 "The return type of operator True or False " +
7879 // Checks for Binary operators
7881 if (first_arg_type != declaring_type &&
7882 ParameterTypes [1] != declaring_type){
7885 "One of the parameters of a binary operator must " +
7886 "be the containing type");
7894 protected override bool DoDefine ()
7896 if (!base.DoDefine ())
7899 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7903 public override void Emit ()
7907 Parameters.ApplyAttributes (MethodBuilder);
7910 // abstract or extern methods have no bodies
7912 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7916 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7917 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7919 ec = CreateEmitContext (Parent, null);
7921 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7922 ec.EmitTopBlock (this, Block);
7925 source.CloseMethod ();
7930 // Operator cannot be override
7931 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7936 public static string GetName (OpType ot)
7938 return names [(int) ot] [0];
7941 public static string GetName (string metadata_name)
7943 for (int i = 0; i < names.Length; ++i) {
7944 if (names [i] [1] == metadata_name)
7945 return names [i] [0];
7950 public static string GetMetadataName (OpType ot)
7952 return names [(int) ot] [1];
7955 public static string GetMetadataName (string name)
7957 for (int i = 0; i < names.Length; ++i) {
7958 if (names [i] [0] == name)
7959 return names [i] [1];
7964 public OpType GetMatchingOperator ()
7966 switch (OperatorType) {
7967 case OpType.Equality:
7968 return OpType.Inequality;
7969 case OpType.Inequality:
7970 return OpType.Equality;
7972 return OpType.False;
7975 case OpType.GreaterThan:
7976 return OpType.LessThan;
7977 case OpType.LessThan:
7978 return OpType.GreaterThan;
7979 case OpType.GreaterThanOrEqual:
7980 return OpType.LessThanOrEqual;
7981 case OpType.LessThanOrEqual:
7982 return OpType.GreaterThanOrEqual;
7988 public override string GetSignatureForError ()
7990 StringBuilder sb = new StringBuilder ();
7991 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7992 sb.AppendFormat ("{0}.{1} operator {2}",
7993 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7996 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7999 sb.Append (Parameters.GetSignatureForError ());
8000 return sb.ToString ();
8005 // This is used to compare method signatures
8007 struct MethodSignature {
8009 public Type RetType;
8010 public Type [] Parameters;
8013 /// This delegate is used to extract methods which have the
8014 /// same signature as the argument
8016 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8018 public MethodSignature (string name, Type ret_type, Type [] parameters)
8023 if (parameters == null)
8024 Parameters = Type.EmptyTypes;
8026 Parameters = parameters;
8029 public override string ToString ()
8032 if (Parameters.Length != 0){
8033 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8034 for (int i = 0; i < Parameters.Length; i++){
8035 sb.Append (Parameters [i]);
8036 if (i+1 < Parameters.Length)
8039 pars = sb.ToString ();
8042 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8045 public override int GetHashCode ()
8047 return Name.GetHashCode ();
8050 public override bool Equals (Object o)
8052 MethodSignature other = (MethodSignature) o;
8054 if (other.Name != Name)
8057 if (other.RetType != RetType)
8060 if (Parameters == null){
8061 if (other.Parameters == null)
8066 if (other.Parameters == null)
8069 int c = Parameters.Length;
8070 if (other.Parameters.Length != c)
8073 for (int i = 0; i < c; i++)
8074 if (other.Parameters [i] != Parameters [i])
8080 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8082 MethodSignature sig = (MethodSignature) filter_criteria;
8084 if (m.Name != sig.Name)
8088 MethodInfo mi = m as MethodInfo;
8089 PropertyInfo pi = m as PropertyInfo;
8092 ReturnType = mi.ReturnType;
8093 else if (pi != null)
8094 ReturnType = pi.PropertyType;
8099 // we use sig.RetType == null to mean `do not check the
8100 // method return value.
8102 if (sig.RetType != null) {
8103 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8109 args = TypeManager.GetParameterData (mi).Types;
8111 args = TypeManager.GetArgumentTypes (pi);
8112 Type [] sigp = sig.Parameters;
8114 if (args.Length != sigp.Length)
8117 for (int i = args.Length - 1; i >= 0; i--)
8118 if (!TypeManager.IsEqual (args [i], sigp [i]))