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.Warning (3015, 1, 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.Warning (3009, 1, 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 ());
2515 /// Performs checks for an explicit interface implementation. First it
2516 /// checks whether the `interface_type' is a base inteface implementation.
2517 /// Then it checks whether `name' exists in the interface type.
2519 public bool VerifyImplements (InterfaceMemberBase mb)
2521 if (ifaces != null) {
2522 foreach (Type t in ifaces){
2523 if (TypeManager.IsEqual (t, mb.InterfaceType))
2528 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2529 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2530 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2534 public override Type LookupAnyGeneric (string typeName)
2536 if (types != null) {
2537 foreach (TypeContainer tc in types) {
2541 int pos = tc.Basename.LastIndexOf ('`');
2542 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2543 return tc.TypeBuilder;
2547 return base.LookupAnyGeneric (typeName);
2550 public void Mark_HasEquals ()
2552 cached_method |= CachedMethods.Equals;
2555 public void Mark_HasGetHashCode ()
2557 cached_method |= CachedMethods.GetHashCode;
2561 /// Method container contains Equals method
2563 public bool HasEquals {
2565 return (cached_method & CachedMethods.Equals) != 0;
2570 /// Method container contains GetHashCode method
2572 public bool HasGetHashCode {
2574 return (cached_method & CachedMethods.GetHashCode) != 0;
2578 public bool HasStaticFieldInitializer {
2580 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2584 cached_method |= CachedMethods.HasStaticFieldInitializer;
2586 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2594 string IMemberContainer.Name {
2600 Type IMemberContainer.Type {
2606 bool IMemberContainer.IsInterface {
2608 return Kind == Kind.Interface;
2612 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2614 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2616 if (GenericType != null)
2617 return TypeManager.FindMembers (GenericType, mt, new_bf,
2620 return FindMembers (mt, new_bf, null, null);
2624 // Generates xml doc comments (if any), and if required,
2625 // handle warning report.
2627 internal override void GenerateDocComment (DeclSpace ds)
2629 DocUtil.GenerateTypeDocComment (this, ds);
2632 public override string DocCommentHeader {
2633 get { return "T:"; }
2636 public MemberCache BaseCache {
2638 if (base_cache != null)
2640 if (TypeBuilder.BaseType != null)
2641 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2642 if (TypeBuilder.IsInterface)
2643 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2649 public abstract class ClassOrStruct : TypeContainer {
2650 ListDictionary declarative_security;
2652 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2653 MemberName name, Attributes attrs, Kind kind)
2654 : base (ns, parent, name, attrs, kind)
2658 protected override bool AddToContainer (MemberCore symbol, string name)
2660 if (name == MemberName.Name) {
2661 if (symbol is TypeParameter) {
2662 Report.Error (694, symbol.Location,
2663 "Type parameter `{0}' has same name as " +
2664 "containing type, or method", name);
2668 Report.SymbolRelatedToPreviousError (this);
2669 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2670 symbol.GetSignatureForError ());
2674 return base.AddToContainer (symbol, name);
2677 public override void VerifyMembers ()
2679 base.VerifyMembers ();
2681 if ((events != null) && Report.WarningLevel >= 3) {
2682 foreach (Event e in events){
2683 // Note: The event can be assigned from same class only, so we can report
2684 // this warning for all accessibility modes
2685 if ((e.caching_flags & Flags.IsUsed) == 0)
2686 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2691 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2693 if (a.IsValidSecurityAttribute ()) {
2694 if (declarative_security == null)
2695 declarative_security = new ListDictionary ();
2697 a.ExtractSecurityPermissionSet (declarative_security);
2701 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2702 PartialContainer.HasExplicitLayout = true;
2705 base.ApplyAttributeBuilder (a, cb);
2709 /// Defines the default constructors
2711 protected void DefineDefaultConstructor (bool is_static)
2713 // The default instance constructor is public
2714 // If the class is abstract, the default constructor is protected
2715 // The default static constructor is private
2719 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2721 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2724 Constructor c = new Constructor (this, MemberName.Name, mods,
2725 Parameters.EmptyReadOnlyParameters,
2726 new GeneratedBaseInitializer (Location),
2730 c.Block = new ToplevelBlock (null, Location);
2733 public override bool Define ()
2735 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2736 DefineDefaultConstructor (true);
2738 if (default_static_constructor != null)
2739 default_static_constructor.Define ();
2741 return base.Define ();
2744 public override void Emit ()
2748 if (declarative_security != null) {
2749 foreach (DictionaryEntry de in declarative_security) {
2750 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2755 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2757 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2760 protected override TypeAttributes TypeAttr {
2762 if (default_static_constructor == null)
2763 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2765 return base.TypeAttr;
2771 // TODO: should be sealed
2772 public class Class : ClassOrStruct {
2773 const int AllowedModifiers =
2776 Modifiers.PROTECTED |
2777 Modifiers.INTERNAL |
2779 Modifiers.ABSTRACT |
2784 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2786 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2788 : base (ns, parent, name, attrs, Kind.Class)
2790 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2791 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2793 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2794 Report.FeatureIsNotAvailable (Location, "static classes");
2798 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2800 if (part.Name == "System.Object")
2801 Report.Error (537, part.Location,
2802 "The class System.Object cannot have a base class or implement an interface.");
2803 base.AddBasesForPart (part, bases);
2806 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2808 if (a.Type == TypeManager.attribute_usage_type) {
2809 if (!TypeManager.IsAttributeType (BaseType) &&
2810 TypeBuilder.FullName != "System.Attribute") {
2811 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2815 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2816 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2820 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2821 !attributes.Contains (TypeManager.guid_attr_type)) {
2822 a.Error_MissingGuidAttribute ();
2826 if (a.Type == TypeManager.extension_attribute_type) {
2827 a.Error_MisusedExtensionAttribute ();
2831 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2834 base.ApplyAttributeBuilder (a, cb);
2837 public override AttributeTargets AttributeTargets {
2839 return AttributeTargets.Class;
2843 protected override void DefineContainerMembers (MemberCoreArrayList list)
2849 base.DefineContainerMembers (list);
2853 foreach (MemberCore m in list) {
2854 if (m is Operator) {
2855 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2859 if (m is Destructor) {
2860 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2864 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2865 m.CheckProtectedModifier ();
2870 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2874 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2877 if (m is Constructor) {
2878 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2882 Method method = m as Method;
2883 if (method != null && method.Parameters.HasExtensionMethodType) {
2884 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2888 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2891 base.DefineContainerMembers (list);
2894 public override TypeBuilder DefineType ()
2896 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2897 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2901 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2902 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2906 return base.DefineType ();
2909 protected override bool DoDefineMembers ()
2911 if (InstanceConstructors == null && !IsStatic)
2912 DefineDefaultConstructor (false);
2914 return base.DoDefineMembers ();
2917 public override void Emit ()
2922 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2923 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2927 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2929 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2931 if (base_class == null) {
2932 if (RootContext.StdLib)
2933 base_class = TypeManager.system_object_expr;
2934 else if (Name != "System.Object")
2935 base_class = TypeManager.system_object_expr;
2937 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2939 689, base_class.Location,
2940 "Cannot derive from `{0}' because it is a type parameter",
2941 base_class.GetSignatureForError ());
2945 if (base_class.IsSealed){
2946 Report.SymbolRelatedToPreviousError (base_class.Type);
2947 if (base_class.Type.IsAbstract) {
2948 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2949 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2951 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2952 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2957 if (!base_class.CanInheritFrom ()){
2958 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2959 GetSignatureForError (), base_class.GetSignatureForError ());
2963 if (!base_class.AsAccessible (this)) {
2964 Report.SymbolRelatedToPreviousError (base_class.Type);
2965 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2966 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2970 if (PartialContainer.IsStaticClass) {
2971 if (base_class.Type != TypeManager.object_type) {
2972 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2973 GetSignatureForError (), base_class.GetSignatureForError ());
2977 if (ifaces != null) {
2978 foreach (TypeExpr t in ifaces)
2979 Report.SymbolRelatedToPreviousError (t.Type);
2980 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2987 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2988 /// Valid only for attribute classes.
2989 public bool IsExcluded ()
2991 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2992 return (caching_flags & Flags.Excluded) != 0;
2994 caching_flags &= ~Flags.Excluded_Undetected;
2996 if (OptAttributes == null)
2999 if (TypeManager.conditional_attribute_type == null)
3002 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3007 foreach (Attribute a in attrs) {
3008 string condition = a.GetConditionalAttributeValue ();
3009 if (Location.CompilationUnit.IsConditionalDefined (condition))
3013 caching_flags |= Flags.Excluded;
3019 return (ModFlags & Modifiers.STATIC) != 0;
3024 // FIXME: How do we deal with the user specifying a different
3027 protected override TypeAttributes TypeAttr {
3029 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3031 ta |= StaticClassAttribute;
3037 public sealed class Struct : ClassOrStruct {
3039 // Modifiers allowed in a struct declaration
3041 const int AllowedModifiers =
3044 Modifiers.PROTECTED |
3045 Modifiers.INTERNAL |
3049 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3050 int mod, Attributes attrs)
3051 : base (ns, parent, name, attrs, Kind.Struct)
3055 if (parent.Parent == null)
3056 accmods = Modifiers.INTERNAL;
3058 accmods = Modifiers.PRIVATE;
3060 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3062 this.ModFlags |= Modifiers.SEALED;
3065 public override AttributeTargets AttributeTargets {
3067 return AttributeTargets.Struct;
3071 const TypeAttributes DefaultTypeAttributes =
3072 TypeAttributes.SequentialLayout |
3073 TypeAttributes.Sealed |
3074 TypeAttributes.BeforeFieldInit;
3077 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3079 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3081 // If we are compiling our runtime,
3082 // and we are defining ValueType, then our
3083 // base is `System.Object'.
3085 if (base_class == null) {
3086 if (!RootContext.StdLib && Name == "System.ValueType")
3087 base_class = TypeManager.system_object_expr;
3089 base_class = TypeManager.system_valuetype_expr;
3096 // FIXME: Allow the user to specify a different set of attributes
3097 // in some cases (Sealed for example is mandatory for a class,
3098 // but what SequentialLayout can be changed
3100 protected override TypeAttributes TypeAttr {
3102 return base.TypeAttr | DefaultTypeAttributes;
3106 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3108 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3109 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3110 field.GetSignatureForError ());
3113 base.RegisterFieldForInitialization (field, expression);
3121 public sealed class Interface : TypeContainer, IMemberContainer {
3124 /// Modifiers allowed in a class declaration
3126 public const int AllowedModifiers =
3129 Modifiers.PROTECTED |
3130 Modifiers.INTERNAL |
3134 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3136 : base (ns, parent, name, attrs, Kind.Interface)
3140 if (parent.Parent == null)
3141 accmods = Modifiers.INTERNAL;
3143 accmods = Modifiers.PRIVATE;
3145 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3148 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3150 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3151 !attributes.Contains (TypeManager.guid_attr_type)) {
3152 a.Error_MissingGuidAttribute ();
3155 base.ApplyAttributeBuilder (a, cb);
3159 public override AttributeTargets AttributeTargets {
3161 return AttributeTargets.Interface;
3165 const TypeAttributes DefaultTypeAttributes =
3166 TypeAttributes.AutoLayout |
3167 TypeAttributes.Abstract |
3168 TypeAttributes.Interface;
3170 protected override TypeAttributes TypeAttr {
3172 return base.TypeAttr | DefaultTypeAttributes;
3176 protected override bool VerifyClsCompliance ()
3178 if (!base.VerifyClsCompliance ())
3181 if (ifaces != null) {
3182 foreach (Type t in ifaces) {
3183 if (AttributeTester.IsClsCompliant (t))
3186 Report.SymbolRelatedToPreviousError (t);
3187 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3188 GetSignatureForError (), TypeManager.CSharpName (t));
3196 // It is used as a base class for all property based members
3197 // This includes properties, indexers, and events
3198 public abstract class PropertyBasedMember : InterfaceMemberBase
3200 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3201 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3202 MemberName name, Attributes attrs)
3203 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3207 protected override bool VerifyClsCompliance ()
3209 if (!base.VerifyClsCompliance ())
3212 if (!AttributeTester.IsClsCompliant (MemberType)) {
3213 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3214 GetSignatureForError ());
3222 public abstract class MethodCore : InterfaceMemberBase
3224 public readonly Parameters Parameters;
3225 protected ToplevelBlock block;
3227 public MethodCore (DeclSpace parent, GenericMethod generic,
3228 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3229 MemberName name, Attributes attrs, Parameters parameters)
3230 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3232 Parameters = parameters;
3236 // Returns the System.Type array for the parameters of this method
3238 public Type [] ParameterTypes {
3240 return Parameters.Types;
3244 public Parameters ParameterInfo
3251 public ToplevelBlock Block {
3261 protected override bool CheckBase ()
3263 // Check whether arguments were correct.
3264 if (!DefineParameters (Parameters))
3267 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3268 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3269 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3272 // TODO: Find a better way how to check reserved accessors collision
3273 Method m = this as Method;
3275 if (!m.CheckForDuplications ())
3280 if (!base.CheckBase ())
3287 // Returns a string that represents the signature for this
3288 // member which should be used in XML documentation.
3290 public override string GetDocCommentName (DeclSpace ds)
3292 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3296 // Raised (and passed an XmlElement that contains the comment)
3297 // when GenerateDocComment is writing documentation expectedly.
3299 // FIXME: with a few effort, it could be done with XmlReader,
3300 // that means removal of DOM use.
3302 internal override void OnGenerateDocComment (XmlElement el)
3304 DocUtil.OnMethodGenerateDocComment (this, el);
3308 // Represents header string for documentation comment.
3310 public override string DocCommentHeader
3312 get { return "M:"; }
3315 public override bool EnableOverloadChecks (MemberCore overload)
3317 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3318 caching_flags |= Flags.MethodOverloadsExist;
3325 protected override bool VerifyClsCompliance ()
3327 if (!base.VerifyClsCompliance ())
3330 if (Parameters.HasArglist) {
3331 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3334 if (!AttributeTester.IsClsCompliant (MemberType)) {
3335 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3336 GetSignatureForError ());
3339 Parameters.VerifyClsCompliance ();
3345 public abstract class InterfaceMemberBase : MemberBase {
3347 // Whether this is an interface member.
3349 public bool IsInterface;
3352 // If true, this is an explicit interface implementation
3354 public bool IsExplicitImpl;
3356 protected bool is_external_implementation;
3359 // The interface type we are explicitly implementing
3361 public Type InterfaceType;
3364 // The method we're overriding if this is an override method.
3366 protected MethodInfo base_method;
3368 readonly int explicit_mod_flags;
3369 public MethodAttributes flags;
3371 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3372 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3373 MemberName name, Attributes attrs)
3374 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3377 IsInterface = is_iface;
3378 IsExplicitImpl = (MemberName.Left != null);
3379 explicit_mod_flags = mod;
3382 protected override bool CheckBase ()
3384 if (!base.CheckBase ())
3390 // Is null for System.Object while compiling corlib and base interfaces
3391 if (Parent.PartialContainer.BaseCache == null) {
3392 if ((ModFlags & Modifiers.NEW) != 0) {
3393 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3398 Type base_ret_type = null;
3399 base_method = FindOutBaseMethod (ref base_ret_type);
3401 // method is override
3402 if (base_method != null) {
3403 if (!CheckMethodAgainstBase (base_ret_type))
3406 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3407 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3409 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3410 Report.SymbolRelatedToPreviousError (base_method);
3411 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3412 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3415 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3416 Report.SymbolRelatedToPreviousError (base_method);
3417 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3418 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3425 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3426 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3427 if (conflict_symbol != null) {
3428 Report.SymbolRelatedToPreviousError (conflict_symbol);
3430 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3431 else if (this is PropertyBase)
3432 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3434 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3436 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3437 GetSignatureForError (), SimpleName.GetMemberType (this));
3442 if (conflict_symbol == null) {
3443 if ((ModFlags & Modifiers.NEW) != 0) {
3444 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3449 if ((ModFlags & Modifiers.NEW) == 0) {
3450 if (this is Method && conflict_symbol is MethodBase)
3453 Report.SymbolRelatedToPreviousError (conflict_symbol);
3454 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3455 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3462 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3463 // that have been defined.
3465 // `name' is the user visible name for reporting errors (this is used to
3466 // provide the right name regarding method names and properties)
3468 bool CheckMethodAgainstBase (Type base_method_type)
3472 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3473 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3474 Report.Error (506, Location,
3475 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3476 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3480 // Now we check that the overriden method is not final
3482 if (base_method.IsFinal) {
3483 Report.SymbolRelatedToPreviousError (base_method);
3484 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3485 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3489 // Check that the permissions are not being changed
3491 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3492 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3494 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3495 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3499 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3500 Report.SymbolRelatedToPreviousError (base_method);
3501 if (this is PropertyBasedMember) {
3502 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3503 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3506 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3507 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3513 if ((ModFlags & Modifiers.NEW) == 0) {
3514 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3515 ModFlags |= Modifiers.NEW;
3516 Report.SymbolRelatedToPreviousError (base_method);
3517 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3518 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",
3519 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3521 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3522 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3526 if (base_method.IsAbstract && !IsInterface) {
3527 Report.SymbolRelatedToPreviousError (base_method);
3528 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3529 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3537 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3539 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3541 // when overriding protected internal, the method can be declared
3542 // protected internal only within the same assembly or assembly
3543 // which has InternalsVisibleTo
3545 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3546 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3547 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3549 // if it's not "protected internal", it must be "protected"
3553 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3555 // protected within the same assembly - an error
3558 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3559 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3561 // protected ok, but other attributes differ - report an error
3567 return (thisp == base_classp);
3571 protected bool DefineParameters (Parameters parameters)
3573 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3575 if (!parameters.Resolve (rc))
3579 foreach (Parameter p in parameters.FixedParameters) {
3580 if (p.CheckAccessibility (this))
3583 Report.SymbolRelatedToPreviousError (p.ParameterType);
3584 if (this is Indexer)
3585 Report.Error (55, Location,
3586 "Inconsistent accessibility: parameter type `" +
3587 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3588 "accessible than indexer `" + GetSignatureForError () + "'");
3589 else if (this is Operator)
3590 Report.Error (57, Location,
3591 "Inconsistent accessibility: parameter type `" +
3592 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3593 "accessible than operator `" + GetSignatureForError () + "'");
3595 Report.Error (51, Location,
3596 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3597 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3603 protected override bool DoDefine()
3605 if (!base.DoDefine ())
3608 if (IsExplicitImpl) {
3609 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3613 InterfaceType = texpr.Type;
3615 if (!InterfaceType.IsInterface) {
3616 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3620 if (!Parent.PartialContainer.VerifyImplements (this))
3627 protected bool DoDefineBase ()
3630 throw new InternalErrorException ();
3633 ModFlags = Modifiers.PUBLIC |
3634 Modifiers.ABSTRACT |
3635 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3637 flags = MethodAttributes.Public |
3638 MethodAttributes.Abstract |
3639 MethodAttributes.HideBySig |
3640 MethodAttributes.NewSlot |
3641 MethodAttributes.Virtual;
3643 if (!Parent.PartialContainer.MethodModifiersValid (this))
3646 flags = Modifiers.MethodAttr (ModFlags);
3649 if (IsExplicitImpl) {
3650 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3651 if (iface_texpr == null)
3654 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3655 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3656 GetSignatureForError ());
3660 InterfaceType = iface_texpr.Type;
3662 if (!InterfaceType.IsInterface) {
3663 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3667 if (!Parent.PartialContainer.VerifyImplements (this))
3670 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3676 public override void Emit()
3678 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3679 // We are more strict than Microsoft and report CS0626 as error
3680 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3681 Report.Error (626, Location,
3682 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3683 GetSignatureForError ());
3689 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3691 Report.SymbolRelatedToPreviousError (base_method);
3692 string base_name = TypeManager.GetFullNameSignature (base_method);
3693 string this_name = GetSignatureForError ();
3694 if (suffix != null) {
3695 base_name += suffix;
3696 this_name += suffix;
3699 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3700 this_name, Modifiers.GetDescription (ma), base_name);
3703 protected static string Error722 {
3705 return "`{0}': static types cannot be used as return types";
3710 /// Gets base method and its return type
3712 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3715 // The "short" name of this property / indexer / event. This is the
3716 // name without the explicit interface.
3718 public string ShortName
3720 get { return MemberName.Name; }
3721 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3724 public string GetFullName (MemberName name)
3726 if (!IsExplicitImpl)
3729 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3732 protected override bool VerifyClsCompliance ()
3734 if (!base.VerifyClsCompliance ()) {
3735 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3736 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3739 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3740 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3745 if (GenericMethod != null)
3746 GenericMethod.VerifyClsCompliance ();
3751 public override bool IsUsed
3753 get { return IsExplicitImpl || base.IsUsed; }
3758 public abstract class MethodOrOperator : MethodCore, IMethodData
3760 public MethodBuilder MethodBuilder;
3761 ReturnParameter return_attributes;
3762 ListDictionary declarative_security;
3763 protected MethodData MethodData;
3765 static string[] attribute_targets = new string [] { "method", "return" };
3767 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3768 int allowed_mod, bool is_interface, MemberName name,
3769 Attributes attrs, Parameters parameters)
3770 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3775 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3777 if (a.Target == AttributeTargets.ReturnValue) {
3778 if (return_attributes == null)
3779 return_attributes = new ReturnParameter (MethodBuilder, Location);
3781 return_attributes.ApplyAttributeBuilder (a, cb);
3785 if (a.IsInternalMethodImplAttribute) {
3786 is_external_implementation = true;
3789 if (a.Type == TypeManager.dllimport_type) {
3790 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3791 if ((ModFlags & extern_static) != extern_static) {
3792 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3794 is_external_implementation = true;
3797 if (a.IsValidSecurityAttribute ()) {
3798 if (declarative_security == null)
3799 declarative_security = new ListDictionary ();
3800 a.ExtractSecurityPermissionSet (declarative_security);
3804 if (MethodBuilder != null)
3805 MethodBuilder.SetCustomAttribute (cb);
3808 public override AttributeTargets AttributeTargets {
3810 return AttributeTargets.Method;
3814 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3816 return new EmitContext (
3817 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3820 protected bool DefineGenericMethod ()
3822 if (!DoDefineBase ())
3826 if (GenericMethod != null) {
3827 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3828 if (!GenericMethod.Define (MethodBuilder))
3836 public bool ResolveMembers ()
3838 if (!DefineGenericMethod ())
3844 public override bool Define ()
3849 if (!CheckAbstractAndExtern (block != null))
3852 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3853 for (int i = 0; i < Parameters.Count; ++i ) {
3854 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
3855 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3856 GetSignatureForError ());
3865 if (block != null && block.IsIterator && !(Parent is IteratorStorey))
3866 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3868 if (IsPartialDefinition) {
3869 caching_flags &= ~Flags.Excluded_Undetected;
3870 caching_flags |= Flags.Excluded;
3871 // Add to member cache only when a partial method implementation is not there
3872 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3873 MethodBase mb = new PartialMethodDefinitionInfo (this);
3874 Parent.MemberCache.AddMember (mb, this);
3875 TypeManager.AddMethod (mb, this);
3881 MethodData = new MethodData (
3882 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3884 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3887 MethodBuilder = MethodData.MethodBuilder;
3890 if (MethodBuilder.IsGenericMethod)
3891 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3894 Parent.MemberCache.AddMember (MethodBuilder, this);
3896 if (!TypeManager.IsGenericParameter (MemberType)) {
3897 if (MemberType.IsAbstract && MemberType.IsSealed) {
3898 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3906 public override void Emit ()
3909 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3910 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3911 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3912 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3914 if (OptAttributes != null)
3915 OptAttributes.Emit ();
3917 if (declarative_security != null) {
3918 foreach (DictionaryEntry de in declarative_security) {
3919 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3926 protected void Error_ConditionalAttributeIsNotValid ()
3928 Report.Error (577, Location,
3929 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3930 GetSignatureForError ());
3933 public bool IsPartialDefinition {
3935 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3939 public bool IsPartialImplementation {
3941 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3945 public override string[] ValidAttributeTargets {
3947 return attribute_targets;
3951 #region IMethodData Members
3953 public CallingConventions CallingConventions {
3955 CallingConventions cc = Parameters.CallingConvention;
3957 if ((ModFlags & Modifiers.STATIC) == 0)
3958 cc |= CallingConventions.HasThis;
3960 // FIXME: How is `ExplicitThis' used in C#?
3966 public Type ReturnType {
3972 public MemberName MethodName {
3978 protected override bool CheckBase ()
3980 if (!base.CheckBase ())
3983 // TODO: Destructor should derive from MethodCore
3984 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3985 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3986 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3994 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3996 public bool IsExcluded () {
3997 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3998 return (caching_flags & Flags.Excluded) != 0;
4000 caching_flags &= ~Flags.Excluded_Undetected;
4002 if (base_method == null) {
4003 if (OptAttributes == null)
4006 if (TypeManager.conditional_attribute_type == null)
4009 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4014 foreach (Attribute a in attrs) {
4015 string condition = a.GetConditionalAttributeValue ();
4016 if (condition == null)
4019 if (Location.CompilationUnit.IsConditionalDefined (condition))
4023 caching_flags |= Flags.Excluded;
4027 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4029 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
4030 caching_flags |= Flags.Excluded;
4036 if (md.IsExcluded ()) {
4037 caching_flags |= Flags.Excluded;
4043 GenericMethod IMethodData.GenericMethod {
4045 return GenericMethod;
4049 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4056 public class SourceMethod : IMethodDef
4059 SourceMethodBuilder builder;
4061 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4063 this.method = method;
4065 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4068 public string Name {
4069 get { return method.Name; }
4074 if (method is MethodBuilder)
4075 return ((MethodBuilder) method).GetToken ().Token;
4076 else if (method is ConstructorBuilder)
4077 return ((ConstructorBuilder) method).GetToken ().Token;
4079 throw new NotSupportedException ();
4083 public void CloseMethod ()
4085 SymbolWriter.CloseMethod ();
4088 public void SetRealMethodName (string name)
4090 if (builder != null)
4091 builder.SetRealMethodName (name);
4094 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4096 if (!SymbolWriter.HasSymbolWriter)
4101 Location start_loc = block.StartLocation;
4102 if (start_loc.IsNull)
4105 ICompileUnit compile_unit = start_loc.CompilationUnit;
4106 if (compile_unit == null)
4109 return new SourceMethod (parent, method, compile_unit);
4113 public class Method : MethodOrOperator {
4116 /// Modifiers allowed in a class declaration
4118 const int AllowedModifiers =
4121 Modifiers.PROTECTED |
4122 Modifiers.INTERNAL |
4127 Modifiers.OVERRIDE |
4128 Modifiers.ABSTRACT |
4132 const int AllowedInterfaceModifiers =
4133 Modifiers.NEW | Modifiers.UNSAFE;
4136 // return_type can be "null" for VOID values.
4138 public Method (DeclSpace parent, GenericMethod generic,
4139 FullNamedExpression return_type, int mod, bool is_iface,
4140 MemberName name, Parameters parameters, Attributes attrs)
4141 : base (parent, generic, return_type, mod,
4142 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4143 is_iface, name, attrs, parameters)
4147 public override string GetSignatureForError()
4149 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4152 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4154 Report.Error (17, location,
4155 "Program `{0}' has more than one entry point defined: `{1}'",
4156 CodeGen.FileName, TypeManager.CSharpSignature(b));
4159 bool IsEntryPoint ()
4161 if (ReturnType != TypeManager.void_type &&
4162 ReturnType != TypeManager.int32_type)
4165 if (Parameters.Count == 0)
4168 if (Parameters.Count > 1)
4171 Type t = Parameters.ParameterType (0);
4172 return t.IsArray && t.GetArrayRank () == 1 &&
4173 TypeManager.GetElementType (t) == TypeManager.string_type &&
4174 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4177 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4179 if (a.Type == TypeManager.conditional_attribute_type) {
4180 if (IsExplicitImpl) {
4181 Error_ConditionalAttributeIsNotValid ();
4185 if (ReturnType != TypeManager.void_type) {
4186 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4190 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4191 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4196 Report.Error (582, Location, "Conditional not valid on interface members");
4200 if (MethodData.implementing != null) {
4201 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4202 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4203 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4207 for (int i = 0; i < Parameters.Count; ++i) {
4208 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4209 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4215 if (a.Type == TypeManager.extension_attribute_type) {
4216 a.Error_MisusedExtensionAttribute ();
4220 base.ApplyAttributeBuilder (a, cb);
4223 public bool CheckForDuplications ()
4225 ArrayList ar = Parent.PartialContainer.Properties;
4227 for (int i = 0; i < ar.Count; ++i) {
4228 PropertyBase pb = (PropertyBase) ar [i];
4229 if (pb.AreAccessorsDuplicateImplementation (this))
4234 ar = Parent.PartialContainer.Indexers;
4236 for (int i = 0; i < ar.Count; ++i) {
4237 PropertyBase pb = (PropertyBase) ar [i];
4238 if (pb.AreAccessorsDuplicateImplementation (this))
4249 public override bool Define ()
4251 if (!base.Define ())
4254 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4255 Error1599 (Location, ReturnType);
4259 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4260 Name == "Finalize" && !(this is Destructor)) {
4261 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4264 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4265 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4266 Parent.PartialContainer.Mark_HasEquals ();
4267 else if (Parameters.Empty && Name == "GetHashCode")
4268 Parent.PartialContainer.Mark_HasGetHashCode ();
4271 if ((ModFlags & Modifiers.STATIC) == 0)
4274 if (Parameters.HasExtensionMethodType) {
4275 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4276 if (!Parent.IsTopLevel)
4277 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4278 GetSignatureForError ());
4280 if (TypeManager.extension_attribute_type == null) {
4281 Report.Error (1110, Location,
4282 "`{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",
4283 GetSignatureForError ());
4284 } else if (TypeManager.extension_attribute_attr == null) {
4285 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4286 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4289 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4292 ModFlags |= Modifiers.METHOD_EXTENSION;
4293 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4294 CodeGen.Assembly.HasExtensionMethods = true;
4296 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4297 GetSignatureForError ());
4302 // This is used to track the Entry Point,
4304 if (RootContext.NeedsEntryPoint &&
4306 (RootContext.MainClass == null ||
4307 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4308 if (IsEntryPoint ()) {
4310 if (RootContext.EntryPoint == null) {
4311 if (Parent.IsGeneric || MemberName.IsGeneric) {
4312 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4313 GetSignatureForError ());
4315 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4316 md.SetMemberIsUsed ();
4318 RootContext.EntryPoint = MethodBuilder;
4319 RootContext.EntryPointLocation = Location;
4322 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4323 Error_DuplicateEntryPoint (MethodBuilder, Location);
4326 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4327 GetSignatureForError ());
4337 public override void Emit ()
4340 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4341 if (IsPartialDefinition) {
4343 // Do attribute checks only when partial implementation does not exist
4345 if (MethodBuilder == null)
4351 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4352 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4353 GetSignatureForError ());
4355 MethodData.Emit (Parent);
4359 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4360 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4366 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4367 Location, MethodBuilder);
4372 public override bool EnableOverloadChecks (MemberCore overload)
4374 // TODO: It can be deleted when members will be defined in correct order
4375 if (overload is Operator)
4376 return overload.EnableOverloadChecks (this);
4378 if (overload is Indexer)
4381 return base.EnableOverloadChecks (overload);
4384 public static void Error1599 (Location loc, Type t)
4386 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4389 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4391 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4392 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4397 if (mi.IsSpecialName)
4400 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4404 public void SetPartialDefinition (Method methodDefinition)
4406 caching_flags |= Flags.PartialDefinitionExists;
4407 methodDefinition.MethodBuilder = MethodBuilder;
4408 if (methodDefinition.attributes == null)
4411 if (attributes == null) {
4412 attributes = methodDefinition.attributes;
4414 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4418 protected override bool VerifyClsCompliance ()
4420 if (!base.VerifyClsCompliance ())
4423 if (ParameterInfo.Count > 0) {
4424 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4426 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4433 public abstract class ConstructorInitializer : ExpressionStatement
4435 ArrayList argument_list;
4436 MethodGroupExpr base_constructor_group;
4438 public ConstructorInitializer (ArrayList argument_list, Location loc)
4440 this.argument_list = argument_list;
4444 public ArrayList Arguments {
4446 return argument_list;
4450 public override Expression CreateExpressionTree (EmitContext ec)
4452 throw new NotSupportedException ("ET");
4455 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4457 if (argument_list != null){
4458 foreach (Argument a in argument_list){
4459 if (!a.Resolve (ec, loc))
4464 if (this is ConstructorBaseInitializer) {
4465 if (ec.ContainerType.BaseType == null)
4468 type = ec.ContainerType.BaseType;
4469 if (ec.ContainerType.IsValueType) {
4470 Report.Error (522, loc,
4471 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4476 // It is legal to have "this" initializers that take no arguments
4477 // in structs, they are just no-ops.
4479 // struct D { public D (int a) : this () {}
4481 if (ec.ContainerType.IsValueType && argument_list == null)
4484 type = ec.ContainerType;
4487 base_constructor_group = MemberLookupFinal (
4488 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4489 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4490 loc) as MethodGroupExpr;
4492 if (base_constructor_group == null)
4495 base_constructor_group = base_constructor_group.OverloadResolve (
4496 ec, ref argument_list, false, loc);
4498 if (base_constructor_group == null)
4501 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4503 if (base_ctor == caller_builder){
4504 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4510 public override Expression DoResolve (EmitContext ec)
4512 throw new NotSupportedException ();
4515 public override void Emit (EmitContext ec)
4517 // It can be null for static initializers
4518 if (base_constructor_group == null)
4523 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4525 base_constructor_group.EmitCall (ec, argument_list);
4528 public override void EmitStatement (EmitContext ec)
4534 public class ConstructorBaseInitializer : ConstructorInitializer {
4535 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4536 base (argument_list, l)
4541 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4542 public GeneratedBaseInitializer (Location loc):
4548 public class ConstructorThisInitializer : ConstructorInitializer {
4549 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4550 base (argument_list, l)
4555 public class Constructor : MethodCore, IMethodData {
4556 public ConstructorBuilder ConstructorBuilder;
4557 public ConstructorInitializer Initializer;
4558 ListDictionary declarative_security;
4559 bool has_compliant_args;
4562 // Modifiers allowed for a constructor.
4564 public const int AllowedModifiers =
4566 Modifiers.PROTECTED |
4567 Modifiers.INTERNAL |
4573 static readonly string[] attribute_targets = new string [] { "method" };
4576 // The spec claims that static is not permitted, but
4577 // my very own code has static constructors.
4579 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4580 ConstructorInitializer init, Location loc)
4581 : base (parent, null, null, mod, AllowedModifiers, false,
4582 new MemberName (name, loc), null, args)
4587 public bool HasCompliantArgs {
4588 get { return has_compliant_args; }
4591 public override AttributeTargets AttributeTargets {
4592 get { return AttributeTargets.Constructor; }
4596 // Returns true if this is a default constructor
4598 public bool IsDefault ()
4600 if ((ModFlags & Modifiers.STATIC) != 0)
4601 return Parameters.Empty;
4603 return Parameters.Empty &&
4604 (Initializer is ConstructorBaseInitializer) &&
4605 (Initializer.Arguments == null);
4608 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4610 if (a.IsValidSecurityAttribute ()) {
4611 if (declarative_security == null) {
4612 declarative_security = new ListDictionary ();
4614 a.ExtractSecurityPermissionSet (declarative_security);
4618 if (a.IsInternalMethodImplAttribute) {
4619 is_external_implementation = true;
4622 ConstructorBuilder.SetCustomAttribute (cb);
4625 protected override bool CheckBase ()
4627 if ((ModFlags & Modifiers.STATIC) != 0) {
4628 if (!Parameters.Empty) {
4629 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4630 GetSignatureForError ());
4634 // the rest can be ignored
4638 // Check whether arguments were correct.
4639 if (!DefineParameters (Parameters))
4642 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4643 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4646 if (Parent.PartialContainer.Kind == Kind.Struct) {
4647 if (ParameterTypes.Length == 0) {
4648 Report.Error (568, Location,
4649 "Structs cannot contain explicit parameterless constructors");
4654 CheckProtectedModifier ();
4660 // Creates the ConstructorBuilder
4662 public override bool Define ()
4664 if (ConstructorBuilder != null)
4667 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4668 MethodAttributes.SpecialName);
4670 if ((ModFlags & Modifiers.STATIC) != 0) {
4671 ca |= MethodAttributes.Static | MethodAttributes.Private;
4673 ca |= MethodAttributes.HideBySig;
4675 if ((ModFlags & Modifiers.PUBLIC) != 0)
4676 ca |= MethodAttributes.Public;
4677 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4678 if ((ModFlags & Modifiers.INTERNAL) != 0)
4679 ca |= MethodAttributes.FamORAssem;
4681 ca |= MethodAttributes.Family;
4682 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4683 ca |= MethodAttributes.Assembly;
4685 ca |= MethodAttributes.Private;
4688 if (!CheckAbstractAndExtern (block != null))
4691 // Check if arguments were correct.
4695 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4696 ca, CallingConventions,
4699 if (Parent.PartialContainer.IsComImport) {
4700 if (!IsDefault ()) {
4701 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4702 Parent.GetSignatureForError ());
4705 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4708 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4709 TypeManager.AddMethod (ConstructorBuilder, this);
4711 // It's here only to report an error
4712 if (block != null && block.IsIterator) {
4713 member_type = TypeManager.void_type;
4714 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4723 public override void Emit ()
4725 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4726 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4728 if (OptAttributes != null)
4729 OptAttributes.Emit ();
4733 EmitContext ec = CreateEmitContext (null, null);
4736 // If we use a "this (...)" constructor initializer, then
4737 // do not emit field initializers, they are initialized in the other constructor
4739 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4740 !(Initializer is ConstructorThisInitializer);
4742 if (emit_field_initializers)
4743 Parent.PartialContainer.ResolveFieldInitializers (ec);
4745 if (block != null) {
4746 // If this is a non-static `struct' constructor and doesn't have any
4747 // initializer, it must initialize all of the struct's fields.
4748 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4749 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4750 block.AddThisVariable (Parent, Location);
4752 if (!block.ResolveMeta (ec, ParameterInfo))
4755 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4756 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4757 Initializer = new GeneratedBaseInitializer (Location);
4760 // Spec mandates that Initializers will not have `this' access
4762 if (Initializer != null) {
4764 Initializer.Resolve (ConstructorBuilder, ec);
4765 ec.IsStatic = false;
4766 block.AddScopeStatement (new StatementExpression (Initializer));
4771 Parameters.ApplyAttributes (ConstructorBuilder);
4773 SourceMethod source = null;
4775 ec.OmitDebuggingInfo = true;
4777 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4779 bool unreachable = false;
4780 if (block != null) {
4781 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4784 ec.EmitMeta (block);
4786 if (Report.Errors > 0)
4789 if (emit_field_initializers)
4790 Parent.PartialContainer.EmitFieldInitializers (ec);
4792 ec.EmitResolvedTopBlock (block, unreachable);
4796 source.CloseMethod ();
4798 if (declarative_security != null) {
4799 foreach (DictionaryEntry de in declarative_security) {
4800 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4807 // Is never override
4808 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4813 public override string GetSignatureForError()
4815 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4818 public override string[] ValidAttributeTargets {
4820 return attribute_targets;
4824 protected override bool VerifyClsCompliance ()
4826 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4830 if (ParameterInfo.Count > 0) {
4831 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4833 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4835 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4836 foreach (Type param in ParameterTypes) {
4837 if (param.IsArray) {
4843 has_compliant_args = true;
4847 #region IMethodData Members
4849 public System.Reflection.CallingConventions CallingConventions {
4851 CallingConventions cc = Parameters.CallingConvention;
4853 if (Parent.PartialContainer.Kind == Kind.Class)
4854 if ((ModFlags & Modifiers.STATIC) == 0)
4855 cc |= CallingConventions.HasThis;
4857 // FIXME: How is `ExplicitThis' used in C#?
4863 public MemberName MethodName {
4869 public Type ReturnType {
4875 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4877 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4878 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4879 ec.CurrentBlock = block;
4883 public bool IsExcluded()
4888 GenericMethod IMethodData.GenericMethod {
4894 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4901 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4903 public interface IMethodData
4905 CallingConventions CallingConventions { get; }
4906 Location Location { get; }
4907 MemberName MethodName { get; }
4908 Type ReturnType { get; }
4909 GenericMethod GenericMethod { get; }
4910 Parameters ParameterInfo { get; }
4912 Attributes OptAttributes { get; }
4913 ToplevelBlock Block { get; set; }
4915 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4916 ObsoleteAttribute GetObsoleteAttribute ();
4917 string GetSignatureForError ();
4919 bool IsClsComplianceRequired ();
4920 void SetMemberIsUsed ();
4921 void EmitExtraSymbolInfo (SourceMethod source);
4925 // Encapsulates most of the Method's state
4927 public class MethodData {
4929 static FieldInfo methodbuilder_attrs_field;
4931 public readonly IMethodData method;
4933 public readonly GenericMethod GenericMethod;
4936 // Are we implementing an interface ?
4938 public MethodInfo implementing;
4943 protected InterfaceMemberBase member;
4944 protected int modifiers;
4945 protected MethodAttributes flags;
4946 protected Type declaring_type;
4947 protected MethodInfo parent_method;
4949 MethodBuilder builder = null;
4950 public MethodBuilder MethodBuilder {
4956 public Type DeclaringType {
4958 return declaring_type;
4962 public MethodData (InterfaceMemberBase member,
4963 int modifiers, MethodAttributes flags, IMethodData method)
4965 this.member = member;
4966 this.modifiers = modifiers;
4969 this.method = method;
4972 public MethodData (InterfaceMemberBase member,
4973 int modifiers, MethodAttributes flags,
4974 IMethodData method, MethodBuilder builder,
4975 GenericMethod generic, MethodInfo parent_method)
4976 : this (member, modifiers, flags, method)
4978 this.builder = builder;
4979 this.GenericMethod = generic;
4980 this.parent_method = parent_method;
4983 public bool Define (DeclSpace parent, string method_full_name)
4985 string name = method.MethodName.Basename;
4987 TypeContainer container = parent.PartialContainer;
4989 PendingImplementation pending = container.PendingImplementations;
4990 if (pending != null){
4991 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4993 if (member.InterfaceType != null){
4994 if (implementing == null){
4995 if (member is PropertyBase) {
4996 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4997 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4998 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5001 Report.Error (539, method.Location,
5002 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5003 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5007 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5008 Report.SymbolRelatedToPreviousError (implementing);
5009 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5010 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5014 if (implementing != null) {
5015 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5016 if (prop_method == null) {
5017 if (TypeManager.IsSpecialMethod (implementing)) {
5018 Report.SymbolRelatedToPreviousError (implementing);
5019 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5020 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5021 implementing.Name.StartsWith ("get_") ? "get" : "set");
5023 } else if (implementing.DeclaringType.IsInterface) {
5024 if (!implementing.IsSpecialName) {
5025 Report.SymbolRelatedToPreviousError (implementing);
5026 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5027 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5030 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5031 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5032 Report.SymbolRelatedToPreviousError (implementing);
5033 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5034 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5043 // For implicit implementations, make sure we are public, for
5044 // explicit implementations, make sure we are private.
5046 if (implementing != null){
5048 // Setting null inside this block will trigger a more
5049 // verbose error reporting for missing interface implementations
5051 // The "candidate" function has been flagged already
5052 // but it wont get cleared
5054 if (member.IsExplicitImpl){
5055 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5056 Report.SymbolRelatedToPreviousError (implementing);
5057 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5058 method.GetSignatureForError ());
5062 if (implementing.DeclaringType.IsInterface) {
5064 // If this is an interface method implementation,
5065 // check for public accessibility
5067 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5069 implementing = null;
5071 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5072 // We may never be private.
5073 implementing = null;
5075 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5077 // We may be protected if we're overriding something.
5079 implementing = null;
5084 // Static is not allowed
5086 if ((modifiers & Modifiers.STATIC) != 0){
5087 implementing = null;
5092 // If implementing is still valid, set flags
5094 if (implementing != null){
5096 // When implementing interface methods, set NewSlot
5097 // unless, we are overwriting a method.
5099 if (implementing.DeclaringType.IsInterface){
5100 if ((modifiers & Modifiers.OVERRIDE) == 0)
5101 flags |= MethodAttributes.NewSlot;
5104 MethodAttributes.Virtual |
5105 MethodAttributes.HideBySig;
5107 // Set Final unless we're virtual, abstract or already overriding a method.
5108 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5109 flags |= MethodAttributes.Final;
5112 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5114 if (builder == null)
5117 if (container.CurrentType != null)
5118 declaring_type = container.CurrentType;
5120 declaring_type = container.TypeBuilder;
5122 if (implementing != null){
5124 // clear the pending implemntation flag
5126 pending.ImplementMethod (name, member.InterfaceType, this, member.IsExplicitImpl);
5128 if (member.IsExplicitImpl)
5129 container.TypeBuilder.DefineMethodOverride (
5130 builder, implementing);
5133 TypeManager.AddMethod (builder, method);
5135 if (GenericMethod != null) {
5136 bool is_override = member.IsExplicitImpl |
5137 ((modifiers & Modifiers.OVERRIDE) != 0);
5139 if (implementing != null)
5140 parent_method = implementing;
5142 EmitContext ec = method.CreateEmitContext (container, null);
5143 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5152 /// Create the MethodBuilder for the method
5154 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5156 if (builder == null) {
5157 builder = container.TypeBuilder.DefineMethod (
5158 method_name, flags, method.CallingConventions,
5159 method.ReturnType, ParameterTypes);
5165 // Generic method has been already defined to resolve method parameters
5166 // correctly when they use type parameters
5168 builder.SetParameters (ParameterTypes);
5169 builder.SetReturnType (method.ReturnType);
5171 if (builder.Attributes != flags) {
5173 if (methodbuilder_attrs_field == null)
5174 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5175 methodbuilder_attrs_field.SetValue (builder, flags);
5177 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5181 throw new InternalErrorException ();
5188 public void Emit (DeclSpace parent)
5190 ToplevelBlock block = method.Block;
5194 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5196 ec = method.CreateEmitContext (parent, null);
5198 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5200 if (GenericMethod != null)
5201 GenericMethod.EmitAttributes ();
5203 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5206 // Handle destructors specially
5208 // FIXME: This code generates buggy code
5210 if (member is Destructor)
5211 EmitDestructor (ec, block);
5213 ec.EmitTopBlock (method, block);
5215 if (source != null) {
5216 method.EmitExtraSymbolInfo (source);
5217 source.CloseMethod ();
5221 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5223 ILGenerator ig = ec.ig;
5225 Label finish = ig.DefineLabel ();
5227 block.SetDestructor ();
5229 ig.BeginExceptionBlock ();
5230 ec.ReturnLabel = finish;
5231 ec.HasReturnLabel = true;
5232 ec.EmitTopBlock (method, block);
5234 // ig.MarkLabel (finish);
5235 ig.BeginFinallyBlock ();
5237 if (ec.ContainerType.BaseType != null) {
5238 Expression member_lookup = Expression.MemberLookup (
5239 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5240 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5242 if (member_lookup != null){
5243 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5245 ig.Emit (OpCodes.Ldarg_0);
5246 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5250 ig.EndExceptionBlock ();
5251 //ig.MarkLabel (ec.ReturnLabel);
5252 ig.Emit (OpCodes.Ret);
5256 // TODO: Should derive from MethodCore
5257 public class Destructor : Method {
5259 static string[] attribute_targets = new string [] { "method" };
5261 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5262 string name, Parameters parameters, Attributes attrs,
5264 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5268 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5270 if (a.Type == TypeManager.conditional_attribute_type) {
5271 Error_ConditionalAttributeIsNotValid ();
5275 base.ApplyAttributeBuilder (a, cb);
5278 public override string GetSignatureForError ()
5280 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5283 public override string[] ValidAttributeTargets {
5285 return attribute_targets;
5290 abstract public class MemberBase : MemberCore {
5291 protected FullNamedExpression type_name;
5292 public readonly DeclSpace ds;
5293 public readonly GenericMethod GenericMethod;
5296 // The type of this property / indexer / event
5298 protected Type member_type;
5299 public Type MemberType {
5301 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5302 if (member_type == null && type_name != null) {
5303 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5304 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5305 if (type_name != null) {
5306 member_type = type_name.Type;
5314 // The constructor is only exposed to our children
5316 protected MemberBase (DeclSpace parent, GenericMethod generic,
5317 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5318 MemberName name, Attributes attrs)
5319 : base (parent, name, attrs)
5321 this.ds = generic != null ? generic : (DeclSpace) parent;
5322 this.type_name = type;
5323 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5324 GenericMethod = generic;
5325 if (GenericMethod != null)
5326 GenericMethod.ModFlags = ModFlags;
5329 protected virtual bool CheckBase ()
5331 CheckProtectedModifier ();
5336 protected virtual bool DoDefine ()
5338 if (MemberType == null)
5341 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5342 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5343 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5344 GetSignatureForError (), Parent.GetSignatureForError ());
5348 // verify accessibility
5349 if (!IsAccessibleAs (MemberType)) {
5350 Report.SymbolRelatedToPreviousError (MemberType);
5351 if (this is Property)
5352 Report.Error (53, Location,
5353 "Inconsistent accessibility: property type `" +
5354 TypeManager.CSharpName (MemberType) + "' is less " +
5355 "accessible than property `" + GetSignatureForError () + "'");
5356 else if (this is Indexer)
5357 Report.Error (54, Location,
5358 "Inconsistent accessibility: indexer return type `" +
5359 TypeManager.CSharpName (MemberType) + "' is less " +
5360 "accessible than indexer `" + GetSignatureForError () + "'");
5361 else if (this is MethodCore) {
5362 if (this is Operator)
5363 Report.Error (56, Location,
5364 "Inconsistent accessibility: return type `" +
5365 TypeManager.CSharpName (MemberType) + "' is less " +
5366 "accessible than operator `" + GetSignatureForError () + "'");
5368 Report.Error (50, Location,
5369 "Inconsistent accessibility: return type `" +
5370 TypeManager.CSharpName (MemberType) + "' is less " +
5371 "accessible than method `" + GetSignatureForError () + "'");
5373 Report.Error (52, Location,
5374 "Inconsistent accessibility: field type `" +
5375 TypeManager.CSharpName (MemberType) + "' is less " +
5376 "accessible than field `" + GetSignatureForError () + "'");
5384 protected bool IsTypePermitted ()
5386 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5387 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5395 // Abstract class for all fields
5397 abstract public class FieldBase : MemberBase {
5398 public FieldBuilder FieldBuilder;
5399 public Status status;
5400 protected Expression initializer;
5403 public enum Status : byte {
5404 HAS_OFFSET = 4 // Used by FieldMember.
5407 static readonly string[] attribute_targets = new string [] { "field" };
5409 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5410 int allowed_mod, MemberName name, Attributes attrs)
5411 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5414 if ((mod & Modifiers.ABSTRACT) != 0)
5415 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5418 public override AttributeTargets AttributeTargets {
5420 return AttributeTargets.Field;
5424 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5426 if (a.Type == TypeManager.field_offset_attribute_type) {
5427 status |= Status.HAS_OFFSET;
5429 if (!Parent.PartialContainer.HasExplicitLayout) {
5430 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5434 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5435 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5441 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5442 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5448 if (a.Type == TypeManager.marshal_as_attr_type) {
5449 UnmanagedMarshal marshal = a.GetMarshal (this);
5450 if (marshal != null) {
5451 FieldBuilder.SetMarshal (marshal);
5456 if ((a.HasSecurityAttribute)) {
5457 a.Error_InvalidSecurityParent ();
5461 FieldBuilder.SetCustomAttribute (cb);
5464 protected override bool CheckBase ()
5466 if (!base.CheckBase ())
5469 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5470 if (conflict_symbol == null) {
5471 if ((ModFlags & Modifiers.NEW) != 0) {
5472 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5477 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5478 Report.SymbolRelatedToPreviousError (conflict_symbol);
5479 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5480 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5486 public override bool Define()
5488 if (MemberType == null || member_type == null)
5491 if (TypeManager.IsGenericParameter (MemberType))
5494 if (MemberType == TypeManager.void_type) {
5495 // TODO: wrong location
5496 Expression.Error_VoidInvalidInTheContext (Location);
5500 if (MemberType.IsSealed && MemberType.IsAbstract) {
5501 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5511 if (!IsTypePermitted ())
5518 // Represents header string for documentation comment.
5520 public override string DocCommentHeader {
5521 get { return "F:"; }
5524 public override void Emit ()
5527 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5528 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5531 if (OptAttributes != null) {
5532 OptAttributes.Emit ();
5535 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5536 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5542 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5544 Report.SymbolRelatedToPreviousError (static_class);
5545 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5549 public Expression Initializer {
5551 if (value != null) {
5552 this.initializer = value;
5557 protected virtual bool IsFieldClsCompliant {
5559 if (FieldBuilder == null)
5562 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5566 public override string[] ValidAttributeTargets
5569 return attribute_targets;
5573 protected override bool VerifyClsCompliance ()
5575 if (!base.VerifyClsCompliance ())
5578 if (!IsFieldClsCompliant) {
5579 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5580 GetSignatureForError ());
5585 public void SetAssigned ()
5587 caching_flags |= Flags.IsAssigned;
5591 interface IFixedBuffer
5593 FieldInfo Element { get; }
5594 Type ElementType { get; }
5597 public class FixedFieldExternal: IFixedBuffer
5599 FieldInfo element_field;
5601 public FixedFieldExternal (FieldInfo fi)
5603 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5606 #region IFixedField Members
5608 public FieldInfo Element {
5610 return element_field;
5614 public Type ElementType {
5616 return element_field.FieldType;
5624 /// Fixed buffer implementation
5626 public class FixedField : FieldBase, IFixedBuffer
5628 public const string FixedElementName = "FixedElementField";
5629 static int GlobalCounter = 0;
5630 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5631 static FieldInfo[] fi;
5633 TypeBuilder fixed_buffer_type;
5634 FieldBuilder element;
5635 Expression size_expr;
5637 const int AllowedModifiers =
5640 Modifiers.PROTECTED |
5641 Modifiers.INTERNAL |
5644 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5645 Expression size_expr, Attributes attrs, Location loc):
5646 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5648 if (RootContext.Version == LanguageVersion.ISO_1)
5649 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5651 this.size_expr = size_expr;
5654 public override bool Define()
5656 if (!Parent.IsInUnsafeScope)
5657 Expression.UnsafeError (Location);
5659 if (!base.Define ())
5662 if (!TypeManager.IsPrimitiveType (MemberType)) {
5663 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",
5664 GetSignatureForError ());
5667 // Create nested fixed buffer container
5668 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5669 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5670 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5672 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5673 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5675 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5676 Parent.MemberCache.AddMember (FieldBuilder, this);
5677 TypeManager.RegisterFieldBase (FieldBuilder, this);
5682 public override void Emit()
5684 if (Parent.PartialContainer.Kind != Kind.Struct) {
5685 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5686 GetSignatureForError ());
5689 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5690 Constant c = size_expr.ResolveAsConstant (ec, this);
5694 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5695 if (buffer_size_const == null)
5698 int buffer_size = buffer_size_const.Value;
5700 if (buffer_size <= 0) {
5701 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5705 int type_size = Expression.GetTypeSize (MemberType);
5707 if (buffer_size > int.MaxValue / type_size) {
5708 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5709 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5713 buffer_size *= type_size;
5714 EmitFieldSize (buffer_size);
5718 void EmitFieldSize (int buffer_size)
5720 if (TypeManager.struct_layout_attribute_type == null) {
5721 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5722 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5724 if (TypeManager.struct_layout_attribute_type == null)
5729 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5731 object [] fi_val = new object [] { buffer_size };
5733 if (TypeManager.struct_layout_attribute_ctor == null) {
5734 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5735 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5736 if (TypeManager.struct_layout_attribute_ctor == null)
5740 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5741 ctor_args, fi, fi_val);
5742 fixed_buffer_type.SetCustomAttribute (cab);
5745 // Don't emit FixedBufferAttribute attribute for private types
5747 if ((ModFlags & Modifiers.PRIVATE) != 0)
5750 if (TypeManager.fixed_buffer_attr_ctor == null) {
5751 if (TypeManager.fixed_buffer_attr_type == null) {
5752 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5753 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5755 if (TypeManager.fixed_buffer_attr_type == null)
5759 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5760 Location, TypeManager.type_type, TypeManager.int32_type);
5762 if (TypeManager.fixed_buffer_attr_ctor == null)
5766 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5767 FieldBuilder.SetCustomAttribute (cab);
5770 protected override bool IsFieldClsCompliant {
5776 #region IFixedField Members
5778 public FieldInfo Element {
5784 public Type ElementType {
5794 // The Field class is used to represents class/struct fields during parsing.
5796 public class Field : FieldBase {
5798 // Modifiers allowed in a class declaration
5800 const int AllowedModifiers =
5803 Modifiers.PROTECTED |
5804 Modifiers.INTERNAL |
5807 Modifiers.VOLATILE |
5811 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5812 Attributes attrs, Location loc)
5813 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5818 bool CanBeVolatile ()
5820 if (TypeManager.IsReferenceType (MemberType))
5823 if (MemberType.IsEnum)
5826 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5827 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5828 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5829 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5830 MemberType == TypeManager.float_type)
5836 public override bool Define ()
5838 if (!base.Define ())
5841 if ((ModFlags & Modifiers.VOLATILE) != 0){
5842 if (!CanBeVolatile ()) {
5843 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5844 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5847 if ((ModFlags & Modifiers.READONLY) != 0){
5848 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5849 GetSignatureForError ());
5853 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5857 Type[] required_modifier = null;
5858 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5859 if (TypeManager.isvolatile_type == null)
5860 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5861 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5863 if (TypeManager.isvolatile_type != null)
5864 required_modifier = new Type [] { TypeManager.isvolatile_type };
5867 FieldBuilder = Parent.TypeBuilder.DefineField (
5868 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5870 FieldBuilder = Parent.TypeBuilder.DefineField (
5871 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5873 Parent.MemberCache.AddMember (FieldBuilder, this);
5874 TypeManager.RegisterFieldBase (FieldBuilder, this);
5876 catch (ArgumentException) {
5877 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5881 if (initializer != null)
5882 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5883 new FieldInitializer (FieldBuilder, initializer));
5885 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
5886 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
5887 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
5888 GetSignatureForError ());
5895 public override string GetSignatureForError ()
5897 string s = base.GetSignatureForError ();
5898 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5901 // Undecorate name mangling
5902 int l = s.LastIndexOf ('>');
5903 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5906 protected override bool VerifyClsCompliance ()
5908 if (!base.VerifyClsCompliance ())
5911 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5912 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5920 // `set' and `get' accessors are represented with an Accessor.
5922 public class Accessor {
5924 // Null if the accessor is empty, or a Block if not
5926 public const int AllowedModifiers =
5928 Modifiers.PROTECTED |
5929 Modifiers.INTERNAL |
5932 public ToplevelBlock Block;
5933 public Attributes Attributes;
5934 public Location Location;
5935 public int ModFlags;
5937 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5942 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5946 // Ooouh Martin, templates are missing here.
5947 // When it will be possible move here a lot of child code and template method type.
5948 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5949 protected MethodData method_data;
5950 protected ToplevelBlock block;
5951 protected ListDictionary declarative_security;
5953 // The accessor are created event if they are not wanted.
5954 // But we need them because their names are reserved.
5955 // Field says whether accessor will be emited or not
5956 public readonly bool IsDummy;
5958 protected readonly string prefix;
5960 ReturnParameter return_attributes;
5962 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5963 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5965 this.prefix = prefix;
5969 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5971 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5972 accessor.Attributes)
5974 this.prefix = prefix;
5975 this.block = accessor.Block;
5978 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5980 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5983 public void UpdateName (InterfaceMemberBase member)
5985 SetMemberName (SetupName (prefix, member, Location));
5988 #region IMethodData Members
5990 public ToplevelBlock Block {
6000 public CallingConventions CallingConventions {
6002 return CallingConventions.Standard;
6006 public bool IsExcluded ()
6011 GenericMethod IMethodData.GenericMethod {
6017 public MemberName MethodName {
6023 public Type[] ParameterTypes {
6025 return ParameterInfo.Types;
6029 public abstract Parameters ParameterInfo { get ; }
6030 public abstract Type ReturnType { get; }
6031 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6035 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6037 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6038 a.Type == TypeManager.conditional_attribute_type) {
6039 Report.Error (1667, a.Location,
6040 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6041 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6045 if (a.IsValidSecurityAttribute ()) {
6046 if (declarative_security == null)
6047 declarative_security = new ListDictionary ();
6048 a.ExtractSecurityPermissionSet (declarative_security);
6052 if (a.Target == AttributeTargets.Method) {
6053 method_data.MethodBuilder.SetCustomAttribute (cb);
6057 if (a.Target == AttributeTargets.ReturnValue) {
6058 if (return_attributes == null)
6059 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6061 return_attributes.ApplyAttributeBuilder (a, cb);
6065 ApplyToExtraTarget (a, cb);
6068 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6070 throw new NotSupportedException ("You forgot to define special attribute target handling");
6073 // It is not supported for the accessors
6074 public sealed override bool Define()
6076 throw new NotSupportedException ();
6079 public void Emit (DeclSpace parent)
6081 EmitMethod (parent);
6084 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6085 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6086 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6087 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6089 if (OptAttributes != null)
6090 OptAttributes.Emit ();
6092 if (declarative_security != null) {
6093 foreach (DictionaryEntry de in declarative_security) {
6094 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6101 protected virtual void EmitMethod (DeclSpace parent)
6103 method_data.Emit (parent);
6106 public override bool EnableOverloadChecks (MemberCore overload)
6108 // This can only happen with indexers and it will
6109 // be catched as indexer difference
6110 if (overload is AbstractPropertyEventMethod)
6113 if (overload is MethodCore) {
6114 caching_flags |= Flags.MethodOverloadsExist;
6120 public override bool IsClsComplianceRequired()
6125 public bool IsDuplicateImplementation (MethodCore method)
6127 if (!MemberName.Equals (method.MemberName))
6130 Type[] param_types = method.ParameterTypes;
6132 if (param_types == null || param_types.Length != ParameterTypes.Length)
6135 for (int i = 0; i < param_types.Length; i++)
6136 if (param_types [i] != ParameterTypes [i])
6139 Report.SymbolRelatedToPreviousError (method);
6140 Report.Error (82, Location, "A member `{0}' is already reserved",
6141 method.GetSignatureForError ());
6145 public override bool IsUsed
6156 // Represents header string for documentation comment.
6158 public override string DocCommentHeader {
6159 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6162 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6167 // Properties and Indexers both generate PropertyBuilders, we use this to share
6168 // their common bits.
6170 abstract public class PropertyBase : PropertyBasedMember {
6172 public class GetMethod : PropertyMethod
6174 static string[] attribute_targets = new string [] { "method", "return" };
6176 public GetMethod (PropertyBase method):
6177 base (method, "get_")
6181 public GetMethod (PropertyBase method, Accessor accessor):
6182 base (method, accessor, "get_")
6186 public override MethodBuilder Define (DeclSpace parent)
6188 if (!CheckForDuplications ())
6194 base.Define (parent);
6196 method_data = new MethodData (method, ModFlags, flags, this);
6198 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6201 return method_data.MethodBuilder;
6204 public override Type ReturnType {
6206 return method.MemberType;
6210 public override Parameters ParameterInfo {
6212 return Parameters.EmptyReadOnlyParameters;
6216 public override string[] ValidAttributeTargets {
6218 return attribute_targets;
6223 public class SetMethod : PropertyMethod {
6225 static string[] attribute_targets = new string [] { "method", "param", "return" };
6226 ImplicitParameter param_attr;
6227 protected Parameters parameters;
6229 public SetMethod (PropertyBase method):
6230 base (method, "set_")
6234 public SetMethod (PropertyBase method, Accessor accessor):
6235 base (method, accessor, "set_")
6239 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6241 if (a.Target == AttributeTargets.Parameter) {
6242 if (param_attr == null)
6243 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6245 param_attr.ApplyAttributeBuilder (a, cb);
6249 base.ApplyAttributeBuilder (a, cb);
6252 public override Parameters ParameterInfo {
6254 if (parameters == null)
6255 DefineParameters ();
6260 protected virtual void DefineParameters ()
6262 parameters = Parameters.CreateFullyResolved (
6263 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6266 public override MethodBuilder Define (DeclSpace parent)
6268 if (!CheckForDuplications ())
6274 base.Define (parent);
6276 method_data = new MethodData (method, ModFlags, flags, this);
6278 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6281 return method_data.MethodBuilder;
6284 public override Type ReturnType {
6286 return TypeManager.void_type;
6290 public override string[] ValidAttributeTargets {
6292 return attribute_targets;
6297 static string[] attribute_targets = new string [] { "property" };
6299 public abstract class PropertyMethod : AbstractPropertyEventMethod
6301 protected readonly PropertyBase method;
6302 protected MethodAttributes flags;
6304 public PropertyMethod (PropertyBase method, string prefix)
6305 : base (method, prefix)
6307 this.method = method;
6310 public PropertyMethod (PropertyBase method, Accessor accessor,
6312 : base (method, accessor, prefix)
6314 this.method = method;
6315 this.ModFlags = accessor.ModFlags;
6317 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6318 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6322 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6324 if (a.IsInternalMethodImplAttribute) {
6325 method.is_external_implementation = true;
6328 base.ApplyAttributeBuilder (a, cb);
6331 public override AttributeTargets AttributeTargets {
6333 return AttributeTargets.Method;
6337 public override bool IsClsComplianceRequired ()
6339 return method.IsClsComplianceRequired ();
6342 public virtual MethodBuilder Define (DeclSpace parent)
6344 TypeContainer container = parent.PartialContainer;
6347 // Check for custom access modifier
6349 if ((ModFlags & Modifiers.Accessibility) == 0) {
6350 ModFlags |= method.ModFlags;
6351 flags = method.flags;
6353 if (container.Kind == Kind.Interface)
6354 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6355 GetSignatureForError ());
6357 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6358 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6361 CheckModifiers (ModFlags);
6362 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6363 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6364 flags = Modifiers.MethodAttr (ModFlags);
6365 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6368 CheckAbstractAndExtern (block != null);
6370 if (block != null && block.IsIterator)
6371 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6376 public bool HasCustomAccessModifier
6379 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6383 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6385 return new EmitContext (method,
6386 ds, method.ds, method.Location, ig, ReturnType,
6387 method.ModFlags, false);
6390 public override ObsoleteAttribute GetObsoleteAttribute ()
6392 return method.GetObsoleteAttribute ();
6395 public override string GetSignatureForError()
6397 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6400 void CheckModifiers (int modflags)
6402 modflags &= Modifiers.Accessibility;
6404 int mflags = method.ModFlags & Modifiers.Accessibility;
6406 if ((mflags & Modifiers.PUBLIC) != 0) {
6407 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6409 else if ((mflags & Modifiers.PROTECTED) != 0) {
6410 if ((mflags & Modifiers.INTERNAL) != 0)
6411 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6413 flags |= Modifiers.PRIVATE;
6415 else if ((mflags & Modifiers.INTERNAL) != 0)
6416 flags |= Modifiers.PRIVATE;
6418 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6419 Report.Error (273, Location,
6420 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6421 GetSignatureForError (), method.GetSignatureForError ());
6425 protected bool CheckForDuplications ()
6427 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6430 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6434 public PropertyMethod Get, Set;
6435 public PropertyBuilder PropertyBuilder;
6436 public MethodBuilder GetBuilder, SetBuilder;
6438 protected bool define_set_first = false;
6440 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6441 int allowed_mod, bool is_iface, MemberName name,
6442 Attributes attrs, bool define_set_first)
6443 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6445 this.define_set_first = define_set_first;
6448 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6450 if (a.HasSecurityAttribute) {
6451 a.Error_InvalidSecurityParent ();
6455 PropertyBuilder.SetCustomAttribute (cb);
6458 public override AttributeTargets AttributeTargets {
6460 return AttributeTargets.Property;
6464 public override bool Define ()
6469 if (!IsTypePermitted ())
6475 protected override bool DoDefine ()
6477 if (!base.DoDefine ())
6481 // Accessors modifiers check
6483 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6484 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6485 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6486 GetSignatureForError ());
6490 if ((Get.IsDummy || Set.IsDummy)
6491 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6492 Report.Error (276, Location,
6493 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6494 GetSignatureForError ());
6499 if (MemberType.IsGenericParameter)
6503 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6504 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6513 GetBuilder = Get.Define (Parent);
6514 return (Get.IsDummy) ? true : GetBuilder != null;
6517 bool DefineSet (bool define)
6522 SetBuilder = Set.Define (Parent);
6523 return (Set.IsDummy) ? true : SetBuilder != null;
6526 protected bool DefineAccessors ()
6528 return DefineSet (define_set_first) &&
6530 DefineSet (!define_set_first);
6533 protected abstract PropertyInfo ResolveBaseProperty ();
6535 // TODO: rename to Resolve......
6536 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6538 PropertyInfo base_property = ResolveBaseProperty ();
6539 if (base_property == null)
6542 base_ret_type = base_property.PropertyType;
6543 MethodInfo get_accessor = base_property.GetGetMethod (true);
6544 MethodInfo set_accessor = base_property.GetSetMethod (true);
6545 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6548 // Check base property accessors conflict
6550 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6551 if (get_accessor == null) {
6552 if (Get != null && !Get.IsDummy) {
6553 Report.SymbolRelatedToPreviousError (base_property);
6554 Report.Error (545, Location,
6555 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6556 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6559 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6561 if (!Get.IsDummy && !CheckAccessModifiers (
6562 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6563 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6566 if (set_accessor == null) {
6567 if (Set != null && !Set.IsDummy) {
6568 Report.SymbolRelatedToPreviousError (base_property);
6569 Report.Error (546, Location,
6570 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6571 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6574 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6576 if (!Set.IsDummy && !CheckAccessModifiers (
6577 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6578 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6582 // When one accessor does not exist and property hides base one
6583 // we need to propagate this upwards
6584 if (set_accessor == null)
6585 set_accessor = get_accessor;
6588 // Get the less restrictive access
6590 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6593 public override void Emit ()
6596 // The PropertyBuilder can be null for explicit implementations, in that
6597 // case, we do not actually emit the ".property", so there is nowhere to
6598 // put the attribute
6600 if (PropertyBuilder != null && OptAttributes != null)
6601 OptAttributes.Emit ();
6613 /// Tests whether accessors are not in collision with some method (CS0111)
6615 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6617 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6620 public override bool IsUsed
6626 return Get.IsUsed | Set.IsUsed;
6630 protected override void SetMemberName (MemberName new_name)
6632 base.SetMemberName (new_name);
6634 Get.UpdateName (this);
6635 Set.UpdateName (this);
6638 public override string[] ValidAttributeTargets {
6640 return attribute_targets;
6645 // Represents header string for documentation comment.
6647 public override string DocCommentHeader {
6648 get { return "P:"; }
6652 public class Property : PropertyBase {
6653 const int AllowedModifiers =
6656 Modifiers.PROTECTED |
6657 Modifiers.INTERNAL |
6661 Modifiers.OVERRIDE |
6662 Modifiers.ABSTRACT |
6667 const int AllowedInterfaceModifiers =
6670 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6673 Field field = new Field (
6675 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6676 "<" + Name + ">k__BackingField", null, Location);
6677 ((TypeContainer)Parent).PartialContainer.AddField (field);
6680 get_block.Block = new ToplevelBlock (block, null, Location);
6681 Return r = new Return (new SimpleName(field.Name, Location), Location);
6682 get_block.Block.AddStatement (r);
6683 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6686 Parameters parameters = new Parameters (new Parameter (type_name, "value", Parameter.Modifier.NONE, null, Location));
6687 set_block.Block = new ToplevelBlock (block, parameters, Location);
6688 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6689 set_block.Block.AddStatement (new StatementExpression(a));
6690 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6693 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6694 MemberName name, Attributes attrs, Accessor get_block,
6695 Accessor set_block, bool define_set_first)
6696 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6697 define_set_first, null)
6701 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6702 MemberName name, Attributes attrs, Accessor get_block,
6703 Accessor set_block, bool define_set_first, Block current_block)
6704 : base (parent, type, mod,
6705 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6706 is_iface, name, attrs, define_set_first)
6708 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6709 get_block != null && get_block.Block == null &&
6710 set_block != null && set_block.Block == null) {
6711 if (RootContext.Version <= LanguageVersion.ISO_2)
6712 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6714 CreateAutomaticProperty (current_block, get_block, set_block);
6717 if (get_block == null)
6718 Get = new GetMethod (this);
6720 Get = new GetMethod (this, get_block);
6722 if (set_block == null)
6723 Set = new SetMethod (this);
6725 Set = new SetMethod (this, set_block);
6728 public override bool Define ()
6730 if (!DoDefineBase ())
6733 if (!base.Define ())
6736 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6738 if (!DefineAccessors ())
6744 // FIXME - PropertyAttributes.HasDefault ?
6746 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6747 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6750 PropertyBuilder.SetGetMethod (GetBuilder);
6751 Parent.MemberCache.AddMember (GetBuilder, Get);
6755 PropertyBuilder.SetSetMethod (SetBuilder);
6756 Parent.MemberCache.AddMember (SetBuilder, Set);
6759 TypeManager.RegisterProperty (PropertyBuilder, this);
6760 Parent.MemberCache.AddMember (PropertyBuilder, this);
6764 protected override PropertyInfo ResolveBaseProperty ()
6766 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6767 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6772 /// Gigantic workaround for lameness in SRE follows :
6773 /// This class derives from EventInfo and attempts to basically
6774 /// wrap around the EventBuilder so that FindMembers can quickly
6775 /// return this in it search for members
6777 public class MyEventBuilder : EventInfo {
6780 // We use this to "point" to our Builder which is
6781 // not really a MemberInfo
6783 EventBuilder MyBuilder;
6786 // We "catch" and wrap these methods
6788 MethodInfo raise, remove, add;
6790 EventAttributes attributes;
6791 Type declaring_type, reflected_type, event_type;
6796 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6798 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6800 // And now store the values in our own fields.
6802 declaring_type = type_builder;
6804 reflected_type = type_builder;
6806 attributes = event_attr;
6809 this.event_type = event_type;
6813 // Methods that you have to override. Note that you only need
6814 // to "implement" the variants that take the argument (those are
6815 // the "abstract" methods, the others (GetAddMethod()) are
6818 public override MethodInfo GetAddMethod (bool nonPublic)
6823 public override MethodInfo GetRemoveMethod (bool nonPublic)
6828 public override MethodInfo GetRaiseMethod (bool nonPublic)
6834 // These methods make "MyEventInfo" look like a Builder
6836 public void SetRaiseMethod (MethodBuilder raiseMethod)
6838 raise = raiseMethod;
6839 MyBuilder.SetRaiseMethod (raiseMethod);
6842 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6844 remove = removeMethod;
6845 MyBuilder.SetRemoveOnMethod (removeMethod);
6848 public void SetAddOnMethod (MethodBuilder addMethod)
6851 MyBuilder.SetAddOnMethod (addMethod);
6854 public void SetCustomAttribute (CustomAttributeBuilder cb)
6856 MyBuilder.SetCustomAttribute (cb);
6859 public override object [] GetCustomAttributes (bool inherit)
6861 // FIXME : There's nothing which can be seemingly done here because
6862 // we have no way of getting at the custom attribute objects of the
6867 public override object [] GetCustomAttributes (Type t, bool inherit)
6869 // FIXME : Same here !
6873 public override bool IsDefined (Type t, bool b)
6878 public override EventAttributes Attributes {
6884 public override string Name {
6890 public override Type DeclaringType {
6892 return declaring_type;
6896 public override Type ReflectedType {
6898 return reflected_type;
6902 public Type EventType {
6908 public void SetUsed ()
6910 if (my_event != null) {
6911 // my_event.SetAssigned ();
6912 my_event.SetMemberIsUsed ();
6918 /// For case when event is declared like property (with add and remove accessors).
6920 public class EventProperty: Event {
6921 abstract class AEventPropertyAccessor : AEventAccessor
6923 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6924 base (method, accessor, prefix)
6928 public override MethodBuilder Define (DeclSpace ds)
6930 CheckAbstractAndExtern (block != null);
6931 return base.Define (ds);
6934 public override string GetSignatureForError ()
6936 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6940 sealed class AddDelegateMethod: AEventPropertyAccessor
6942 public AddDelegateMethod (Event method, Accessor accessor):
6943 base (method, accessor, "add_")
6947 protected override MethodInfo DelegateMethodInfo {
6949 return TypeManager.delegate_combine_delegate_delegate;
6954 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6956 public RemoveDelegateMethod (Event method, Accessor accessor):
6957 base (method, accessor, "remove_")
6961 protected override MethodInfo DelegateMethodInfo {
6963 return TypeManager.delegate_remove_delegate_delegate;
6969 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6971 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6972 bool is_iface, MemberName name,
6973 Attributes attrs, Accessor add, Accessor remove)
6974 : base (parent, type, mod_flags, is_iface, name, attrs)
6976 Add = new AddDelegateMethod (this, add);
6977 Remove = new RemoveDelegateMethod (this, remove);
6980 public override bool Define()
6982 if (!base.Define ())
6989 public override string[] ValidAttributeTargets {
6991 return attribute_targets;
6997 /// Event is declared like field.
6999 public class EventField : Event {
7000 abstract class EventFieldAccessor : AEventAccessor
7002 protected EventFieldAccessor (Event method, string prefix)
7003 : base (method, prefix)
7007 protected override void EmitMethod(DeclSpace parent)
7009 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7012 MethodBuilder mb = method_data.MethodBuilder;
7013 ILGenerator ig = mb.GetILGenerator ();
7015 // TODO: because we cannot use generics yet
7016 FieldInfo field_info = ((EventField)method).FieldBuilder;
7018 if (parent is Class) {
7019 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7022 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7023 ig.Emit (OpCodes.Ldsfld, field_info);
7024 ig.Emit (OpCodes.Ldarg_0);
7025 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7026 ig.Emit (OpCodes.Castclass, method.MemberType);
7027 ig.Emit (OpCodes.Stsfld, field_info);
7029 ig.Emit (OpCodes.Ldarg_0);
7030 ig.Emit (OpCodes.Ldarg_0);
7031 ig.Emit (OpCodes.Ldfld, field_info);
7032 ig.Emit (OpCodes.Ldarg_1);
7033 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7034 ig.Emit (OpCodes.Castclass, method.MemberType);
7035 ig.Emit (OpCodes.Stfld, field_info);
7037 ig.Emit (OpCodes.Ret);
7041 sealed class AddDelegateMethod: EventFieldAccessor
7043 public AddDelegateMethod (Event method):
7044 base (method, "add_")
7048 protected override MethodInfo DelegateMethodInfo {
7050 return TypeManager.delegate_combine_delegate_delegate;
7055 sealed class RemoveDelegateMethod: EventFieldAccessor
7057 public RemoveDelegateMethod (Event method):
7058 base (method, "remove_")
7062 protected override MethodInfo DelegateMethodInfo {
7064 return TypeManager.delegate_remove_delegate_delegate;
7070 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7071 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7073 public FieldBuilder FieldBuilder;
7074 public Expression Initializer;
7076 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags,
7077 bool is_iface, MemberName name,
7079 : base (parent, type, mod_flags, is_iface, name, attrs)
7081 Add = new AddDelegateMethod (this);
7082 Remove = new RemoveDelegateMethod (this);
7085 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7087 if (a.Target == AttributeTargets.Field) {
7088 FieldBuilder.SetCustomAttribute (cb);
7092 if (a.Target == AttributeTargets.Method) {
7093 int errors = Report.Errors;
7094 Add.ApplyAttributeBuilder (a, cb);
7095 if (errors == Report.Errors)
7096 Remove.ApplyAttributeBuilder (a, cb);
7100 base.ApplyAttributeBuilder (a, cb);
7103 public override bool Define()
7105 if (!base.Define ())
7111 // FIXME: We are unable to detect whether generic event is used because
7112 // we are using FieldExpr instead of EventExpr for event access in that
7113 // case. When this issue will be fixed this hack can be removed.
7114 if (TypeManager.IsGenericType (MemberType))
7117 if (Add.IsInterfaceImplementation)
7120 FieldBuilder = Parent.TypeBuilder.DefineField (
7122 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7123 TypeManager.RegisterEventField (EventBuilder, this);
7125 if (Initializer != null) {
7126 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7127 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7128 GetSignatureForError ());
7132 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7133 new FieldInitializer (FieldBuilder, Initializer));
7139 public override string[] ValidAttributeTargets
7142 return IsInterface ? attribute_targets_interface : attribute_targets;
7147 public abstract class Event : PropertyBasedMember {
7148 public abstract class AEventAccessor : AbstractPropertyEventMethod
7150 protected readonly Event method;
7151 ImplicitParameter param_attr;
7153 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7155 protected AEventAccessor (Event method, string prefix)
7156 : base (method, prefix)
7158 this.method = method;
7159 this.ModFlags = method.ModFlags;
7162 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7163 : base (method, accessor, prefix)
7165 this.method = method;
7166 this.ModFlags = method.ModFlags;
7169 public bool IsInterfaceImplementation {
7170 get { return method_data.implementing != null; }
7173 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7175 if (a.IsInternalMethodImplAttribute) {
7176 method.is_external_implementation = true;
7179 base.ApplyAttributeBuilder (a, cb);
7182 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7184 if (a.Target == AttributeTargets.Parameter) {
7185 if (param_attr == null)
7186 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7188 param_attr.ApplyAttributeBuilder (a, cb);
7192 base.ApplyAttributeBuilder (a, cb);
7195 public override AttributeTargets AttributeTargets {
7197 return AttributeTargets.Method;
7201 public override bool IsClsComplianceRequired ()
7203 return method.IsClsComplianceRequired ();
7206 public virtual MethodBuilder Define (DeclSpace parent)
7208 method_data = new MethodData (method, method.ModFlags,
7209 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7211 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7214 MethodBuilder mb = method_data.MethodBuilder;
7215 ParameterInfo.ApplyAttributes (mb);
7219 protected abstract MethodInfo DelegateMethodInfo { get; }
7221 public override Type ReturnType {
7223 return TypeManager.void_type;
7227 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7229 return new EmitContext (
7230 this, method.Parent, Location, ig, ReturnType,
7231 method.ModFlags, false);
7234 public override ObsoleteAttribute GetObsoleteAttribute ()
7236 return method.GetObsoleteAttribute ();
7239 public override string[] ValidAttributeTargets {
7241 return attribute_targets;
7245 public override Parameters ParameterInfo {
7247 return method.parameters;
7253 const int AllowedModifiers =
7256 Modifiers.PROTECTED |
7257 Modifiers.INTERNAL |
7262 Modifiers.OVERRIDE |
7264 Modifiers.ABSTRACT |
7267 const int AllowedInterfaceModifiers =
7270 public AEventAccessor Add, Remove;
7271 public MyEventBuilder EventBuilder;
7272 public MethodBuilder AddBuilder, RemoveBuilder;
7274 Parameters parameters;
7276 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags,
7277 bool is_iface, MemberName name, Attributes attrs)
7278 : base (parent, null, type, mod_flags,
7279 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7284 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7286 if ((a.HasSecurityAttribute)) {
7287 a.Error_InvalidSecurityParent ();
7291 EventBuilder.SetCustomAttribute (cb);
7294 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7296 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7299 public override AttributeTargets AttributeTargets {
7301 return AttributeTargets.Event;
7305 public override bool Define ()
7307 if (!DoDefineBase ())
7313 if (!TypeManager.IsDelegateType (MemberType)) {
7314 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7318 parameters = Parameters.CreateFullyResolved (
7319 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7324 if (TypeManager.delegate_combine_delegate_delegate == null) {
7325 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7326 TypeManager.delegate_type, "Combine", Location,
7327 TypeManager.delegate_type, TypeManager.delegate_type);
7329 if (TypeManager.delegate_remove_delegate_delegate == null) {
7330 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7331 TypeManager.delegate_type, "Remove", Location,
7332 TypeManager.delegate_type, TypeManager.delegate_type);
7336 // Now define the accessors
7339 AddBuilder = Add.Define (Parent);
7340 if (AddBuilder == null)
7343 RemoveBuilder = Remove.Define (Parent);
7344 if (RemoveBuilder == null)
7347 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7348 EventBuilder.SetAddOnMethod (AddBuilder);
7349 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7351 Parent.MemberCache.AddMember (EventBuilder, this);
7352 Parent.MemberCache.AddMember (AddBuilder, Add);
7353 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7358 public override void Emit ()
7360 if (OptAttributes != null) {
7361 OptAttributes.Emit ();
7365 Remove.Emit (Parent);
7370 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7372 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7373 Parent.TypeBuilder, Name);
7378 ParameterData pd = TypeManager.GetParameterData (mi);
7379 base_ret_type = pd.ParameterType (0);
7384 // Represents header string for documentation comment.
7386 public override string DocCommentHeader {
7387 get { return "E:"; }
7392 public class Indexer : PropertyBase
7394 public class GetIndexerMethod : GetMethod
7396 Parameters parameters;
7398 public GetIndexerMethod (PropertyBase method):
7403 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7404 base (method, accessor)
7408 public override MethodBuilder Define (DeclSpace parent)
7411 // Clone indexer accessor parameters for localized capturing
7413 parameters = ((Indexer) method).parameters.Clone ();
7414 return base.Define (parent);
7417 public override bool EnableOverloadChecks (MemberCore overload)
7419 if (base.EnableOverloadChecks (overload)) {
7420 overload.caching_flags |= Flags.MethodOverloadsExist;
7427 public override Parameters ParameterInfo {
7434 public class SetIndexerMethod: SetMethod
7436 public SetIndexerMethod (PropertyBase method):
7441 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7442 base (method, accessor)
7446 protected override void DefineParameters ()
7448 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7449 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7452 public override bool EnableOverloadChecks (MemberCore overload)
7454 if (base.EnableOverloadChecks (overload)) {
7455 overload.caching_flags |= Flags.MethodOverloadsExist;
7463 const int AllowedModifiers =
7466 Modifiers.PROTECTED |
7467 Modifiers.INTERNAL |
7471 Modifiers.OVERRIDE |
7476 const int AllowedInterfaceModifiers =
7479 public readonly Parameters parameters;
7481 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7482 bool is_iface, Parameters parameters, Attributes attrs,
7483 Accessor get_block, Accessor set_block, bool define_set_first)
7484 : base (parent, type, mod,
7485 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7486 is_iface, name, attrs, define_set_first)
7488 if (type == TypeManager.system_void_expr)
7489 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7491 this.parameters = parameters;
7493 if (get_block == null)
7494 Get = new GetIndexerMethod (this);
7496 Get = new GetIndexerMethod (this, get_block);
7498 if (set_block == null)
7499 Set = new SetIndexerMethod (this);
7501 Set = new SetIndexerMethod (this, set_block);
7504 public override bool Define ()
7506 if (!DoDefineBase ())
7509 if (!base.Define ())
7512 if (!DefineParameters (parameters))
7515 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7516 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7517 if (indexer_attr != null) {
7518 // Remove the attribute from the list because it is not emitted
7519 OptAttributes.Attrs.Remove (indexer_attr);
7521 string name = indexer_attr.GetIndexerAttributeValue ();
7527 if (IsExplicitImpl) {
7528 Report.Error (415, indexer_attr.Location,
7529 "The `IndexerName' attribute is valid only on an " +
7530 "indexer that is not an explicit interface member declaration");
7534 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7535 Report.Error (609, indexer_attr.Location,
7536 "Cannot set the `IndexerName' attribute on an indexer marked override");
7542 if (InterfaceType != null) {
7543 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7544 if (base_IndexerName != Name)
7545 ShortName = base_IndexerName;
7548 if (!Parent.PartialContainer.AddMember (this) ||
7549 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7552 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7553 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7557 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7559 if (!DefineAccessors ())
7566 // Now name the parameters
7568 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7569 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7572 PropertyBuilder.SetGetMethod (GetBuilder);
7573 Parent.MemberCache.AddMember (GetBuilder, Get);
7577 PropertyBuilder.SetSetMethod (SetBuilder);
7578 Parent.MemberCache.AddMember (SetBuilder, Set);
7581 TypeManager.RegisterIndexer (PropertyBuilder, parameters.Types);
7582 Parent.MemberCache.AddMember (PropertyBuilder, this);
7586 public override bool EnableOverloadChecks (MemberCore overload)
7588 if (overload is Indexer) {
7589 caching_flags |= Flags.MethodOverloadsExist;
7596 public override string GetDocCommentName (DeclSpace ds)
7598 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7601 public override string GetSignatureForError ()
7603 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7604 if (MemberName.Left != null) {
7606 sb.Append (MemberName.Left.GetSignatureForError ());
7609 sb.Append (".this");
7610 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7611 return sb.ToString ();
7614 protected override PropertyInfo ResolveBaseProperty ()
7616 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7617 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7620 protected override bool VerifyClsCompliance ()
7622 if (!base.VerifyClsCompliance ())
7625 parameters.VerifyClsCompliance ();
7630 public class Operator : MethodOrOperator {
7632 const int AllowedModifiers =
7638 public enum OpType : byte {
7648 // Unary and Binary operators
7671 // Implicit and Explicit
7675 // Just because of enum
7679 public readonly OpType OperatorType;
7681 static readonly string [] [] names;
7685 names = new string[(int)OpType.TOP][];
7686 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7687 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7688 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7689 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7690 names [(int) OpType.True] = new string [] { "true", "op_True" };
7691 names [(int) OpType.False] = new string [] { "false", "op_False" };
7692 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7693 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7694 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7695 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7696 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7697 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7698 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7699 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7700 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7701 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7702 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7703 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7704 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7705 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7706 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7707 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7708 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7709 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7710 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7711 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7714 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7715 int mod_flags, Parameters parameters,
7716 ToplevelBlock block, Attributes attrs, Location loc)
7717 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7718 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7720 OperatorType = type;
7724 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7726 if (a.Type == TypeManager.conditional_attribute_type) {
7727 Error_ConditionalAttributeIsNotValid ();
7731 base.ApplyAttributeBuilder (a, cb);
7734 public override bool Define ()
7736 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7737 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7738 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7742 if (!base.Define ())
7745 // imlicit and explicit operator of same types are not allowed
7746 if (OperatorType == OpType.Explicit)
7747 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7748 else if (OperatorType == OpType.Implicit)
7749 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7751 if (MemberType == TypeManager.void_type) {
7752 Report.Error (590, Location, "User-defined operators cannot return void");
7756 Type declaring_type = MethodData.DeclaringType;
7757 Type return_type = MemberType;
7758 Type first_arg_type = ParameterTypes [0];
7760 Type first_arg_type_unwrap = first_arg_type;
7761 if (TypeManager.IsNullableType (first_arg_type))
7762 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7764 Type return_type_unwrap = return_type;
7765 if (TypeManager.IsNullableType (return_type))
7766 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7769 // Rules for conversion operators
7771 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7772 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7773 Report.Error (555, Location,
7774 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7779 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7780 conv_type = first_arg_type;
7781 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7782 conv_type = return_type;
7784 Report.Error (556, Location,
7785 "User-defined conversion must convert to or from the enclosing type");
7790 // Because IsInterface and IsClass are not supported
7792 if (!TypeManager.IsGenericParameter (conv_type)) {
7793 if (conv_type.IsInterface) {
7794 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7795 GetSignatureForError ());
7799 if (conv_type.IsClass) {
7800 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7801 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7802 GetSignatureForError ());
7806 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7807 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7808 GetSignatureForError ());
7813 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7814 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7815 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");
7818 } else if (Parameters.Count == 1) {
7819 // Checks for Unary operators
7821 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7822 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7823 Report.Error (448, Location,
7824 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7827 if (first_arg_type != declaring_type) {
7829 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7834 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7835 Report.Error (562, Location,
7836 "The parameter type of a unary operator must be the containing type");
7840 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7841 if (return_type != TypeManager.bool_type){
7844 "The return type of operator True or False " +
7851 // Checks for Binary operators
7853 if (first_arg_type != declaring_type &&
7854 ParameterTypes [1] != declaring_type){
7857 "One of the parameters of a binary operator must " +
7858 "be the containing type");
7866 protected override bool DoDefine ()
7868 if (!base.DoDefine ())
7871 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7875 public override void Emit ()
7879 Parameters.ApplyAttributes (MethodBuilder);
7882 // abstract or extern methods have no bodies
7884 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7888 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7889 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7891 ec = CreateEmitContext (Parent, null);
7893 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7894 ec.EmitTopBlock (this, Block);
7897 source.CloseMethod ();
7902 // Operator cannot be override
7903 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7908 public static string GetName (OpType ot)
7910 return names [(int) ot] [0];
7913 public static string GetName (string metadata_name)
7915 for (int i = 0; i < names.Length; ++i) {
7916 if (names [i] [1] == metadata_name)
7917 return names [i] [0];
7922 public static string GetMetadataName (OpType ot)
7924 return names [(int) ot] [1];
7927 public static string GetMetadataName (string name)
7929 for (int i = 0; i < names.Length; ++i) {
7930 if (names [i] [0] == name)
7931 return names [i] [1];
7936 public OpType GetMatchingOperator ()
7938 switch (OperatorType) {
7939 case OpType.Equality:
7940 return OpType.Inequality;
7941 case OpType.Inequality:
7942 return OpType.Equality;
7944 return OpType.False;
7947 case OpType.GreaterThan:
7948 return OpType.LessThan;
7949 case OpType.LessThan:
7950 return OpType.GreaterThan;
7951 case OpType.GreaterThanOrEqual:
7952 return OpType.LessThanOrEqual;
7953 case OpType.LessThanOrEqual:
7954 return OpType.GreaterThanOrEqual;
7960 public override string GetSignatureForError ()
7962 StringBuilder sb = new StringBuilder ();
7963 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7964 sb.AppendFormat ("{0}.{1} operator {2}",
7965 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7968 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7971 sb.Append (Parameters.GetSignatureForError ());
7972 return sb.ToString ();
7977 // This is used to compare method signatures
7979 struct MethodSignature {
7981 public Type RetType;
7982 public Type [] Parameters;
7985 /// This delegate is used to extract methods which have the
7986 /// same signature as the argument
7988 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7990 public MethodSignature (string name, Type ret_type, Type [] parameters)
7995 if (parameters == null)
7996 Parameters = Type.EmptyTypes;
7998 Parameters = parameters;
8001 public override string ToString ()
8004 if (Parameters.Length != 0){
8005 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8006 for (int i = 0; i < Parameters.Length; i++){
8007 sb.Append (Parameters [i]);
8008 if (i+1 < Parameters.Length)
8011 pars = sb.ToString ();
8014 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8017 public override int GetHashCode ()
8019 return Name.GetHashCode ();
8022 public override bool Equals (Object o)
8024 MethodSignature other = (MethodSignature) o;
8026 if (other.Name != Name)
8029 if (other.RetType != RetType)
8032 if (Parameters == null){
8033 if (other.Parameters == null)
8038 if (other.Parameters == null)
8041 int c = Parameters.Length;
8042 if (other.Parameters.Length != c)
8045 for (int i = 0; i < c; i++)
8046 if (other.Parameters [i] != Parameters [i])
8052 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8054 MethodSignature sig = (MethodSignature) filter_criteria;
8056 if (m.Name != sig.Name)
8060 MethodInfo mi = m as MethodInfo;
8061 PropertyInfo pi = m as PropertyInfo;
8064 ReturnType = mi.ReturnType;
8065 else if (pi != null)
8066 ReturnType = pi.PropertyType;
8071 // we use sig.RetType == null to mean `do not check the
8072 // method return value.
8074 if (sig.RetType != null) {
8075 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8081 args = TypeManager.GetParameterData (mi).Types;
8083 args = TypeManager.GetArgumentTypes (pi);
8084 Type [] sigp = sig.Parameters;
8086 if (args.Length != sigp.Length)
8089 for (int i = args.Length - 1; i >= 0; i--)
8090 if (!TypeManager.IsEqual (args [i], sigp [i]))