2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
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 ArrayList type_bases;
254 bool members_resolved;
255 bool members_resolved_ok;
256 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;
274 GenericTypeParameterBuilder[] gen_params;
277 ArrayList partial_parts;
280 /// The pending methods that need to be implemented
281 // (interfaces or abstract methods)
283 PendingImplementation pending;
285 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
286 Attributes attrs, Kind kind)
287 : base (ns, parent, name, attrs)
289 if (parent != null && parent.NamespaceEntry != ns)
290 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
293 this.PartialContainer = this;
296 public bool AddMember (MemberCore symbol)
298 return AddToContainer (symbol, symbol.MemberName.MethodName);
301 protected virtual bool AddMemberType (DeclSpace ds)
303 return AddToContainer (ds, ds.Basename);
306 public void AddConstant (Const constant)
308 if (!AddMember (constant))
311 if (constants == null)
312 constants = new MemberCoreArrayList ();
314 constants.Add (constant);
317 public TypeContainer AddTypeContainer (TypeContainer tc)
319 if (!AddMemberType (tc))
323 types = new MemberCoreArrayList ();
329 public virtual TypeContainer AddPartial (TypeContainer next_part)
331 return AddPartial (next_part, next_part.Basename);
334 protected TypeContainer AddPartial (TypeContainer next_part, string name)
336 next_part.ModFlags |= Modifiers.PARTIAL;
337 TypeContainer tc = defined_names [name] as TypeContainer;
340 return AddTypeContainer (next_part);
342 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
343 Report.SymbolRelatedToPreviousError (tc);
344 Error_MissingPartialModifier (next_part);
347 if (tc.Kind != next_part.Kind) {
348 Report.SymbolRelatedToPreviousError (tc);
349 Report.Error (261, next_part.Location,
350 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
351 next_part.GetSignatureForError ());
354 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
355 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
356 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
357 Report.SymbolRelatedToPreviousError (tc);
358 Report.Error (262, next_part.Location,
359 "Partial declarations of `{0}' have conflicting accessibility modifiers",
360 next_part.GetSignatureForError ());
363 if (tc.MemberName.IsGeneric) {
364 TypeParameter[] tc_names = tc.TypeParameters;
365 TypeParameterName[] part_names = next_part.MemberName.TypeArguments.GetDeclarations ();
367 for (int i = 0; i < tc_names.Length; ++i) {
368 if (tc_names[i].Name == part_names[i].Name)
371 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
372 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
373 tc.GetSignatureForError ());
377 if (tc.partial_parts == null)
378 tc.partial_parts = new ArrayList (1);
380 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
381 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
382 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
383 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
384 tc.ModFlags |= next_part.ModFlags;
386 tc.ModFlags |= next_part.ModFlags;
389 if (next_part.attributes != null) {
390 if (tc.attributes == null)
391 tc.attributes = next_part.attributes;
393 tc.attributes.AddAttributes (next_part.attributes.Attrs);
396 next_part.PartialContainer = tc;
397 tc.partial_parts.Add (next_part);
401 public void AddDelegate (Delegate d)
403 if (!AddMemberType (d))
406 if (delegates == null)
407 delegates = new MemberCoreArrayList ();
412 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
414 if (ordered_explicit_member_list == null) {
415 ordered_explicit_member_list = new MemberCoreArrayList ();
416 ordered_member_list = new MemberCoreArrayList ();
420 ordered_explicit_member_list.Add (mc);
421 alist.Insert (0, mc);
424 ordered_member_list.Add (mc);
430 public void AddMethod (Method method)
432 MemberName mn = method.MemberName;
433 if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
437 methods = new MemberCoreArrayList ();
439 if (method.MemberName.Left != null)
440 AddMemberToList (method, methods, true);
442 AddMemberToList (method, methods, false);
446 // Do not use this method: use AddMethod.
448 // This is only used by iterators.
450 public void AppendMethod (Method method)
452 if (!AddMember (method))
456 methods = new MemberCoreArrayList ();
458 AddMemberToList (method, methods, false);
461 public void AddConstructor (Constructor c)
463 if (c.Name != MemberName.Name) {
464 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
467 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
468 if (!AddToContainer (c, is_static ?
469 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
472 if (is_static && c.Parameters.Empty){
473 if (default_static_constructor != null) {
474 Report.SymbolRelatedToPreviousError (default_static_constructor);
475 Report.Error (111, c.Location,
476 "A member `{0}' is already defined. Rename this member or use different parameter types",
477 c.GetSignatureForError ());
481 default_static_constructor = c;
483 if (c.Parameters.Empty)
484 default_constructor = c;
486 if (instance_constructors == null)
487 instance_constructors = new MemberCoreArrayList ();
489 instance_constructors.Add (c);
493 public bool AddField (FieldBase field)
495 if (!AddMember (field))
499 fields = new MemberCoreArrayList ();
503 if ((field.ModFlags & Modifiers.STATIC) != 0)
506 if (first_nonstatic_field == null) {
507 first_nonstatic_field = field;
511 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
512 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
513 Report.Warning (282, 3, field.Location,
514 "struct instance field `{0}' found in different declaration from instance field `{1}'",
515 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
520 public void AddProperty (Property prop)
522 if (!AddMember (prop) ||
523 !AddMember (prop.Get) || !AddMember (prop.Set))
526 if (properties == null)
527 properties = new MemberCoreArrayList ();
529 if (prop.MemberName.Left != null)
530 AddMemberToList (prop, properties, true);
532 AddMemberToList (prop, properties, false);
535 public void AddEvent (Event e)
540 if (e is EventProperty) {
541 if (!AddMember (e.Add))
544 if (!AddMember (e.Remove))
549 events = new MemberCoreArrayList ();
555 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
557 public void AddIndexer (Indexer i)
559 if (indexers == null)
560 indexers = new ArrayList ();
562 if (i.IsExplicitImpl)
563 AddMemberToList (i, indexers, true);
565 AddMemberToList (i, indexers, false);
568 public void AddOperator (Operator op)
573 if (operators == null)
574 operators = new OperatorArrayList (this);
579 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
581 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
583 if (compiler_generated == null)
584 compiler_generated = new ArrayList ();
586 compiler_generated.Add (c);
589 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
591 if (a.Type == TypeManager.default_member_type) {
592 if (Indexers != null) {
593 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
598 base.ApplyAttributeBuilder (a, cb);
601 public override AttributeTargets AttributeTargets {
603 throw new NotSupportedException ();
607 public ArrayList Types {
613 public MemberCoreArrayList Methods {
619 public ArrayList Constants {
625 public ArrayList CompilerGenerated {
627 return compiler_generated;
631 protected Type BaseType {
633 return TypeBuilder.BaseType;
637 public ArrayList Bases {
647 public ArrayList Fields {
653 public ArrayList InstanceConstructors {
655 return instance_constructors;
659 public ArrayList Properties {
665 public ArrayList Events {
671 public ArrayList Indexers {
677 public ArrayList Operators {
683 public ArrayList Delegates {
689 protected override TypeAttributes TypeAttr {
691 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
695 public string IndexerName {
697 return indexers == null ? DefaultIndexerName : indexer_name;
701 public bool IsComImport {
703 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
706 return OptAttributes.Contains (TypeManager.comimport_attr_type);
710 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
712 if ((field.ModFlags & Modifiers.STATIC) != 0){
713 if (initialized_static_fields == null) {
714 PartialContainer.HasStaticFieldInitializer = true;
715 initialized_static_fields = new ArrayList (4);
718 initialized_static_fields.Add (expression);
720 if (initialized_fields == null)
721 initialized_fields = new ArrayList (4);
723 initialized_fields.Add (expression);
727 public void ResolveFieldInitializers (EmitContext ec)
729 // Field initializers are tricky for partial classes. They have to
730 // share same costructor (block) but they have they own resolve scope.
731 DeclSpace orig = ec.DeclContainer;
733 if (partial_parts != null) {
734 foreach (TypeContainer part in partial_parts) {
735 ec.DeclContainer = part;
736 part.DoResolveFieldInitializers (ec);
739 ec.DeclContainer = PartialContainer;
740 DoResolveFieldInitializers (ec);
741 ec.DeclContainer = orig;
744 void DoResolveFieldInitializers (EmitContext ec)
747 if (initialized_static_fields == null)
750 bool has_complex_initializer = false;
751 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
752 foreach (FieldInitializer fi in initialized_static_fields) {
753 fi.ResolveStatement (ec);
754 if (!fi.IsComplexInitializer)
757 has_complex_initializer = true;
760 // Need special check to not optimize code like this
761 // static int a = b = 5;
763 if (!has_complex_initializer && RootContext.Optimize) {
764 for (int i = 0; i < initialized_static_fields.Count; ++i) {
765 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
766 if (fi.IsDefaultInitializer) {
767 initialized_static_fields.RemoveAt (i);
777 if (initialized_fields == null)
780 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
781 for (int i = 0; i < initialized_fields.Count; ++i) {
782 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
783 fi.ResolveStatement (ec);
784 if (fi.IsDefaultInitializer && RootContext.Optimize) {
785 // Field is re-initialized to its default value => removed
786 initialized_fields.RemoveAt (i);
794 // Emits the instance field initializers
796 public bool EmitFieldInitializers (EmitContext ec)
798 if (partial_parts != null) {
799 foreach (TypeContainer part in partial_parts)
800 part.EmitFieldInitializers (ec);
806 fields = initialized_static_fields;
808 fields = initialized_fields;
814 foreach (FieldInitializer f in fields) {
815 f.EmitStatement (ec);
820 public override string DocComment {
832 public PendingImplementation PendingImplementations {
833 get { return pending; }
836 public override bool GetClsCompliantAttributeValue ()
838 if (PartialContainer != this)
839 return PartialContainer.GetClsCompliantAttributeValue ();
841 return base.GetClsCompliantAttributeValue ();
844 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
846 // FIXME: get rid of partial_parts and store lists of bases of each part here
847 // assumed, not verified: 'part' is in 'partial_parts'
848 ((TypeContainer) part).Bases = bases;
851 TypeExpr[] GetNormalBases (out TypeExpr base_class)
857 int count = Bases.Count;
860 if (Kind == Kind.Class){
861 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
867 if (!name.IsInterface) {
868 // base_class could be a class, struct, enum, delegate.
869 // This is validated in GetClassBases.
875 TypeExpr [] ifaces = new TypeExpr [count-start];
877 for (i = start, j = 0; i < count; i++, j++){
878 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
879 if (resolved == null) {
883 ifaces [j] = resolved;
886 return ifaces.Length == 0 ? null : ifaces;
890 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
892 ArrayList ifaces = new ArrayList (0);
893 if (iface_exprs != null)
894 ifaces.AddRange (iface_exprs);
896 foreach (TypeContainer part in partial_parts) {
897 TypeExpr new_base_class;
898 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
899 if (new_base_class != TypeManager.system_object_expr) {
900 if (base_class == TypeManager.system_object_expr)
901 base_class = new_base_class;
903 if (new_base_class != null && !new_base_class.Equals (base_class)) {
904 Report.SymbolRelatedToPreviousError (base_class.Location, "");
905 Report.Error (263, part.Location,
906 "Partial declarations of `{0}' must not specify different base classes",
907 part.GetSignatureForError ());
914 if (new_ifaces == null)
917 foreach (TypeExpr iface in new_ifaces) {
918 if (ifaces.Contains (iface))
925 if (ifaces.Count == 0)
928 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
932 /// This function computes the Base class and also the
933 /// list of interfaces that the class or struct @c implements.
935 /// The return value is an array (might be null) of
936 /// interfaces implemented (as Types).
938 /// The @base_class argument is set to the base object or null
939 /// if this is `System.Object'.
941 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
943 TypeExpr[] ifaces = GetNormalBases (out base_class);
948 int count = ifaces.Length;
950 for (int i = 0; i < count; i++) {
951 TypeExpr iface = (TypeExpr) ifaces [i];
953 if (!iface.IsInterface) {
954 if (Kind != Kind.Class) {
955 // TODO: location of symbol related ....
956 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
958 else if (base_class != null)
959 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
960 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
962 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
963 GetSignatureForError (), iface.GetSignatureForError ());
968 for (int x = 0; x < i; x++) {
969 if (iface.Equals (ifaces [x])) {
970 Report.Error (528, Location,
971 "`{0}' is already listed in " +
972 "interface list", iface.GetSignatureForError ());
977 if ((Kind == Kind.Interface) &&
978 !iface.AsAccessible (this)) {
979 Report.Error (61, Location,
980 "Inconsistent accessibility: base " +
981 "interface `{0}' is less accessible " +
982 "than interface `{1}'", iface.GetSignatureForError (),
990 bool CheckGenericInterfaces (Type[] ifaces)
993 ArrayList already_checked = new ArrayList ();
995 for (int i = 0; i < ifaces.Length; i++) {
996 Type iface = ifaces [i];
997 foreach (Type t in already_checked) {
1001 Type[] inferred = new Type [CountTypeParameters];
1002 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
1005 Report.Error (695, Location,
1006 "`{0}' cannot implement both `{1}' and `{2}' " +
1007 "because they may unify for some type parameter substitutions",
1008 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1009 TypeManager.CSharpName (t));
1013 already_checked.Add (iface);
1022 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1024 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1027 bool CreateTypeBuilder ()
1030 Type default_parent = null;
1031 if (Kind == Kind.Struct)
1032 default_parent = TypeManager.value_type;
1033 else if (Kind == Kind.Enum)
1034 default_parent = TypeManager.enum_type;
1037 if (TypeManager.NamespaceClash (Name, Location)) {
1041 ModuleBuilder builder = CodeGen.Module.Builder;
1042 TypeBuilder = builder.DefineType (
1043 Name, TypeAttr, default_parent, null);
1045 TypeBuilder builder = Parent.TypeBuilder;
1047 TypeBuilder = builder.DefineNestedType (
1048 Basename, TypeAttr, default_parent, null);
1050 } catch (ArgumentException) {
1051 Report.RuntimeMissingSupport (Location, "static classes");
1055 TypeManager.AddUserType (this);
1059 string[] param_names = new string [TypeParameters.Length];
1060 for (int i = 0; i < TypeParameters.Length; i++)
1061 param_names [i] = TypeParameters [i].Name;
1063 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1065 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1066 for (int i = offset; i < gen_params.Length; i++)
1067 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1074 bool DefineBaseTypes ()
1076 iface_exprs = GetClassBases (out base_type);
1077 if (partial_parts != null) {
1078 iface_exprs = GetNormalPartialBases (ref base_type);
1082 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1083 // which in turn should have called DefineType()s on base types if necessary.
1085 // None of the code below should trigger DefineType()s on classes that we depend on.
1086 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1088 // Let's do it as soon as possible, since code below can call DefineType() on classes
1089 // that depend on us to be populated before they are.
1091 if (!(this is CompilerGeneratedClass))
1092 RootContext.RegisterOrder (this);
1094 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1095 Report.Error (698, base_type.Location,
1096 "A generic type cannot derive from `{0}' because it is an attribute class",
1101 if (!CheckRecursiveDefinition (this))
1104 if (base_type != null && base_type.Type != null) {
1105 TypeBuilder.SetParent (base_type.Type);
1107 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1108 if (obsolete_attr != null && !IsInObsoleteScope)
1109 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1112 // add interfaces that were not added at type creation
1113 if (iface_exprs != null) {
1114 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1118 foreach (Type itype in ifaces)
1119 TypeBuilder.AddInterfaceImplementation (itype);
1121 foreach (TypeExpr ie in iface_exprs) {
1122 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1123 if ((oa != null) && !IsInObsoleteScope)
1124 AttributeTester.Report_ObsoleteMessage (
1125 oa, ie.GetSignatureForError (), Location);
1128 if (!CheckGenericInterfaces (ifaces))
1131 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1138 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1140 public TypeBuilder CreateType ()
1142 if (TypeBuilder != null)
1148 if (!CreateTypeBuilder ()) {
1153 if (partial_parts != null) {
1154 foreach (TypeContainer part in partial_parts)
1155 part.TypeBuilder = TypeBuilder;
1158 if (Types != null) {
1159 foreach (TypeContainer tc in Types) {
1160 if (tc.CreateType () == null) {
1172 public override TypeBuilder DefineType ()
1179 type_defined = true;
1181 if (CreateType () == null) {
1186 if (!DefineBaseTypes ()) {
1191 if (!(this is CompilerGeneratedClass)) {
1192 if (!ResolveMembers ()) {
1198 if (!DefineNestedTypes ()) {
1206 public bool ResolveMembers ()
1208 if (members_resolved)
1209 return members_resolved_ok;
1211 members_resolved_ok = DoResolveMembers ();
1212 members_resolved = true;
1214 return members_resolved_ok;
1217 protected virtual bool DoResolveMembers ()
1219 if (methods != null) {
1220 foreach (Method method in methods) {
1221 if (!method.ResolveMembers ())
1226 if (instance_constructors != null) {
1227 foreach (Constructor c in instance_constructors) {
1228 if (!c.ResolveMembers ())
1233 if (default_static_constructor != null) {
1234 if (!default_static_constructor.ResolveMembers ())
1238 if (operators != null) {
1239 foreach (Operator o in operators) {
1240 if (!o.ResolveMembers ())
1245 if (properties != null) {
1246 foreach (PropertyBase p in properties) {
1247 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1249 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1254 if (indexers != null) {
1255 foreach (PropertyBase p in indexers) {
1256 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1258 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1263 if (events != null) {
1264 foreach (Event e in events) {
1265 if (!e.Add.ResolveMembers ())
1267 if (!e.Remove.ResolveMembers ())
1272 if (compiler_generated != null) {
1273 foreach (CompilerGeneratedClass c in compiler_generated) {
1274 if (c.DefineType () == null)
1282 Constraints [] constraints;
1283 public override void SetParameterInfo (ArrayList constraints_list)
1285 if (PartialContainer == this) {
1286 base.SetParameterInfo (constraints_list);
1290 if (constraints_list == null)
1293 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1295 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1296 for (int i = 0; i < constraints.Length; i++) {
1297 foreach (Constraints constraint in constraints_list) {
1298 if (constraint.TypeParameter == current_params [i].Name) {
1299 constraints [i] = constraint;
1306 bool UpdateTypeParameterConstraints ()
1308 if (constraints == null)
1311 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1312 for (int i = 0; i < current_params.Length; i++) {
1313 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1314 Report.SymbolRelatedToPreviousError (Location, "");
1315 Report.Error (265, PartialContainer.Location,
1316 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1317 PartialContainer.GetSignatureForError (), current_params [i].Name);
1325 public bool ResolveType ()
1327 if (!DoResolveType ())
1330 if (compiler_generated != null) {
1331 foreach (CompilerGeneratedClass c in compiler_generated)
1332 if (!c.ResolveType ())
1339 protected virtual bool DoResolveType ()
1341 if ((base_type != null) &&
1342 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1350 if (PartialContainer != this)
1351 throw new InternalErrorException ();
1353 TypeExpr current_type = null;
1355 foreach (TypeParameter type_param in CurrentTypeParameters) {
1356 if (!type_param.Resolve (this)) {
1362 if (partial_parts != null) {
1363 foreach (TypeContainer part in partial_parts) {
1364 if (!part.UpdateTypeParameterConstraints ()) {
1371 foreach (TypeParameter type_param in TypeParameters) {
1372 if (!type_param.DefineType (this)) {
1378 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1380 foreach (TypeParameter type_param in TypeParameters)
1381 if (!type_param.CheckDependencies ()) {
1386 if (current_type != null) {
1387 current_type = current_type.ResolveAsTypeTerminal (this, false);
1388 if (current_type == null) {
1393 CurrentType = current_type.Type;
1399 protected virtual bool DefineNestedTypes ()
1401 if (Types != null) {
1402 foreach (TypeContainer tc in Types)
1403 if (tc.DefineType () == null)
1407 if (Delegates != null) {
1408 foreach (Delegate d in Delegates)
1409 if (d.DefineType () == null)
1416 TypeContainer InTransit;
1418 protected bool CheckRecursiveDefinition (TypeContainer tc)
1420 if (InTransit != null) {
1421 Report.SymbolRelatedToPreviousError (this);
1422 if (this is Interface)
1424 529, tc.Location, "Inherited interface `{0}' causes a " +
1425 "cycle in the interface hierarchy of `{1}'",
1426 GetSignatureForError (), tc.GetSignatureForError ());
1429 146, tc.Location, "Circular base class dependency " +
1430 "involving `{0}' and `{1}'",
1431 tc.GetSignatureForError (), GetSignatureForError ());
1437 if (base_type != null && base_type.Type != null) {
1438 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1439 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1440 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1444 if (iface_exprs != null) {
1445 foreach (TypeExpr iface in iface_exprs) {
1446 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1447 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1448 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1453 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1460 public static void Error_KeywordNotAllowed (Location loc)
1462 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1466 /// Populates our TypeBuilder with fields and methods
1468 public override bool DefineMembers ()
1470 if (members_defined)
1471 return members_defined_ok;
1473 if (!base.DefineMembers ())
1476 members_defined_ok = DoDefineMembers ();
1477 members_defined = true;
1479 return members_defined_ok;
1482 protected virtual bool DoDefineMembers ()
1484 if (iface_exprs != null) {
1485 foreach (TypeExpr iface in iface_exprs) {
1486 ConstructedType ct = iface as ConstructedType;
1487 if ((ct != null) && !ct.CheckConstraints (this))
1492 if (base_type != null) {
1493 ConstructedType ct = base_type as ConstructedType;
1494 if ((ct != null) && !ct.CheckConstraints (this))
1497 member_cache = new MemberCache (base_type.Type, this);
1498 } else if (Kind == Kind.Interface) {
1499 member_cache = new MemberCache (null, this);
1500 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1501 for (int i = 0; i < ifaces.Length; ++i)
1502 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1504 member_cache = new MemberCache (null, this);
1508 foreach (TypeContainer tc in types)
1509 member_cache.AddNestedType (tc);
1511 if (delegates != null)
1512 foreach (Delegate d in delegates)
1513 member_cache.AddNestedType (d);
1515 if (partial_parts != null) {
1516 foreach (TypeContainer part in partial_parts)
1517 part.member_cache = member_cache;
1521 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1522 if (conflict_symbol == null) {
1523 if ((ModFlags & Modifiers.NEW) != 0)
1524 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1526 if ((ModFlags & Modifiers.NEW) == 0) {
1527 Report.SymbolRelatedToPreviousError (conflict_symbol);
1528 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1529 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1534 DefineContainerMembers (constants);
1535 DefineContainerMembers (fields);
1537 if (Kind == Kind.Struct || Kind == Kind.Class) {
1538 pending = PendingImplementation.GetPendingImplementations (this);
1542 // Constructors are not in the defined_names array
1544 DefineContainerMembers (instance_constructors);
1546 DefineContainerMembers (events);
1547 DefineContainerMembers (ordered_explicit_member_list);
1548 DefineContainerMembers (ordered_member_list);
1550 DefineContainerMembers (operators);
1551 DefineContainerMembers (delegates);
1553 ComputeIndexerName();
1554 CheckEqualsAndGetHashCode();
1556 if (CurrentType != null) {
1557 GenericType = CurrentType;
1562 // FIXME: This hack is needed because member cache does not work
1563 // with generic types, we rely on runtime to inflate dynamic types.
1564 // TODO: This hack requires member cache refactoring to be removed
1566 if (TypeBuilder.IsGenericType)
1567 member_cache = new MemberCache (this);
1573 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1576 mcal.DefineContainerMembers ();
1579 protected virtual void ComputeIndexerName ()
1581 if (indexers == null)
1584 string class_indexer_name = null;
1587 // If there's both an explicit and an implicit interface implementation, the
1588 // explicit one actually implements the interface while the other one is just
1589 // a normal indexer. See bug #37714.
1592 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1593 foreach (Indexer i in indexers) {
1594 if (i.InterfaceType != null) {
1595 if (seen_normal_indexers)
1596 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1600 seen_normal_indexers = true;
1602 if (class_indexer_name == null) {
1603 class_indexer_name = i.ShortName;
1607 if (i.ShortName != class_indexer_name)
1608 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");
1611 if (class_indexer_name != null)
1612 indexer_name = class_indexer_name;
1615 protected virtual void EmitIndexerName ()
1617 if (!seen_normal_indexers)
1620 if (TypeManager.default_member_ctor == null) {
1621 if (TypeManager.default_member_type == null) {
1622 TypeManager.default_member_type = TypeManager.CoreLookupType (
1623 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1625 if (TypeManager.default_member_type == null)
1629 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1630 TypeManager.default_member_type, Location, TypeManager.string_type);
1632 if (TypeManager.default_member_ctor == null)
1636 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1637 TypeBuilder.SetCustomAttribute (cb);
1640 protected virtual void CheckEqualsAndGetHashCode ()
1642 if (methods == null)
1645 if (HasEquals && !HasGetHashCode) {
1646 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1650 public override bool Define ()
1652 CheckProtectedModifier ();
1654 if (compiler_generated != null) {
1655 foreach (CompilerGeneratedClass c in compiler_generated) {
1664 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1666 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1670 /// This function is based by a delegate to the FindMembers routine
1672 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1678 /// This filter is used by FindMembers, and we just keep
1679 /// a global for the filter to `AlwaysAccept'
1681 static MemberFilter accepting_filter;
1684 static TypeContainer ()
1686 accepting_filter = new MemberFilter (AlwaysAccept);
1689 public MethodInfo[] GetMethods ()
1691 ArrayList members = new ArrayList ();
1695 if (methods != null) {
1696 int len = methods.Count;
1697 for (int i = 0; i < len; i++) {
1698 Method m = (Method) methods [i];
1700 members.Add (m.MethodBuilder);
1704 if (operators != null) {
1705 int len = operators.Count;
1706 for (int i = 0; i < len; i++) {
1707 Operator o = (Operator) operators [i];
1709 members.Add (o.MethodBuilder);
1713 if (properties != null) {
1714 int len = properties.Count;
1715 for (int i = 0; i < len; i++) {
1716 Property p = (Property) properties [i];
1718 if (p.GetBuilder != null)
1719 members.Add (p.GetBuilder);
1720 if (p.SetBuilder != null)
1721 members.Add (p.SetBuilder);
1725 if (indexers != null) {
1726 int len = indexers.Count;
1727 for (int i = 0; i < len; i++) {
1728 Indexer ix = (Indexer) indexers [i];
1730 if (ix.GetBuilder != null)
1731 members.Add (ix.GetBuilder);
1732 if (ix.SetBuilder != null)
1733 members.Add (ix.SetBuilder);
1737 if (events != null) {
1738 int len = events.Count;
1739 for (int i = 0; i < len; i++) {
1740 Event e = (Event) events [i];
1742 if (e.AddBuilder != null)
1743 members.Add (e.AddBuilder);
1744 if (e.RemoveBuilder != null)
1745 members.Add (e.RemoveBuilder);
1749 MethodInfo[] retMethods = new MethodInfo [members.Count];
1750 members.CopyTo (retMethods, 0);
1754 // Indicated whether container has StructLayout attribute set Explicit
1755 public bool HasExplicitLayout {
1756 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1757 set { caching_flags |= Flags.HasExplicitLayout; }
1761 // Return the nested type with name @name. Ensures that the nested type
1762 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1764 public Type FindNestedType (string name)
1766 if (PartialContainer != this)
1767 throw new InternalErrorException ("should not happen");
1769 ArrayList [] lists = { types, delegates };
1771 for (int j = 0; j < lists.Length; ++j) {
1772 ArrayList list = lists [j];
1776 int len = list.Count;
1777 for (int i = 0; i < len; ++i) {
1778 DeclSpace ds = (DeclSpace) list [i];
1779 if (ds.Basename == name) {
1780 return ds.DefineType ();
1788 private void FindMembers_NestedTypes (int modflags,
1789 BindingFlags bf, MemberFilter filter, object criteria,
1790 ref ArrayList members)
1792 ArrayList [] lists = { types, delegates };
1794 for (int j = 0; j < lists.Length; ++j) {
1795 ArrayList list = lists [j];
1799 int len = list.Count;
1800 for (int i = 0; i < len; i++) {
1801 DeclSpace ds = (DeclSpace) list [i];
1803 if ((ds.ModFlags & modflags) == 0)
1806 TypeBuilder tb = ds.TypeBuilder;
1808 if (!(criteria is string) || ds.Basename.Equals (criteria))
1809 tb = ds.DefineType ();
1812 if (tb != null && (filter (tb, criteria) == true)) {
1813 if (members == null)
1814 members = new ArrayList ();
1823 /// This method returns the members of this type just like Type.FindMembers would
1824 /// Only, we need to use this for types which are _being_ defined because MS'
1825 /// implementation can't take care of that.
1828 // FIXME: return an empty static array instead of null, that cleans up
1829 // some code and is consistent with some coding conventions I just found
1833 // Notice that in various cases we check if our field is non-null,
1834 // something that would normally mean that there was a bug elsewhere.
1836 // The problem happens while we are defining p-invoke methods, as those
1837 // will trigger a FindMembers, but this happens before things are defined
1839 // Since the whole process is a no-op, it is fine to check for null here.
1841 // TODO: This approach will be one day completely removed, it's already
1842 // used at few places only
1845 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1846 MemberFilter filter, object criteria)
1848 ArrayList members = null;
1851 if ((bf & BindingFlags.Public) != 0)
1852 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1854 if ((bf & BindingFlags.NonPublic) != 0)
1855 modflags |= Modifiers.PRIVATE;
1857 int static_mask = 0, static_flags = 0;
1858 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1859 case BindingFlags.Static:
1860 static_mask = static_flags = Modifiers.STATIC;
1863 case BindingFlags.Instance:
1864 static_mask = Modifiers.STATIC;
1869 static_mask = static_flags = 0;
1873 Timer.StartTimer (TimerType.TcFindMembers);
1876 filter = accepting_filter;
1878 if ((mt & MemberTypes.Field) != 0) {
1879 if (fields != null) {
1880 int len = fields.Count;
1881 for (int i = 0; i < len; i++) {
1882 FieldBase f = (FieldBase) fields [i];
1884 if ((f.ModFlags & modflags) == 0)
1886 if ((f.ModFlags & static_mask) != static_flags)
1889 FieldBuilder fb = f.FieldBuilder;
1890 if (fb != null && filter (fb, criteria) == true) {
1891 if (members == null)
1892 members = new ArrayList ();
1899 if (constants != null) {
1900 int len = constants.Count;
1901 for (int i = 0; i < len; i++) {
1902 Const con = (Const) constants [i];
1904 if ((con.ModFlags & modflags) == 0)
1906 if ((con.ModFlags & static_mask) != static_flags)
1909 FieldBuilder fb = con.FieldBuilder;
1912 fb = con.FieldBuilder;
1914 if (fb != null && filter (fb, criteria) == true) {
1915 if (members == null)
1916 members = new ArrayList ();
1924 if ((mt & MemberTypes.Method) != 0) {
1925 if (methods != null) {
1926 int len = methods.Count;
1927 for (int i = 0; i < len; i++) {
1928 Method m = (Method) methods [i];
1930 if ((m.ModFlags & modflags) == 0)
1932 if ((m.ModFlags & static_mask) != static_flags)
1935 MethodBuilder mb = m.MethodBuilder;
1937 if (mb != null && filter (mb, criteria) == true) {
1938 if (members == null)
1939 members = new ArrayList ();
1946 if (operators != null) {
1947 int len = operators.Count;
1948 for (int i = 0; i < len; i++) {
1949 Operator o = (Operator) operators [i];
1951 if ((o.ModFlags & modflags) == 0)
1953 if ((o.ModFlags & static_mask) != static_flags)
1956 MethodBuilder ob = o.MethodBuilder;
1957 if (ob != null && filter (ob, criteria) == true) {
1958 if (members == null)
1959 members = new ArrayList ();
1966 if (events != null) {
1967 foreach (Event e in events) {
1968 if ((e.ModFlags & modflags) == 0)
1970 if ((e.ModFlags & static_mask) != static_flags)
1973 MethodBuilder b = e.AddBuilder;
1974 if (b != null && filter (b, criteria)) {
1975 if (members == null)
1976 members = new ArrayList (4);
1981 b = e.RemoveBuilder;
1982 if (b != null && filter (b, criteria)) {
1983 if (members == null)
1984 members = new ArrayList (4);
1991 if (properties != null) {
1992 int len = properties.Count;
1993 for (int i = 0; i < len; i++) {
1994 Property p = (Property) properties [i];
1996 if ((p.ModFlags & modflags) == 0)
1998 if ((p.ModFlags & static_mask) != static_flags)
2004 if (b != null && filter (b, criteria) == true) {
2005 if (members == null)
2006 members = new ArrayList ();
2012 if (b != null && filter (b, criteria) == true) {
2013 if (members == null)
2014 members = new ArrayList ();
2021 if (indexers != null) {
2022 int len = indexers.Count;
2023 for (int i = 0; i < len; i++) {
2024 Indexer ix = (Indexer) indexers [i];
2026 if ((ix.ModFlags & modflags) == 0)
2028 if ((ix.ModFlags & static_mask) != static_flags)
2034 if (b != null && filter (b, criteria) == true) {
2035 if (members == null)
2036 members = new ArrayList ();
2042 if (b != null && filter (b, criteria) == true) {
2043 if (members == null)
2044 members = new ArrayList ();
2052 if ((mt & MemberTypes.Event) != 0) {
2053 if (events != null) {
2054 int len = events.Count;
2055 for (int i = 0; i < len; i++) {
2056 Event e = (Event) events [i];
2058 if ((e.ModFlags & modflags) == 0)
2060 if ((e.ModFlags & static_mask) != static_flags)
2063 MemberInfo eb = e.EventBuilder;
2064 if (eb != null && filter (eb, criteria) == true) {
2065 if (members == null)
2066 members = new ArrayList ();
2068 members.Add (e.EventBuilder);
2074 if ((mt & MemberTypes.Property) != 0){
2075 if (properties != null) {
2076 int len = properties.Count;
2077 for (int i = 0; i < len; i++) {
2078 Property p = (Property) properties [i];
2080 if ((p.ModFlags & modflags) == 0)
2082 if ((p.ModFlags & static_mask) != static_flags)
2085 MemberInfo pb = p.PropertyBuilder;
2086 if (pb != null && filter (pb, criteria) == true) {
2087 if (members == null)
2088 members = new ArrayList ();
2090 members.Add (p.PropertyBuilder);
2095 if (indexers != null) {
2096 int len = indexers.Count;
2097 for (int i = 0; i < len; i++) {
2098 Indexer ix = (Indexer) indexers [i];
2100 if ((ix.ModFlags & modflags) == 0)
2102 if ((ix.ModFlags & static_mask) != static_flags)
2105 MemberInfo ib = ix.PropertyBuilder;
2106 if (ib != null && filter (ib, criteria) == true) {
2107 if (members == null)
2108 members = new ArrayList ();
2110 members.Add (ix.PropertyBuilder);
2116 if ((mt & MemberTypes.NestedType) != 0)
2117 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2119 if ((mt & MemberTypes.Constructor) != 0){
2120 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2121 int len = instance_constructors.Count;
2122 for (int i = 0; i < len; i++) {
2123 Constructor c = (Constructor) instance_constructors [i];
2125 ConstructorBuilder cb = c.ConstructorBuilder;
2126 if (cb != null && filter (cb, criteria) == true) {
2127 if (members == null)
2128 members = new ArrayList ();
2135 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2136 ConstructorBuilder cb =
2137 default_static_constructor.ConstructorBuilder;
2139 if (cb != null && filter (cb, criteria) == true) {
2140 if (members == null)
2141 members = new ArrayList ();
2149 // Lookup members in base if requested.
2151 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2152 if (TypeBuilder.BaseType != null) {
2153 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2154 if (list.Count > 0) {
2155 if (members == null)
2156 members = new ArrayList ();
2158 members.AddRange (list);
2163 Timer.StopTimer (TimerType.TcFindMembers);
2165 if (members == null)
2166 return MemberList.Empty;
2168 return new MemberList (members);
2171 public override MemberCache MemberCache {
2173 return member_cache;
2177 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2178 MemberFilter filter, object criteria)
2180 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2183 return ds.FindMembers (mt, bf, filter, criteria);
2185 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2189 /// Emits the values for the constants
2191 public void EmitConstants ()
2193 if (constants != null)
2194 foreach (Const con in constants)
2199 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2204 foreach (MemberCore mc in al) {
2205 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2208 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2209 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2214 public virtual void VerifyMembers ()
2217 // Check for internal or private fields that were never assigned
2219 if (Report.WarningLevel >= 3) {
2220 CheckMemberUsage (properties, "property");
2221 CheckMemberUsage (methods, "method");
2222 CheckMemberUsage (constants, "constant");
2224 if (fields != null){
2225 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2226 foreach (FieldBase f in fields) {
2227 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2228 if (is_type_exposed)
2231 f.SetMemberIsUsed ();
2235 if ((f.caching_flags & Flags.IsAssigned) == 0)
2236 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2239 const int error_code = 414;
2241 const int error_code = 169;
2243 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2244 f.GetSignatureForError ());
2250 // Only report 649 on level 4
2252 if (Report.WarningLevel < 4)
2255 if ((f.caching_flags & Flags.IsAssigned) != 0)
2258 Constant c = New.Constantify (f.Type.Type);
2259 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2260 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2266 // TODO: move to ClassOrStruct
2267 void EmitConstructors ()
2269 if (instance_constructors == null)
2272 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2273 bool has_compliant_args = false;
2275 foreach (Constructor c in instance_constructors) {
2279 catch (Exception e) {
2280 throw new InternalErrorException (c, e);
2283 if (has_compliant_args)
2286 has_compliant_args = c.HasCompliantArgs;
2288 if (!has_compliant_args)
2289 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2291 foreach (Constructor c in instance_constructors) {
2295 catch (Exception e) {
2296 throw new InternalErrorException (c, e);
2303 /// Emits the code, this step is performed after all
2304 /// the types, enumerations, constructors
2306 public virtual void EmitType ()
2308 if (OptAttributes != null)
2309 OptAttributes.Emit ();
2313 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2314 for (int i = offset; i < gen_params.Length; i++)
2315 CurrentTypeParameters [i - offset].Emit ();
2320 // Structs with no fields need to have at least one byte.
2321 // The right thing would be to set the PackingSize in a DefineType
2322 // but there are no functions that allow interfaces *and* the size to
2326 if (Kind == Kind.Struct && first_nonstatic_field == null){
2327 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2328 FieldAttributes.Private);
2330 if (HasExplicitLayout){
2331 object [] ctor_args = new object [] { 0 };
2333 if (TypeManager.field_offset_attribute_ctor == null) {
2335 if (TypeManager.field_offset_attribute_type == null) {
2336 TypeManager.field_offset_attribute_type = TypeManager.CoreLookupType (
2337 "System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, true);
2340 TypeManager.field_offset_attribute_ctor = TypeManager.GetPredefinedConstructor (
2341 TypeManager.field_offset_attribute_type, Location, TypeManager.int32_type);
2344 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2345 TypeManager.field_offset_attribute_ctor, ctor_args);
2346 fb.SetCustomAttribute (cba);
2352 EmitConstructors ();
2354 // Can not continue if constants are broken
2356 if (Report.Errors > 0)
2359 if (default_static_constructor != null)
2360 default_static_constructor.Emit ();
2362 if (methods != null){
2363 for (int i = 0; i < methods.Count; ++i)
2364 ((Method)methods[i]).Emit ();
2367 if (operators != null)
2368 foreach (Operator o in operators)
2371 if (properties != null)
2372 foreach (Property p in properties)
2375 if (indexers != null) {
2376 foreach (Indexer indx in indexers)
2382 foreach (FieldBase f in fields)
2385 if (events != null){
2386 foreach (Event e in Events)
2390 if (delegates != null) {
2391 foreach (Delegate d in Delegates) {
2396 if (pending != null)
2397 if (pending.VerifyPendingMethods ())
2400 if (Report.Errors > 0)
2403 if (compiler_generated != null) {
2404 foreach (CompilerGeneratedClass c in compiler_generated) {
2405 if (!c.DefineMembers ())
2406 throw new InternalErrorException ();
2408 foreach (CompilerGeneratedClass c in compiler_generated)
2413 public override void CloseType ()
2415 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2419 caching_flags |= Flags.CloseTypeCreated;
2420 TypeBuilder.CreateType ();
2421 } catch (TypeLoadException){
2423 // This is fine, the code still created the type
2425 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2426 // Console.WriteLine (e.Message);
2427 } catch (Exception e) {
2428 throw new InternalErrorException (this, e);
2432 foreach (TypeContainer tc in Types)
2433 if (tc.Kind == Kind.Struct)
2436 foreach (TypeContainer tc in Types)
2437 if (tc.Kind != Kind.Struct)
2441 if (Delegates != null)
2442 foreach (Delegate d in Delegates)
2445 if (CompilerGenerated != null)
2446 foreach (CompilerGeneratedClass c in CompilerGenerated)
2453 initialized_fields = null;
2454 initialized_static_fields = null;
2456 ordered_explicit_member_list = null;
2457 ordered_member_list = null;
2462 compiler_generated = null;
2463 default_constructor = null;
2464 default_static_constructor = null;
2466 OptAttributes = null;
2469 member_cache = null;
2473 // Performs the validation on a Method's modifiers (properties have
2474 // the same properties).
2476 public bool MethodModifiersValid (MemberCore mc)
2478 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2479 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2480 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2482 int flags = mc.ModFlags;
2485 // At most one of static, virtual or override
2487 if ((flags & Modifiers.STATIC) != 0){
2488 if ((flags & vao) != 0){
2489 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2490 mc.GetSignatureForError ());
2495 if (Kind == Kind.Struct){
2496 if ((flags & va) != 0){
2497 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2502 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2503 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2504 mc.GetSignatureForError ());
2509 // If the declaration includes the abstract modifier, then the
2510 // declaration does not include static, virtual or extern
2512 if ((flags & Modifiers.ABSTRACT) != 0){
2513 if ((flags & Modifiers.EXTERN) != 0){
2515 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2519 if ((flags & Modifiers.SEALED) != 0) {
2520 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2524 if ((flags & Modifiers.VIRTUAL) != 0){
2525 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2529 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2530 Report.SymbolRelatedToPreviousError (this);
2531 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2532 mc.GetSignatureForError (), GetSignatureForError ());
2537 if ((flags & Modifiers.PRIVATE) != 0){
2538 if ((flags & vao) != 0){
2539 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2544 if ((flags & Modifiers.SEALED) != 0){
2545 if ((flags & Modifiers.OVERRIDE) == 0){
2546 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2554 public Constructor DefaultStaticConstructor {
2555 get { return default_static_constructor; }
2558 protected override bool VerifyClsCompliance ()
2560 if (!base.VerifyClsCompliance ())
2565 Type base_type = TypeBuilder.BaseType;
2566 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2567 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2574 /// Checks whether container name is CLS Compliant
2576 void VerifyClsName ()
2578 Hashtable base_members = base_cache == null ?
2580 base_cache.GetPublicMembers ();
2581 Hashtable this_members = new Hashtable ();
2583 foreach (DictionaryEntry entry in defined_names) {
2584 MemberCore mc = (MemberCore)entry.Value;
2585 if (!mc.IsClsComplianceRequired ())
2588 string name = (string) entry.Key;
2589 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2591 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2592 object found = base_members [lcase];
2593 if (found == null) {
2594 found = this_members [lcase];
2595 if (found == null) {
2596 this_members.Add (lcase, mc);
2601 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2604 if (found is MemberInfo) {
2605 if (basename == ((MemberInfo) found).Name)
2607 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2609 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2612 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2614 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2621 /// Performs checks for an explicit interface implementation. First it
2622 /// checks whether the `interface_type' is a base inteface implementation.
2623 /// Then it checks whether `name' exists in the interface type.
2625 public bool VerifyImplements (InterfaceMemberBase mb)
2627 if (ifaces != null) {
2628 foreach (Type t in ifaces){
2629 if (TypeManager.IsEqual (t, mb.InterfaceType))
2634 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2635 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2636 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2640 public override Type LookupAnyGeneric (string typeName)
2642 if (types != null) {
2643 foreach (TypeContainer tc in types) {
2647 int pos = tc.Basename.LastIndexOf ('`');
2648 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2649 return tc.TypeBuilder;
2653 return base.LookupAnyGeneric (typeName);
2656 public void Mark_HasEquals ()
2658 cached_method |= CachedMethods.Equals;
2661 public void Mark_HasGetHashCode ()
2663 cached_method |= CachedMethods.GetHashCode;
2667 /// Method container contains Equals method
2669 public bool HasEquals {
2671 return (cached_method & CachedMethods.Equals) != 0;
2676 /// Method container contains GetHashCode method
2678 public bool HasGetHashCode {
2680 return (cached_method & CachedMethods.GetHashCode) != 0;
2684 public bool HasStaticFieldInitializer {
2686 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2690 cached_method |= CachedMethods.HasStaticFieldInitializer;
2692 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2700 string IMemberContainer.Name {
2706 Type IMemberContainer.Type {
2712 bool IMemberContainer.IsInterface {
2714 return Kind == Kind.Interface;
2718 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2720 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2722 if (GenericType != null)
2723 return TypeManager.FindMembers (GenericType, mt, new_bf,
2726 return FindMembers (mt, new_bf, null, null);
2730 // Generates xml doc comments (if any), and if required,
2731 // handle warning report.
2733 internal override void GenerateDocComment (DeclSpace ds)
2735 DocUtil.GenerateTypeDocComment (this, ds);
2738 public override string DocCommentHeader {
2739 get { return "T:"; }
2742 public MemberCache BaseCache {
2744 if (base_cache != null)
2746 if (TypeBuilder.BaseType != null)
2747 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2748 if (TypeBuilder.IsInterface)
2749 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2755 public abstract class ClassOrStruct : TypeContainer {
2756 ListDictionary declarative_security;
2758 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2759 MemberName name, Attributes attrs, Kind kind)
2760 : base (ns, parent, name, attrs, kind)
2764 protected override bool AddToContainer (MemberCore symbol, string name)
2766 if (name == MemberName.Name) {
2767 if (symbol is TypeParameter) {
2768 Report.Error (694, symbol.Location,
2769 "Type parameter `{0}' has same name as " +
2770 "containing type, or method", name);
2774 Report.SymbolRelatedToPreviousError (this);
2775 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2776 symbol.GetSignatureForError ());
2780 return base.AddToContainer (symbol, name);
2783 public override void VerifyMembers ()
2785 base.VerifyMembers ();
2787 if ((events != null) && Report.WarningLevel >= 3) {
2788 foreach (Event e in events){
2789 // Note: The event can be assigned from same class only, so we can report
2790 // this warning for all accessibility modes
2791 if ((e.caching_flags & Flags.IsUsed) == 0)
2792 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2797 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2799 if (a.IsValidSecurityAttribute ()) {
2800 if (declarative_security == null)
2801 declarative_security = new ListDictionary ();
2803 a.ExtractSecurityPermissionSet (declarative_security);
2807 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2808 HasExplicitLayout = true;
2811 base.ApplyAttributeBuilder (a, cb);
2815 /// Defines the default constructors
2817 protected void DefineDefaultConstructor (bool is_static)
2819 // The default instance constructor is public
2820 // If the class is abstract, the default constructor is protected
2821 // The default static constructor is private
2825 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2827 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2830 Constructor c = new Constructor (this, MemberName.Name, mods,
2831 Parameters.EmptyReadOnlyParameters,
2832 new GeneratedBaseInitializer (Location),
2836 c.Block = new ToplevelBlock (null, Location);
2839 public override bool Define ()
2841 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2842 DefineDefaultConstructor (true);
2844 if (default_static_constructor != null)
2845 default_static_constructor.Define ();
2847 return base.Define ();
2850 public override void Emit ()
2854 if (declarative_security != null) {
2855 foreach (DictionaryEntry de in declarative_security) {
2856 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2861 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2863 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2866 protected override TypeAttributes TypeAttr {
2868 if (default_static_constructor == null)
2869 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2871 return base.TypeAttr;
2877 // TODO: should be sealed
2878 public class Class : ClassOrStruct {
2879 const int AllowedModifiers =
2882 Modifiers.PROTECTED |
2883 Modifiers.INTERNAL |
2885 Modifiers.ABSTRACT |
2890 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2892 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2894 : base (ns, parent, name, attrs, Kind.Class)
2896 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2897 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2899 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2900 Report.FeatureIsNotAvailable (Location, "static classes");
2904 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2906 if (part.Name == "System.Object")
2907 Report.Error (537, part.Location,
2908 "The class System.Object cannot have a base class or implement an interface.");
2909 base.AddBasesForPart (part, bases);
2912 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2914 if (a.Type == TypeManager.attribute_usage_type) {
2915 if (!TypeManager.IsAttributeType (BaseType) &&
2916 TypeBuilder.FullName != "System.Attribute") {
2917 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2921 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2922 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2926 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2927 !attributes.Contains (TypeManager.guid_attr_type)) {
2928 a.Error_MissingGuidAttribute ();
2932 if (a.Type == TypeManager.extension_attribute_type) {
2933 a.Error_MisusedExtensionAttribute ();
2937 if (AttributeTester.IsAttributeExcluded (a.Type))
2940 base.ApplyAttributeBuilder (a, cb);
2943 public override AttributeTargets AttributeTargets {
2945 return AttributeTargets.Class;
2949 protected override void DefineContainerMembers (MemberCoreArrayList list)
2955 base.DefineContainerMembers (list);
2959 foreach (MemberCore m in list) {
2960 if (m is Operator) {
2961 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2965 if (m is Destructor) {
2966 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2970 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2971 m.CheckProtectedModifier ();
2976 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2980 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2983 if (m is Constructor) {
2984 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2988 Method method = m as Method;
2989 if (method != null && method.Parameters.HasExtensionMethodType) {
2990 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2994 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2997 base.DefineContainerMembers (list);
3000 public override TypeBuilder DefineType ()
3002 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3003 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3007 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3008 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3012 return base.DefineType ();
3015 protected override bool DoDefineMembers ()
3017 if (InstanceConstructors == null && !IsStatic)
3018 DefineDefaultConstructor (false);
3020 return base.DoDefineMembers ();
3023 public override void Emit ()
3028 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
3029 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
3033 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3035 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3037 if (base_class == null) {
3038 if (RootContext.StdLib)
3039 base_class = TypeManager.system_object_expr;
3040 else if (Name != "System.Object")
3041 base_class = TypeManager.system_object_expr;
3043 if (Kind == Kind.Class && base_class is TypeParameterExpr){
3045 689, base_class.Location,
3046 "Cannot derive from `{0}' because it is a type parameter",
3047 base_class.GetSignatureForError ());
3051 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
3052 Report.Error (1521, base_class.Location, "Invalid base type");
3056 if (base_class.IsSealed){
3057 Report.SymbolRelatedToPreviousError (base_class.Type);
3058 if (base_class.Type.IsAbstract) {
3059 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3060 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3062 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3063 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3068 if (!base_class.CanInheritFrom ()){
3069 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3070 GetSignatureForError (), base_class.GetSignatureForError ());
3074 if (!base_class.AsAccessible (this)) {
3075 Report.SymbolRelatedToPreviousError (base_class.Type);
3076 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3077 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3081 if (PartialContainer.IsStaticClass) {
3082 if (base_class.Type != TypeManager.object_type) {
3083 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3084 GetSignatureForError (), base_class.GetSignatureForError ());
3088 if (ifaces != null) {
3089 foreach (TypeExpr t in ifaces)
3090 Report.SymbolRelatedToPreviousError (t.Type);
3091 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
3098 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3099 /// Valid only for attribute classes.
3100 public bool IsExcluded ()
3102 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3103 return (caching_flags & Flags.Excluded) != 0;
3105 caching_flags &= ~Flags.Excluded_Undetected;
3107 if (OptAttributes == null)
3110 if (TypeManager.conditional_attribute_type == null)
3113 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3118 foreach (Attribute a in attrs) {
3119 string condition = a.GetConditionalAttributeValue ();
3120 if (RootContext.AllDefines.Contains (condition))
3124 caching_flags |= Flags.Excluded;
3130 return (ModFlags & Modifiers.STATIC) != 0;
3135 // FIXME: How do we deal with the user specifying a different
3138 protected override TypeAttributes TypeAttr {
3140 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3142 ta |= StaticClassAttribute;
3148 public sealed class Struct : ClassOrStruct {
3150 // Modifiers allowed in a struct declaration
3152 const int AllowedModifiers =
3155 Modifiers.PROTECTED |
3156 Modifiers.INTERNAL |
3160 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3161 int mod, Attributes attrs)
3162 : base (ns, parent, name, attrs, Kind.Struct)
3166 if (parent.Parent == null)
3167 accmods = Modifiers.INTERNAL;
3169 accmods = Modifiers.PRIVATE;
3171 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3173 this.ModFlags |= Modifiers.SEALED;
3176 public override AttributeTargets AttributeTargets {
3178 return AttributeTargets.Struct;
3182 const TypeAttributes DefaultTypeAttributes =
3183 TypeAttributes.SequentialLayout |
3184 TypeAttributes.Sealed |
3185 TypeAttributes.BeforeFieldInit;
3188 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3190 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3192 // If we are compiling our runtime,
3193 // and we are defining ValueType, then our
3194 // base is `System.Object'.
3196 if (base_class == null) {
3197 if (!RootContext.StdLib && Name == "System.ValueType")
3198 base_class = TypeManager.system_object_expr;
3200 base_class = TypeManager.system_valuetype_expr;
3207 // FIXME: Allow the user to specify a different set of attributes
3208 // in some cases (Sealed for example is mandatory for a class,
3209 // but what SequentialLayout can be changed
3211 protected override TypeAttributes TypeAttr {
3213 return base.TypeAttr | DefaultTypeAttributes;
3217 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3219 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3220 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3221 field.GetSignatureForError ());
3224 base.RegisterFieldForInitialization (field, expression);
3232 public sealed class Interface : TypeContainer, IMemberContainer {
3235 /// Modifiers allowed in a class declaration
3237 public const int AllowedModifiers =
3240 Modifiers.PROTECTED |
3241 Modifiers.INTERNAL |
3245 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3247 : base (ns, parent, name, attrs, Kind.Interface)
3251 if (parent.Parent == null)
3252 accmods = Modifiers.INTERNAL;
3254 accmods = Modifiers.PRIVATE;
3256 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3259 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3261 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3262 !attributes.Contains (TypeManager.guid_attr_type)) {
3263 a.Error_MissingGuidAttribute ();
3266 base.ApplyAttributeBuilder (a, cb);
3270 public override AttributeTargets AttributeTargets {
3272 return AttributeTargets.Interface;
3276 const TypeAttributes DefaultTypeAttributes =
3277 TypeAttributes.AutoLayout |
3278 TypeAttributes.Abstract |
3279 TypeAttributes.Interface;
3281 protected override TypeAttributes TypeAttr {
3283 return base.TypeAttr | DefaultTypeAttributes;
3287 protected override bool VerifyClsCompliance ()
3289 if (!base.VerifyClsCompliance ())
3292 if (ifaces != null) {
3293 foreach (Type t in ifaces) {
3294 if (AttributeTester.IsClsCompliant (t))
3297 Report.SymbolRelatedToPreviousError (t);
3298 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3299 GetSignatureForError (), TypeManager.CSharpName (t));
3307 // It is used as a base class for all property based members
3308 // This includes properties, indexers, and events
3309 public abstract class PropertyBasedMember : InterfaceMemberBase
3311 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3312 Expression type, int mod, int allowed_mod, bool is_iface,
3313 MemberName name, Attributes attrs)
3314 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3318 protected override bool VerifyClsCompliance ()
3320 if (!base.VerifyClsCompliance ())
3323 if (!AttributeTester.IsClsCompliant (MemberType)) {
3324 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3325 GetSignatureForError ());
3333 public abstract class MethodCore : InterfaceMemberBase
3335 public readonly Parameters Parameters;
3336 protected ToplevelBlock block;
3338 public MethodCore (DeclSpace parent, GenericMethod generic,
3339 Expression type, int mod, int allowed_mod, bool is_iface,
3340 MemberName name, Attributes attrs, Parameters parameters)
3341 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3343 Parameters = parameters;
3347 // Returns the System.Type array for the parameters of this method
3349 public Type [] ParameterTypes {
3351 return Parameters.Types;
3355 public Parameters ParameterInfo
3362 public ToplevelBlock Block {
3372 protected override bool CheckBase ()
3374 // Check whether arguments were correct.
3375 if (!DefineParameters (Parameters))
3378 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3379 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3380 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3383 // TODO: Find a better way how to check reserved accessors collision
3384 Method m = this as Method;
3386 if (!m.CheckForDuplications ())
3391 if (!base.CheckBase ())
3398 // Returns a string that represents the signature for this
3399 // member which should be used in XML documentation.
3401 public override string GetDocCommentName (DeclSpace ds)
3403 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3407 // Raised (and passed an XmlElement that contains the comment)
3408 // when GenerateDocComment is writing documentation expectedly.
3410 // FIXME: with a few effort, it could be done with XmlReader,
3411 // that means removal of DOM use.
3413 internal override void OnGenerateDocComment (XmlElement el)
3415 DocUtil.OnMethodGenerateDocComment (this, el);
3419 // Represents header string for documentation comment.
3421 public override string DocCommentHeader
3423 get { return "M:"; }
3426 public override bool EnableOverloadChecks (MemberCore overload)
3428 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3429 caching_flags |= Flags.MethodOverloadsExist;
3436 public virtual void SetYields ()
3438 ModFlags |= Modifiers.METHOD_YIELDS;
3441 protected override bool VerifyClsCompliance ()
3443 if (!base.VerifyClsCompliance ())
3446 if (Parameters.HasArglist) {
3447 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3450 if (!AttributeTester.IsClsCompliant (MemberType)) {
3451 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3452 GetSignatureForError ());
3455 Parameters.VerifyClsCompliance ();
3461 public abstract class InterfaceMemberBase : MemberBase {
3463 // Whether this is an interface member.
3465 public bool IsInterface;
3468 // If true, this is an explicit interface implementation
3470 public bool IsExplicitImpl;
3472 protected bool is_external_implementation;
3475 // The interface type we are explicitly implementing
3477 public Type InterfaceType;
3480 // The method we're overriding if this is an override method.
3482 protected MethodInfo base_method;
3484 readonly int explicit_mod_flags;
3485 public MethodAttributes flags;
3487 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3488 Expression type, int mod, int allowed_mod, bool is_iface,
3489 MemberName name, Attributes attrs)
3490 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3493 IsInterface = is_iface;
3494 IsExplicitImpl = (MemberName.Left != null);
3495 explicit_mod_flags = mod;
3498 protected override bool CheckBase ()
3500 if (!base.CheckBase ())
3506 // Is null for System.Object while compiling corlib and base interfaces
3507 if (Parent.PartialContainer.BaseCache == null) {
3508 if ((ModFlags & Modifiers.NEW) != 0) {
3509 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3514 Type base_ret_type = null;
3515 base_method = FindOutBaseMethod (ref base_ret_type);
3517 // method is override
3518 if (base_method != null) {
3519 if (!CheckMethodAgainstBase (base_ret_type))
3522 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3523 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3525 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3526 Report.SymbolRelatedToPreviousError (base_method);
3527 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3528 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3531 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3532 Report.SymbolRelatedToPreviousError (base_method);
3533 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3534 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3541 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3542 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3543 if (conflict_symbol != null) {
3544 Report.SymbolRelatedToPreviousError (conflict_symbol);
3546 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3547 else if (this is PropertyBase)
3548 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3550 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3552 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3553 GetSignatureForError (), SimpleName.GetMemberType (this));
3558 if (conflict_symbol == null) {
3559 if ((ModFlags & Modifiers.NEW) != 0) {
3560 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3565 if ((ModFlags & Modifiers.NEW) == 0) {
3566 if (this is Method && conflict_symbol is MethodBase)
3569 Report.SymbolRelatedToPreviousError (conflict_symbol);
3570 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3571 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3578 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3579 // that have been defined.
3581 // `name' is the user visible name for reporting errors (this is used to
3582 // provide the right name regarding method names and properties)
3584 bool CheckMethodAgainstBase (Type base_method_type)
3588 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3589 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3590 Report.Error (506, Location,
3591 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3592 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3596 // Now we check that the overriden method is not final
3598 if (base_method.IsFinal) {
3599 Report.SymbolRelatedToPreviousError (base_method);
3600 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3601 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3605 // Check that the permissions are not being changed
3607 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3608 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3610 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3611 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3615 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3616 Report.SymbolRelatedToPreviousError (base_method);
3617 if (this is PropertyBasedMember) {
3618 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3619 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3622 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3623 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3629 if ((ModFlags & Modifiers.NEW) == 0) {
3630 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3631 ModFlags |= Modifiers.NEW;
3632 Report.SymbolRelatedToPreviousError (base_method);
3633 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3634 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",
3635 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3637 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3638 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3642 if (base_method.IsAbstract && !IsInterface) {
3643 Report.SymbolRelatedToPreviousError (base_method);
3644 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3645 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3653 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3655 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3657 // when overriding protected internal, the method can be declared
3658 // protected internal only within the same assembly or assembly
3659 // which has InternalsVisibleTo
3661 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3662 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3663 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3665 // if it's not "protected internal", it must be "protected"
3669 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3671 // protected within the same assembly - an error
3674 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3675 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3677 // protected ok, but other attributes differ - report an error
3683 return (thisp == base_classp);
3687 protected bool DefineParameters (Parameters parameters)
3689 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3691 if (!parameters.Resolve (rc))
3695 foreach (Parameter p in parameters.FixedParameters) {
3696 if (p.CheckAccessibility (this))
3699 Report.SymbolRelatedToPreviousError (p.ParameterType);
3700 if (this is Indexer)
3701 Report.Error (55, Location,
3702 "Inconsistent accessibility: parameter type `" +
3703 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3704 "accessible than indexer `" + GetSignatureForError () + "'");
3705 else if (this is Operator)
3706 Report.Error (57, Location,
3707 "Inconsistent accessibility: parameter type `" +
3708 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3709 "accessible than operator `" + GetSignatureForError () + "'");
3711 Report.Error (51, Location,
3712 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3713 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3719 protected override bool DoDefine()
3721 if (!base.DoDefine ())
3724 if (IsExplicitImpl) {
3725 Expression expr = MemberName.Left.GetTypeExpression ();
3726 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
3730 InterfaceType = texpr.Type;
3732 if (!InterfaceType.IsInterface) {
3733 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3737 if (!Parent.PartialContainer.VerifyImplements (this))
3744 protected virtual bool DoDefineBase ()
3747 throw new InternalErrorException ();
3750 ModFlags = Modifiers.PUBLIC |
3751 Modifiers.ABSTRACT |
3752 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3754 flags = MethodAttributes.Public |
3755 MethodAttributes.Abstract |
3756 MethodAttributes.HideBySig |
3757 MethodAttributes.NewSlot |
3758 MethodAttributes.Virtual;
3760 if (!Parent.PartialContainer.MethodModifiersValid (this))
3763 flags = Modifiers.MethodAttr (ModFlags);
3766 if (IsExplicitImpl) {
3767 Expression expr = MemberName.Left.GetTypeExpression ();
3768 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
3769 if (iface_texpr == null)
3772 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3773 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3774 GetSignatureForError ());
3778 InterfaceType = iface_texpr.Type;
3780 if (!InterfaceType.IsInterface) {
3781 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3785 if (!Parent.PartialContainer.VerifyImplements (this))
3788 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3794 public override void Emit()
3796 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3797 // We are more strict than Microsoft and report CS0626 as error
3798 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3799 Report.Error (626, Location,
3800 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3801 GetSignatureForError ());
3807 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3809 Report.SymbolRelatedToPreviousError (base_method);
3810 string base_name = TypeManager.GetFullNameSignature (base_method);
3811 string this_name = GetSignatureForError ();
3812 if (suffix != null) {
3813 base_name += suffix;
3814 this_name += suffix;
3817 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3818 this_name, Modifiers.GetDescription (ma), base_name);
3821 protected static string Error722 {
3823 return "`{0}': static types cannot be used as return types";
3828 /// Gets base method and its return type
3830 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3833 // The "short" name of this property / indexer / event. This is the
3834 // name without the explicit interface.
3836 public string ShortName
3838 get { return MemberName.Name; }
3839 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3842 public string GetFullName (MemberName name)
3844 if (!IsExplicitImpl)
3847 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3850 protected override bool VerifyClsCompliance ()
3852 if (!base.VerifyClsCompliance ()) {
3853 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3854 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3857 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3858 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3863 if (GenericMethod != null)
3864 GenericMethod.VerifyClsCompliance ();
3869 public override bool IsUsed
3871 get { return IsExplicitImpl || base.IsUsed; }
3876 public abstract class MethodOrOperator : MethodCore, IMethodData
3878 public MethodBuilder MethodBuilder;
3879 ReturnParameter return_attributes;
3880 ListDictionary declarative_security;
3881 protected MethodData MethodData;
3884 ArrayList anonymous_methods;
3886 static string[] attribute_targets = new string [] { "method", "return" };
3888 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3889 int allowed_mod, bool is_interface, MemberName name,
3890 Attributes attrs, Parameters parameters)
3891 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3896 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3898 if (a.Target == AttributeTargets.ReturnValue) {
3899 if (return_attributes == null)
3900 return_attributes = new ReturnParameter (MethodBuilder, Location);
3902 return_attributes.ApplyAttributeBuilder (a, cb);
3906 if (a.IsInternalMethodImplAttribute) {
3907 is_external_implementation = true;
3910 if (a.Type == TypeManager.dllimport_type) {
3911 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3912 if ((ModFlags & extern_static) != extern_static) {
3913 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3915 is_external_implementation = true;
3918 if (a.IsValidSecurityAttribute ()) {
3919 if (declarative_security == null)
3920 declarative_security = new ListDictionary ();
3921 a.ExtractSecurityPermissionSet (declarative_security);
3925 if (MethodBuilder != null)
3926 MethodBuilder.SetCustomAttribute (cb);
3929 public override AttributeTargets AttributeTargets {
3931 return AttributeTargets.Method;
3935 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3937 return new EmitContext (
3938 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3941 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
3943 if (anonymous_methods == null)
3944 anonymous_methods = new ArrayList ();
3945 anonymous_methods.Add (anonymous);
3948 protected bool DefineGenericMethod ()
3950 if (!DoDefineBase ())
3954 if (GenericMethod != null) {
3957 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags); //, ReturnType, null);
3959 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3962 if (!GenericMethod.Define (MethodBuilder, block))
3970 public bool ResolveMembers ()
3972 if (!DefineGenericMethod ())
3975 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
3976 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
3977 if (iterator == null)
3981 if (anonymous_methods != null) {
3982 foreach (AnonymousMethodExpression ame in anonymous_methods) {
3983 if (!ame.CreateAnonymousHelpers ())
3991 public override bool Define ()
3996 if (!CheckAbstractAndExtern (block != null))
3999 if ((ModFlags & Modifiers.PARTIAL) != 0) {
4000 for (int i = 0; i < Parameters.Count; ++i ) {
4001 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
4002 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
4003 GetSignatureForError ());
4012 if (IsPartialDefinition) {
4013 caching_flags &= ~Flags.Excluded_Undetected;
4014 caching_flags |= Flags.Excluded;
4015 // Add to member cache only when a partial method implementation is not there
4016 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
4017 MethodBase mb = new PartialMethodDefinitionInfo (this);
4018 Parent.MemberCache.AddMember (mb, this);
4019 TypeManager.AddMethod (mb, this);
4025 MethodData = new MethodData (
4026 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
4028 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
4031 MethodBuilder = MethodData.MethodBuilder;
4034 if (MethodBuilder.IsGenericMethod)
4035 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
4038 Parent.MemberCache.AddMember (MethodBuilder, this);
4040 if (!TypeManager.IsGenericParameter (MemberType)) {
4041 if (MemberType.IsAbstract && MemberType.IsSealed) {
4042 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4050 public override void Emit ()
4053 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
4054 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
4056 if (OptAttributes != null)
4057 OptAttributes.Emit ();
4059 if (declarative_security != null) {
4060 foreach (DictionaryEntry de in declarative_security) {
4061 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4068 protected void Error_ConditionalAttributeIsNotValid ()
4070 Report.Error (577, Location,
4071 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4072 GetSignatureForError ());
4075 public bool IsPartialDefinition {
4077 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
4081 public bool IsPartialImplementation {
4083 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
4087 public override string[] ValidAttributeTargets {
4089 return attribute_targets;
4093 #region IMethodData Members
4095 public CallingConventions CallingConventions {
4097 CallingConventions cc = Parameters.CallingConvention;
4098 if (Parameters.HasArglist && block != null)
4099 block.HasVarargs = true;
4102 if ((ModFlags & Modifiers.STATIC) == 0)
4103 cc |= CallingConventions.HasThis;
4105 // FIXME: How is `ExplicitThis' used in C#?
4111 public Type ReturnType {
4117 public MemberName MethodName {
4123 public Iterator Iterator {
4124 get { return iterator; }
4127 public new Location Location {
4129 return base.Location;
4133 protected override bool CheckBase ()
4135 if (!base.CheckBase ())
4138 // TODO: Destructor should derive from MethodCore
4139 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4140 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4141 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4149 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4151 public bool IsExcluded () {
4152 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4153 return (caching_flags & Flags.Excluded) != 0;
4155 caching_flags &= ~Flags.Excluded_Undetected;
4157 if (base_method == null) {
4158 if (OptAttributes == null)
4161 if (TypeManager.conditional_attribute_type == null)
4164 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4169 foreach (Attribute a in attrs) {
4170 string condition = a.GetConditionalAttributeValue ();
4171 if (condition == null)
4174 if (RootContext.AllDefines.Contains (condition))
4178 caching_flags |= Flags.Excluded;
4182 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4184 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4185 caching_flags |= Flags.Excluded;
4191 if (md.IsExcluded ()) {
4192 caching_flags |= Flags.Excluded;
4198 GenericMethod IMethodData.GenericMethod {
4200 return GenericMethod;
4204 public virtual void EmitExtraSymbolInfo ()
4211 public class SourceMethod : ISourceMethod
4216 protected SourceMethod (DeclSpace parent, MethodBase builder,
4217 ISourceFile file, Location start, Location end)
4219 this.parent = parent;
4220 this.builder = builder;
4222 SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
4225 public string Name {
4226 get { return builder.Name; }
4229 public int NamespaceID {
4230 get { return parent.NamespaceEntry.SymbolFileID; }
4235 if (builder is MethodBuilder)
4236 return ((MethodBuilder) builder).GetToken ().Token;
4237 else if (builder is ConstructorBuilder)
4238 return ((ConstructorBuilder) builder).GetToken ().Token;
4240 throw new NotSupportedException ();
4244 public void CloseMethod ()
4246 SymbolWriter.CloseMethod ();
4249 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
4251 if (!SymbolWriter.HasSymbolWriter)
4256 Location start_loc = block.StartLocation;
4257 if (start_loc.IsNull)
4260 Location end_loc = block.EndLocation;
4264 ISourceFile file = start_loc.SourceFile;
4268 return new SourceMethod (
4269 parent, builder, file, start_loc, end_loc);
4273 public class Method : MethodOrOperator, IAnonymousHost {
4276 /// Modifiers allowed in a class declaration
4278 const int AllowedModifiers =
4281 Modifiers.PROTECTED |
4282 Modifiers.INTERNAL |
4287 Modifiers.OVERRIDE |
4288 Modifiers.ABSTRACT |
4290 Modifiers.METHOD_YIELDS |
4293 const int AllowedInterfaceModifiers =
4294 Modifiers.NEW | Modifiers.UNSAFE;
4297 // return_type can be "null" for VOID values.
4299 public Method (DeclSpace parent, GenericMethod generic,
4300 Expression return_type, int mod, bool is_iface,
4301 MemberName name, Parameters parameters, Attributes attrs)
4302 : base (parent, generic, return_type, mod,
4303 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4304 is_iface, name, attrs, parameters)
4308 public override string GetSignatureForError()
4310 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4313 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4315 Report.Error (17, location,
4316 "Program `{0}' has more than one entry point defined: `{1}'",
4317 CodeGen.FileName, TypeManager.CSharpSignature(b));
4320 bool IsEntryPoint ()
4322 if (ReturnType != TypeManager.void_type &&
4323 ReturnType != TypeManager.int32_type)
4326 if (Parameters.Count == 0)
4329 if (Parameters.Count > 1)
4332 Type t = Parameters.ParameterType (0);
4333 return t.IsArray && t.GetArrayRank () == 1 &&
4334 TypeManager.GetElementType (t) == TypeManager.string_type &&
4335 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4338 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4340 if (a.Type == TypeManager.conditional_attribute_type) {
4341 if (IsExplicitImpl) {
4342 Error_ConditionalAttributeIsNotValid ();
4346 if (ReturnType != TypeManager.void_type) {
4347 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4351 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4352 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4357 Report.Error (582, Location, "Conditional not valid on interface members");
4361 if (MethodData.implementing != null) {
4362 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4363 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4364 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4368 for (int i = 0; i < Parameters.Count; ++i) {
4369 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4370 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4376 if (a.Type == TypeManager.extension_attribute_type) {
4377 a.Error_MisusedExtensionAttribute ();
4381 base.ApplyAttributeBuilder (a, cb);
4384 public bool CheckForDuplications ()
4386 ArrayList ar = Parent.PartialContainer.Properties;
4388 for (int i = 0; i < ar.Count; ++i) {
4389 PropertyBase pb = (PropertyBase) ar [i];
4390 if (pb.AreAccessorsDuplicateImplementation (this))
4395 ar = Parent.PartialContainer.Indexers;
4397 for (int i = 0; i < ar.Count; ++i) {
4398 PropertyBase pb = (PropertyBase) ar [i];
4399 if (pb.AreAccessorsDuplicateImplementation (this))
4410 public override bool Define ()
4412 if (!base.Define ())
4415 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4416 Error1599 (Location, ReturnType);
4420 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4421 Name == "Finalize" && !(this is Destructor)) {
4422 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4425 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4426 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4427 Parent.PartialContainer.Mark_HasEquals ();
4428 else if (Parameters.Empty && Name == "GetHashCode")
4429 Parent.PartialContainer.Mark_HasGetHashCode ();
4432 if ((ModFlags & Modifiers.STATIC) == 0)
4435 if (Parameters.HasExtensionMethodType) {
4436 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4437 if (!Parent.IsTopLevel)
4438 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4439 GetSignatureForError ());
4441 if (TypeManager.extension_attribute_type == null) {
4442 Report.Error (1110, Location,
4443 "`{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",
4444 GetSignatureForError ());
4445 } else if (TypeManager.extension_attribute_attr == null) {
4446 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4447 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4450 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4453 ModFlags |= Modifiers.METHOD_EXTENSION;
4454 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4455 CodeGen.Assembly.HasExtensionMethods = true;
4457 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4458 GetSignatureForError ());
4463 // This is used to track the Entry Point,
4465 if (RootContext.NeedsEntryPoint &&
4467 (RootContext.MainClass == null ||
4468 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4469 if (IsEntryPoint ()) {
4471 if (RootContext.EntryPoint == null) {
4472 if (Parent.IsGeneric || MemberName.IsGeneric) {
4473 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4474 GetSignatureForError ());
4476 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4477 md.SetMemberIsUsed ();
4479 RootContext.EntryPoint = MethodBuilder;
4480 RootContext.EntryPointLocation = Location;
4483 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4484 Error_DuplicateEntryPoint (MethodBuilder, Location);
4487 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4488 GetSignatureForError ());
4498 public override void Emit ()
4501 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4502 if (IsPartialDefinition) {
4504 // Do attribute checks only when partial implementation does not exist
4506 if (MethodBuilder == null)
4512 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4513 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4514 GetSignatureForError ());
4516 MethodData.Emit (Parent);
4520 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4521 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4527 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4528 Location, MethodBuilder);
4533 public override bool EnableOverloadChecks (MemberCore overload)
4535 // TODO: It can be deleted when members will be defined in correct order
4536 if (overload is Operator)
4537 return overload.EnableOverloadChecks (this);
4539 if (overload is Indexer)
4542 return base.EnableOverloadChecks (overload);
4545 public static void Error1599 (Location loc, Type t)
4547 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4550 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4552 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4553 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4558 if (mi.IsSpecialName)
4561 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4565 public void SetPartialDefinition (Method methodDefinition)
4567 caching_flags |= Flags.PartialDefinitionExists;
4568 methodDefinition.MethodBuilder = MethodBuilder;
4569 if (methodDefinition.attributes == null)
4572 if (attributes == null) {
4573 attributes = methodDefinition.attributes;
4575 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4579 protected override bool VerifyClsCompliance ()
4581 if (!base.VerifyClsCompliance ())
4584 if (ParameterInfo.Count > 0) {
4585 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4587 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4594 public abstract class ConstructorInitializer : Expression
4596 ArrayList argument_list;
4597 MethodGroupExpr base_constructor_group;
4599 public ConstructorInitializer (ArrayList argument_list, Location loc)
4601 this.argument_list = argument_list;
4605 public ArrayList Arguments {
4607 return argument_list;
4611 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4613 if (argument_list != null){
4614 foreach (Argument a in argument_list){
4615 if (!a.Resolve (ec, loc))
4620 if (this is ConstructorBaseInitializer) {
4621 if (ec.ContainerType.BaseType == null)
4624 type = ec.ContainerType.BaseType;
4625 if (ec.ContainerType.IsValueType) {
4626 Report.Error (522, loc,
4627 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4632 // It is legal to have "this" initializers that take no arguments
4633 // in structs, they are just no-ops.
4635 // struct D { public D (int a) : this () {}
4637 if (ec.ContainerType.IsValueType && argument_list == null)
4640 type = ec.ContainerType;
4643 base_constructor_group = MemberLookupFinal (
4644 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4645 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4646 loc) as MethodGroupExpr;
4648 if (base_constructor_group == null)
4651 base_constructor_group = base_constructor_group.OverloadResolve (
4652 ec, ref argument_list, false, loc);
4654 if (base_constructor_group == null)
4657 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4659 if (base_ctor == caller_builder){
4660 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4666 public override Expression DoResolve (EmitContext ec)
4668 throw new NotSupportedException ();
4671 public override void Emit (EmitContext ec)
4673 // It can be null for static initializers
4674 if (base_constructor_group == null)
4677 ec.Mark (loc, false);
4679 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4681 base_constructor_group.EmitCall (ec, argument_list);
4685 public class ConstructorBaseInitializer : ConstructorInitializer {
4686 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4687 base (argument_list, l)
4692 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4693 public GeneratedBaseInitializer (Location loc):
4699 public class ConstructorThisInitializer : ConstructorInitializer {
4700 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4701 base (argument_list, l)
4706 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4707 public ConstructorBuilder ConstructorBuilder;
4708 public ConstructorInitializer Initializer;
4709 ListDictionary declarative_security;
4710 ArrayList anonymous_methods;
4711 bool has_compliant_args;
4714 // Modifiers allowed for a constructor.
4716 public const int AllowedModifiers =
4718 Modifiers.PROTECTED |
4719 Modifiers.INTERNAL |
4725 static readonly string[] attribute_targets = new string [] { "method" };
4728 // The spec claims that static is not permitted, but
4729 // my very own code has static constructors.
4731 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4732 ConstructorInitializer init, Location loc)
4733 : base (parent, null, null, mod, AllowedModifiers, false,
4734 new MemberName (name, loc), null, args)
4739 public bool HasCompliantArgs {
4740 get { return has_compliant_args; }
4743 public override AttributeTargets AttributeTargets {
4744 get { return AttributeTargets.Constructor; }
4747 public Iterator Iterator {
4748 get { return null; }
4752 // Returns true if this is a default constructor
4754 public bool IsDefault ()
4756 if ((ModFlags & Modifiers.STATIC) != 0)
4757 return Parameters.Empty;
4759 return Parameters.Empty &&
4760 (Initializer is ConstructorBaseInitializer) &&
4761 (Initializer.Arguments == null);
4764 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4766 if (a.IsValidSecurityAttribute ()) {
4767 if (declarative_security == null) {
4768 declarative_security = new ListDictionary ();
4770 a.ExtractSecurityPermissionSet (declarative_security);
4774 if (a.IsInternalMethodImplAttribute) {
4775 is_external_implementation = true;
4778 ConstructorBuilder.SetCustomAttribute (cb);
4781 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4783 if (anonymous_methods == null)
4784 anonymous_methods = new ArrayList ();
4785 anonymous_methods.Add (anonymous);
4788 public bool ResolveMembers ()
4790 if (anonymous_methods != null) {
4791 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4792 if (!ame.CreateAnonymousHelpers ())
4800 protected override bool CheckBase ()
4802 if ((ModFlags & Modifiers.STATIC) != 0) {
4803 if (!Parameters.Empty) {
4804 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4805 GetSignatureForError ());
4809 // the rest can be ignored
4813 // Check whether arguments were correct.
4814 if (!DefineParameters (Parameters))
4817 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4818 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4821 if (Parent.PartialContainer.Kind == Kind.Struct) {
4822 if (ParameterTypes.Length == 0) {
4823 Report.Error (568, Location,
4824 "Structs cannot contain explicit parameterless constructors");
4829 CheckProtectedModifier ();
4835 // Creates the ConstructorBuilder
4837 public override bool Define ()
4839 if (ConstructorBuilder != null)
4842 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4843 MethodAttributes.SpecialName);
4845 if ((ModFlags & Modifiers.STATIC) != 0) {
4846 ca |= MethodAttributes.Static | MethodAttributes.Private;
4848 ca |= MethodAttributes.HideBySig;
4850 if ((ModFlags & Modifiers.PUBLIC) != 0)
4851 ca |= MethodAttributes.Public;
4852 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4853 if ((ModFlags & Modifiers.INTERNAL) != 0)
4854 ca |= MethodAttributes.FamORAssem;
4856 ca |= MethodAttributes.Family;
4857 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4858 ca |= MethodAttributes.Assembly;
4860 ca |= MethodAttributes.Private;
4863 if (!CheckAbstractAndExtern (block != null))
4866 // Check if arguments were correct.
4870 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4871 ca, CallingConventions,
4874 if ((ModFlags & Modifiers.UNSAFE) != 0)
4875 ConstructorBuilder.InitLocals = false;
4877 if (Parent.PartialContainer.IsComImport) {
4878 if (!IsDefault ()) {
4879 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4880 Parent.GetSignatureForError ());
4883 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4886 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4887 TypeManager.AddMethod (ConstructorBuilder, this);
4889 // It's here only to report an error
4890 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4891 member_type = TypeManager.void_type;
4892 Iterator.CreateIterator (this, Parent, null, ModFlags);
4901 public override void Emit ()
4903 if (OptAttributes != null)
4904 OptAttributes.Emit ();
4908 EmitContext ec = CreateEmitContext (null, null);
4911 // If we use a "this (...)" constructor initializer, then
4912 // do not emit field initializers, they are initialized in the other constructor
4914 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4915 !(Initializer is ConstructorThisInitializer);
4917 if (emit_field_initializers)
4918 Parent.PartialContainer.ResolveFieldInitializers (ec);
4920 if (block != null) {
4921 // If this is a non-static `struct' constructor and doesn't have any
4922 // initializer, it must initialize all of the struct's fields.
4923 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4924 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4925 block.AddThisVariable (Parent, Location);
4927 if (!block.ResolveMeta (ec, ParameterInfo))
4931 if ((ModFlags & Modifiers.STATIC) == 0){
4932 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4933 Initializer = new GeneratedBaseInitializer (Location);
4936 // Spec mandates that Initializers will not have
4940 if ((Initializer != null) &&
4941 !Initializer.Resolve (ConstructorBuilder, ec))
4943 ec.IsStatic = false;
4946 Parameters.ApplyAttributes (ConstructorBuilder);
4948 SourceMethod source = SourceMethod.Create (
4949 Parent, ConstructorBuilder, block);
4951 bool unreachable = false;
4952 if (block != null) {
4953 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4956 ec.EmitMeta (block);
4958 if (Report.Errors > 0)
4961 if (emit_field_initializers)
4962 Parent.PartialContainer.EmitFieldInitializers (ec);
4964 if (block.ScopeInfo != null) {
4965 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4966 init.EmitStatement (ec);
4969 if (Initializer != null)
4970 Initializer.Emit (ec);
4972 ec.EmitResolvedTopBlock (block, unreachable);
4976 source.CloseMethod ();
4978 if (declarative_security != null) {
4979 foreach (DictionaryEntry de in declarative_security) {
4980 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4987 // Is never override
4988 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4993 public override string GetSignatureForError()
4995 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4998 public override string[] ValidAttributeTargets {
5000 return attribute_targets;
5004 protected override bool VerifyClsCompliance ()
5006 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
5010 if (ParameterInfo.Count > 0) {
5011 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
5013 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
5015 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
5016 foreach (Type param in ParameterTypes) {
5017 if (param.IsArray) {
5023 has_compliant_args = true;
5027 #region IMethodData Members
5029 public System.Reflection.CallingConventions CallingConventions {
5031 CallingConventions cc = Parameters.CallingConvention;
5033 if (Parent.PartialContainer.Kind == Kind.Class)
5034 if ((ModFlags & Modifiers.STATIC) == 0)
5035 cc |= CallingConventions.HasThis;
5037 // FIXME: How is `ExplicitThis' used in C#?
5043 public new Location Location {
5045 return base.Location;
5049 public MemberName MethodName {
5055 public Type ReturnType {
5061 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5063 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5064 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5065 ec.CurrentBlock = block;
5069 public bool IsExcluded()
5074 GenericMethod IMethodData.GenericMethod {
5080 void IMethodData.EmitExtraSymbolInfo ()
5087 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5089 public interface IMethodData
5091 CallingConventions CallingConventions { get; }
5092 Location Location { get; }
5093 MemberName MethodName { get; }
5094 Type ReturnType { get; }
5095 GenericMethod GenericMethod { get; }
5096 Parameters ParameterInfo { get; }
5098 Iterator Iterator { get; }
5100 Attributes OptAttributes { get; }
5101 ToplevelBlock Block { get; set; }
5103 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5104 ObsoleteAttribute GetObsoleteAttribute ();
5105 string GetSignatureForError ();
5107 bool IsClsComplianceRequired ();
5108 void SetMemberIsUsed ();
5109 void EmitExtraSymbolInfo ();
5113 // Encapsulates most of the Method's state
5115 public class MethodData {
5117 readonly IMethodData method;
5119 public readonly GenericMethod GenericMethod;
5122 // Are we implementing an interface ?
5124 public MethodInfo implementing;
5129 protected InterfaceMemberBase member;
5130 protected int modifiers;
5131 protected MethodAttributes flags;
5132 protected Type declaring_type;
5133 protected MethodInfo parent_method;
5135 MethodBuilder builder = null;
5136 public MethodBuilder MethodBuilder {
5142 public Type DeclaringType {
5144 return declaring_type;
5148 public MethodData (InterfaceMemberBase member,
5149 int modifiers, MethodAttributes flags, IMethodData method)
5151 this.member = member;
5152 this.modifiers = modifiers;
5155 this.method = method;
5158 public MethodData (InterfaceMemberBase member,
5159 int modifiers, MethodAttributes flags,
5160 IMethodData method, MethodBuilder builder,
5161 GenericMethod generic, MethodInfo parent_method)
5162 : this (member, modifiers, flags, method)
5164 this.builder = builder;
5165 this.GenericMethod = generic;
5166 this.parent_method = parent_method;
5169 public bool Define (DeclSpace parent, string method_full_name)
5171 string name = method.MethodName.Basename;
5173 TypeContainer container = parent.PartialContainer;
5175 PendingImplementation pending = container.PendingImplementations;
5176 if (pending != null){
5177 if (member is Indexer) // TODO: test it, but it should work without this IF
5178 implementing = pending.IsInterfaceIndexer (
5179 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5181 implementing = pending.IsInterfaceMethod (
5182 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5184 if (member.InterfaceType != null){
5185 if (implementing == null){
5186 if (member is PropertyBase) {
5187 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5188 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5189 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5192 Report.Error (539, method.Location,
5193 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5194 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5198 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5199 Report.SymbolRelatedToPreviousError (implementing);
5200 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5201 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5205 if (implementing != null) {
5206 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5207 if (prop_method == null) {
5208 if (TypeManager.IsSpecialMethod (implementing)) {
5209 Report.SymbolRelatedToPreviousError (implementing);
5210 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5211 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5212 implementing.Name.StartsWith ("get_") ? "get" : "set");
5214 } else if (implementing.DeclaringType.IsInterface) {
5215 if (!implementing.IsSpecialName) {
5216 Report.SymbolRelatedToPreviousError (implementing);
5217 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5218 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5221 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5222 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5223 Report.SymbolRelatedToPreviousError (implementing);
5224 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5225 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5234 // For implicit implementations, make sure we are public, for
5235 // explicit implementations, make sure we are private.
5237 if (implementing != null){
5239 // Setting null inside this block will trigger a more
5240 // verbose error reporting for missing interface implementations
5242 // The "candidate" function has been flagged already
5243 // but it wont get cleared
5245 if (member.IsExplicitImpl){
5246 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5247 Report.SymbolRelatedToPreviousError (implementing);
5248 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5249 method.GetSignatureForError ());
5253 if (implementing.DeclaringType.IsInterface) {
5255 // If this is an interface method implementation,
5256 // check for public accessibility
5258 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5260 implementing = null;
5262 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5263 // We may never be private.
5264 implementing = null;
5266 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5268 // We may be protected if we're overriding something.
5270 implementing = null;
5275 // Static is not allowed
5277 if ((modifiers & Modifiers.STATIC) != 0){
5278 implementing = null;
5283 // If implementing is still valid, set flags
5285 if (implementing != null){
5287 // When implementing interface methods, set NewSlot
5288 // unless, we are overwriting a method.
5290 if (implementing.DeclaringType.IsInterface){
5291 if ((modifiers & Modifiers.OVERRIDE) == 0)
5292 flags |= MethodAttributes.NewSlot;
5295 MethodAttributes.Virtual |
5296 MethodAttributes.HideBySig;
5298 // Set Final unless we're virtual, abstract or already overriding a method.
5299 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5300 flags |= MethodAttributes.Final;
5303 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5305 if (builder == null)
5308 if (container.CurrentType != null)
5309 declaring_type = container.CurrentType;
5311 declaring_type = container.TypeBuilder;
5313 if ((modifiers & Modifiers.UNSAFE) != 0)
5314 builder.InitLocals = false;
5317 if (implementing != null){
5319 // clear the pending implemntation flag
5321 if (member is Indexer) {
5322 pending.ImplementIndexer (
5323 member.InterfaceType, builder, method.ReturnType,
5324 method.ParameterInfo, member.IsExplicitImpl);
5326 pending.ImplementMethod (
5327 member.InterfaceType, name, method.ReturnType,
5328 method.ParameterInfo, member.IsExplicitImpl);
5330 if (member.IsExplicitImpl)
5331 container.TypeBuilder.DefineMethodOverride (
5332 builder, implementing);
5335 TypeManager.AddMethod (builder, method);
5337 if (GenericMethod != null) {
5338 bool is_override = member.IsExplicitImpl |
5339 ((modifiers & Modifiers.OVERRIDE) != 0);
5341 if (implementing != null)
5342 parent_method = implementing;
5344 EmitContext ec = method.CreateEmitContext (container, null);
5345 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5354 /// Create the MethodBuilder for the method
5356 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5358 if (builder == null) {
5359 builder = container.TypeBuilder.DefineMethod (
5360 method_name, flags, method.CallingConventions,
5361 method.ReturnType, ParameterTypes);
5365 #if GMCS_SOURCE && !MS_COMPATIBLE
5366 builder.SetGenericMethodSignature (
5367 flags, method.CallingConventions,
5368 method.ReturnType, ParameterTypes);
5375 public void Emit (DeclSpace parent)
5377 ToplevelBlock block = method.Block;
5381 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5383 ec = method.CreateEmitContext (parent, null);
5385 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5387 if (GenericMethod != null)
5388 GenericMethod.EmitAttributes ();
5390 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5393 // Handle destructors specially
5395 // FIXME: This code generates buggy code
5397 if (member is Destructor)
5398 EmitDestructor (ec, block);
5400 ec.EmitTopBlock (method, block);
5402 if (source != null) {
5403 method.EmitExtraSymbolInfo ();
5404 source.CloseMethod ();
5408 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5410 ILGenerator ig = ec.ig;
5412 Label finish = ig.DefineLabel ();
5414 block.SetDestructor ();
5416 ig.BeginExceptionBlock ();
5417 ec.ReturnLabel = finish;
5418 ec.HasReturnLabel = true;
5419 ec.EmitTopBlock (method, block);
5421 // ig.MarkLabel (finish);
5422 ig.BeginFinallyBlock ();
5424 if (ec.ContainerType.BaseType != null) {
5425 Expression member_lookup = Expression.MemberLookup (
5426 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5427 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5429 if (member_lookup != null){
5430 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5432 ig.Emit (OpCodes.Ldarg_0);
5433 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5437 ig.EndExceptionBlock ();
5438 //ig.MarkLabel (ec.ReturnLabel);
5439 ig.Emit (OpCodes.Ret);
5443 // TODO: Should derive from MethodCore
5444 public class Destructor : Method {
5446 static string[] attribute_targets = new string [] { "method" };
5448 public Destructor (DeclSpace parent, Expression return_type, int mod,
5449 string name, Parameters parameters, Attributes attrs,
5451 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5455 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5457 if (a.Type == TypeManager.conditional_attribute_type) {
5458 Error_ConditionalAttributeIsNotValid ();
5462 base.ApplyAttributeBuilder (a, cb);
5465 public override string GetSignatureForError ()
5467 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5470 public override string[] ValidAttributeTargets {
5472 return attribute_targets;
5477 abstract public class MemberBase : MemberCore {
5478 public Expression Type;
5479 public readonly DeclSpace ds;
5480 public readonly GenericMethod GenericMethod;
5483 // The type of this property / indexer / event
5485 protected Type member_type;
5486 public Type MemberType {
5488 if (member_type == null && Type != null) {
5489 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5490 Type = Type.ResolveAsTypeTerminal (rc, false);
5492 member_type = Type.Type;
5500 // The constructor is only exposed to our children
5502 protected MemberBase (DeclSpace parent, GenericMethod generic,
5503 Expression type, int mod, int allowed_mod, int def_mod,
5504 MemberName name, Attributes attrs)
5505 : base (parent, name, attrs)
5507 this.ds = generic != null ? generic : (DeclSpace) parent;
5509 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5510 GenericMethod = generic;
5511 if (GenericMethod != null)
5512 GenericMethod.ModFlags = ModFlags;
5515 protected virtual bool CheckBase ()
5517 CheckProtectedModifier ();
5522 protected virtual bool DoDefine ()
5524 if (MemberType == null)
5527 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5528 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5529 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5530 GetSignatureForError (), Parent.GetSignatureForError ());
5534 // verify accessibility
5535 if (!IsAccessibleAs (MemberType)) {
5536 Report.SymbolRelatedToPreviousError (MemberType);
5537 if (this is Property)
5538 Report.Error (53, Location,
5539 "Inconsistent accessibility: property type `" +
5540 TypeManager.CSharpName (MemberType) + "' is less " +
5541 "accessible than property `" + GetSignatureForError () + "'");
5542 else if (this is Indexer)
5543 Report.Error (54, Location,
5544 "Inconsistent accessibility: indexer return type `" +
5545 TypeManager.CSharpName (MemberType) + "' is less " +
5546 "accessible than indexer `" + GetSignatureForError () + "'");
5547 else if (this is MethodCore) {
5548 if (this is Operator)
5549 Report.Error (56, Location,
5550 "Inconsistent accessibility: return type `" +
5551 TypeManager.CSharpName (MemberType) + "' is less " +
5552 "accessible than operator `" + GetSignatureForError () + "'");
5554 Report.Error (50, Location,
5555 "Inconsistent accessibility: return type `" +
5556 TypeManager.CSharpName (MemberType) + "' is less " +
5557 "accessible than method `" + GetSignatureForError () + "'");
5559 Report.Error (52, Location,
5560 "Inconsistent accessibility: field type `" +
5561 TypeManager.CSharpName (MemberType) + "' is less " +
5562 "accessible than field `" + GetSignatureForError () + "'");
5570 protected bool IsTypePermitted ()
5572 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5573 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5581 // Abstract class for all fields
5583 abstract public class FieldBase : MemberBase {
5584 public FieldBuilder FieldBuilder;
5585 public Status status;
5586 protected Expression initializer;
5589 public enum Status : byte {
5590 HAS_OFFSET = 4 // Used by FieldMember.
5593 static readonly string[] attribute_targets = new string [] { "field" };
5595 protected FieldBase (DeclSpace parent, Expression type, int mod,
5596 int allowed_mod, MemberName name, Attributes attrs)
5597 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5600 if ((mod & Modifiers.ABSTRACT) != 0)
5601 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5604 public override AttributeTargets AttributeTargets {
5606 return AttributeTargets.Field;
5610 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5612 if (a.Type == TypeManager.field_offset_attribute_type) {
5613 status |= Status.HAS_OFFSET;
5615 if (!Parent.PartialContainer.HasExplicitLayout) {
5616 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5620 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5621 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5627 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5628 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5633 if (a.Type == TypeManager.marshal_as_attr_type) {
5634 UnmanagedMarshal marshal = a.GetMarshal (this);
5635 if (marshal != null) {
5636 FieldBuilder.SetMarshal (marshal);
5641 if ((a.HasSecurityAttribute)) {
5642 a.Error_InvalidSecurityParent ();
5646 FieldBuilder.SetCustomAttribute (cb);
5649 protected override bool CheckBase ()
5651 if (!base.CheckBase ())
5654 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5655 if (conflict_symbol == null) {
5656 if ((ModFlags & Modifiers.NEW) != 0) {
5657 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5662 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5663 Report.SymbolRelatedToPreviousError (conflict_symbol);
5664 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5665 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5671 public override bool Define()
5673 if (MemberType == null || Type == null)
5676 if (TypeManager.IsGenericParameter (MemberType))
5679 if (MemberType == TypeManager.void_type) {
5680 // TODO: wrong location
5681 Expression.Error_VoidInvalidInTheContext (Location);
5685 if (MemberType.IsSealed && MemberType.IsAbstract) {
5686 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5696 if (!IsTypePermitted ())
5703 // Represents header string for documentation comment.
5705 public override string DocCommentHeader {
5706 get { return "F:"; }
5709 public override void Emit ()
5712 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5713 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5717 if (OptAttributes != null) {
5718 OptAttributes.Emit ();
5721 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5722 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5728 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5730 Report.SymbolRelatedToPreviousError (static_class);
5731 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5735 public Expression Initializer {
5737 if (value != null) {
5738 this.initializer = value;
5743 protected virtual bool IsFieldClsCompliant {
5745 if (FieldBuilder == null)
5748 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5752 public override string[] ValidAttributeTargets
5755 return attribute_targets;
5759 protected override bool VerifyClsCompliance ()
5761 if (!base.VerifyClsCompliance ())
5764 if (!IsFieldClsCompliant) {
5765 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5770 public void SetAssigned ()
5772 caching_flags |= Flags.IsAssigned;
5776 interface IFixedBuffer
5778 FieldInfo Element { get; }
5779 Type ElementType { get; }
5782 public class FixedFieldExternal: IFixedBuffer
5784 FieldInfo element_field;
5786 public FixedFieldExternal (FieldInfo fi)
5788 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5791 #region IFixedField Members
5793 public FieldInfo Element {
5795 return element_field;
5799 public Type ElementType {
5801 return element_field.FieldType;
5809 /// Fixed buffer implementation
5811 public class FixedField : FieldBase, IFixedBuffer
5813 public const string FixedElementName = "FixedElementField";
5814 static int GlobalCounter = 0;
5815 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5816 static FieldInfo[] fi;
5818 TypeBuilder fixed_buffer_type;
5819 FieldBuilder element;
5820 Expression size_expr;
5822 const int AllowedModifiers =
5825 Modifiers.PROTECTED |
5826 Modifiers.INTERNAL |
5829 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5830 Expression size_expr, Attributes attrs, Location loc):
5831 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5833 if (RootContext.Version == LanguageVersion.ISO_1)
5834 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5836 this.size_expr = size_expr;
5839 public override bool Define()
5841 if (!Parent.IsInUnsafeScope)
5842 Expression.UnsafeError (Location);
5844 if (!base.Define ())
5847 if (!TypeManager.IsPrimitiveType (MemberType)) {
5848 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",
5849 GetSignatureForError ());
5852 // Create nested fixed buffer container
5853 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5854 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5855 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5857 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5858 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5860 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5861 Parent.MemberCache.AddMember (FieldBuilder, this);
5862 TypeManager.RegisterFieldBase (FieldBuilder, this);
5867 public override void Emit()
5869 if (Parent.PartialContainer.Kind != Kind.Struct) {
5870 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5871 GetSignatureForError ());
5874 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5875 Constant c = size_expr.ResolveAsConstant (ec, this);
5879 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5880 if (buffer_size_const == null)
5883 int buffer_size = buffer_size_const.Value;
5885 if (buffer_size <= 0) {
5886 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5890 int type_size = Expression.GetTypeSize (MemberType);
5892 if (buffer_size > int.MaxValue / type_size) {
5893 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5894 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5898 buffer_size *= type_size;
5899 EmitFieldSize (buffer_size);
5903 void EmitFieldSize (int buffer_size)
5905 if (TypeManager.struct_layout_attribute_type == null) {
5906 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5907 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5909 if (TypeManager.struct_layout_attribute_type == null)
5914 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5916 object [] fi_val = new object [] { buffer_size };
5918 if (TypeManager.struct_layout_attribute_ctor == null) {
5919 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5920 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5921 if (TypeManager.struct_layout_attribute_ctor == null)
5925 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5926 ctor_args, fi, fi_val);
5927 fixed_buffer_type.SetCustomAttribute (cab);
5930 // Don't emit FixedBufferAttribute attribute for private types
5932 if ((ModFlags & Modifiers.PRIVATE) != 0)
5935 if (TypeManager.fixed_buffer_attr_ctor == null) {
5936 if (TypeManager.fixed_buffer_attr_type == null) {
5937 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5938 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5940 if (TypeManager.fixed_buffer_attr_type == null)
5944 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5945 Location, TypeManager.type_type, TypeManager.int32_type);
5947 if (TypeManager.fixed_buffer_attr_ctor == null)
5951 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5952 FieldBuilder.SetCustomAttribute (cab);
5955 protected override bool IsFieldClsCompliant {
5961 #region IFixedField Members
5963 public FieldInfo Element {
5969 public Type ElementType {
5979 // The Field class is used to represents class/struct fields during parsing.
5981 public class Field : FieldBase {
5983 // Modifiers allowed in a class declaration
5985 const int AllowedModifiers =
5988 Modifiers.PROTECTED |
5989 Modifiers.INTERNAL |
5992 Modifiers.VOLATILE |
5996 public Field (DeclSpace parent, Expression type, int mod, string name,
5997 Attributes attrs, Location loc)
5998 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6003 bool CanBeVolatile ()
6005 if (TypeManager.IsReferenceType (MemberType))
6008 if (MemberType.IsEnum)
6011 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
6012 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
6013 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
6014 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
6015 MemberType == TypeManager.float_type)
6021 public override bool Define ()
6023 if (!base.Define ())
6026 if ((ModFlags & Modifiers.VOLATILE) != 0){
6027 if (!CanBeVolatile ()) {
6028 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6029 GetSignatureForError (), TypeManager.CSharpName (MemberType));
6032 if ((ModFlags & Modifiers.READONLY) != 0){
6033 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6034 GetSignatureForError ());
6038 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6042 Type[] required_modifier = null;
6043 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6044 if (TypeManager.isvolatile_type == null)
6045 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
6046 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
6048 if (TypeManager.isvolatile_type != null)
6049 required_modifier = new Type [] { TypeManager.isvolatile_type };
6052 FieldBuilder = Parent.TypeBuilder.DefineField (
6053 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
6055 FieldBuilder = Parent.TypeBuilder.DefineField (
6056 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6058 Parent.MemberCache.AddMember (FieldBuilder, this);
6059 TypeManager.RegisterFieldBase (FieldBuilder, this);
6061 catch (ArgumentException) {
6062 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6066 if (initializer != null)
6067 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
6068 new FieldInitializer (FieldBuilder, initializer));
6070 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
6071 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
6072 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
6073 GetSignatureForError ());
6080 protected override bool VerifyClsCompliance ()
6082 if (!base.VerifyClsCompliance ())
6085 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6086 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6094 // `set' and `get' accessors are represented with an Accessor.
6096 public class Accessor : IAnonymousHost {
6098 // Null if the accessor is empty, or a Block if not
6100 public const int AllowedModifiers =
6102 Modifiers.PROTECTED |
6103 Modifiers.INTERNAL |
6106 public ToplevelBlock Block;
6107 public Attributes Attributes;
6108 public Location Location;
6109 public int ModFlags;
6111 public ArrayList AnonymousMethods;
6113 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6118 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6121 public void SetYields ()
6126 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6128 if (AnonymousMethods == null)
6129 AnonymousMethods = new ArrayList ();
6130 AnonymousMethods.Add (ame);
6134 // Ooouh Martin, templates are missing here.
6135 // When it will be possible move here a lot of child code and template method type.
6136 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6137 protected MethodData method_data;
6138 protected ToplevelBlock block;
6139 protected ListDictionary declarative_security;
6141 // The accessor are created event if they are not wanted.
6142 // But we need them because their names are reserved.
6143 // Field says whether accessor will be emited or not
6144 public readonly bool IsDummy;
6146 protected readonly string prefix;
6148 ReturnParameter return_attributes;
6150 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6151 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6153 this.prefix = prefix;
6157 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6159 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6160 accessor.Attributes)
6162 this.prefix = prefix;
6163 this.block = accessor.Block;
6166 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6168 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6171 public void UpdateName (InterfaceMemberBase member)
6173 SetMemberName (SetupName (prefix, member, Location));
6176 #region IMethodData Members
6178 public abstract Iterator Iterator {
6182 public ToplevelBlock Block {
6192 public CallingConventions CallingConventions {
6194 return CallingConventions.Standard;
6198 public bool IsExcluded ()
6203 GenericMethod IMethodData.GenericMethod {
6209 public MemberName MethodName {
6215 public Type[] ParameterTypes {
6217 return ParameterInfo.Types;
6221 public abstract Parameters ParameterInfo { get ; }
6222 public abstract Type ReturnType { get; }
6223 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6227 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6229 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6230 a.Type == TypeManager.conditional_attribute_type) {
6231 Report.Error (1667, a.Location,
6232 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6233 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6237 if (a.IsValidSecurityAttribute ()) {
6238 if (declarative_security == null)
6239 declarative_security = new ListDictionary ();
6240 a.ExtractSecurityPermissionSet (declarative_security);
6244 if (a.Target == AttributeTargets.Method) {
6245 method_data.MethodBuilder.SetCustomAttribute (cb);
6249 if (a.Target == AttributeTargets.ReturnValue) {
6250 if (return_attributes == null)
6251 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6253 return_attributes.ApplyAttributeBuilder (a, cb);
6257 ApplyToExtraTarget (a, cb);
6260 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6262 throw new NotSupportedException ("You forgot to define special attribute target handling");
6265 // It is not supported for the accessors
6266 public sealed override bool Define()
6268 throw new NotSupportedException ();
6271 public void Emit (DeclSpace parent)
6273 EmitMethod (parent);
6276 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6277 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6279 if (OptAttributes != null)
6280 OptAttributes.Emit ();
6282 if (declarative_security != null) {
6283 foreach (DictionaryEntry de in declarative_security) {
6284 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6291 protected virtual void EmitMethod (DeclSpace parent)
6293 method_data.Emit (parent);
6296 public override bool EnableOverloadChecks (MemberCore overload)
6298 // This can only happen with indexers and it will
6299 // be catched as indexer difference
6300 if (overload is AbstractPropertyEventMethod)
6303 if (overload is MethodCore) {
6304 caching_flags |= Flags.MethodOverloadsExist;
6310 public override bool IsClsComplianceRequired()
6315 public bool IsDuplicateImplementation (MethodCore method)
6317 if (!MemberName.Equals (method.MemberName))
6320 Type[] param_types = method.ParameterTypes;
6322 if (param_types == null || param_types.Length != ParameterTypes.Length)
6325 for (int i = 0; i < param_types.Length; i++)
6326 if (param_types [i] != ParameterTypes [i])
6329 Report.SymbolRelatedToPreviousError (method);
6330 Report.Error (82, Location, "A member `{0}' is already reserved",
6331 method.GetSignatureForError ());
6335 public override bool IsUsed
6345 public new Location Location {
6347 return base.Location;
6351 public virtual bool ResolveMembers ()
6357 // Represents header string for documentation comment.
6359 public override string DocCommentHeader {
6360 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6363 void IMethodData.EmitExtraSymbolInfo ()
6368 // Properties and Indexers both generate PropertyBuilders, we use this to share
6369 // their common bits.
6371 abstract public class PropertyBase : PropertyBasedMember {
6373 public class GetMethod : PropertyMethod
6375 static string[] attribute_targets = new string [] { "method", "return" };
6377 public GetMethod (PropertyBase method):
6378 base (method, "get_")
6382 public GetMethod (PropertyBase method, Accessor accessor):
6383 base (method, accessor, "get_")
6387 public override MethodBuilder Define (DeclSpace parent)
6389 if (!CheckForDuplications ())
6395 base.Define (parent);
6397 method_data = new MethodData (method, ModFlags, flags, this);
6399 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6402 return method_data.MethodBuilder;
6405 public override Type ReturnType {
6407 return method.MemberType;
6411 public override Parameters ParameterInfo {
6413 return Parameters.EmptyReadOnlyParameters;
6417 public override string[] ValidAttributeTargets {
6419 return attribute_targets;
6424 public class SetMethod : PropertyMethod {
6426 static string[] attribute_targets = new string [] { "method", "param", "return" };
6427 ImplicitParameter param_attr;
6428 protected Parameters parameters;
6430 public SetMethod (PropertyBase method):
6431 base (method, "set_")
6435 public SetMethod (PropertyBase method, Accessor accessor):
6436 base (method, accessor, "set_")
6440 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6442 if (a.Target == AttributeTargets.Parameter) {
6443 if (param_attr == null)
6444 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6446 param_attr.ApplyAttributeBuilder (a, cb);
6450 base.ApplyAttributeBuilder (a, cb);
6453 public override Parameters ParameterInfo {
6455 if (parameters == null)
6456 DefineParameters ();
6461 protected virtual void DefineParameters ()
6463 parameters = Parameters.CreateFullyResolved (
6464 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6467 public override MethodBuilder Define (DeclSpace parent)
6469 if (!CheckForDuplications ())
6475 base.Define (parent);
6477 method_data = new MethodData (method, ModFlags, flags, this);
6479 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6482 return method_data.MethodBuilder;
6485 public override Type ReturnType {
6487 return TypeManager.void_type;
6491 public override string[] ValidAttributeTargets {
6493 return attribute_targets;
6498 static string[] attribute_targets = new string [] { "property" };
6500 public abstract class PropertyMethod : AbstractPropertyEventMethod
6502 protected readonly PropertyBase method;
6503 protected MethodAttributes flags;
6505 ArrayList anonymous_methods;
6508 public PropertyMethod (PropertyBase method, string prefix)
6509 : base (method, prefix)
6511 this.method = method;
6514 public PropertyMethod (PropertyBase method, Accessor accessor,
6516 : base (method, accessor, prefix)
6518 this.method = method;
6519 this.ModFlags = accessor.ModFlags;
6520 yields = accessor.Yields;
6521 anonymous_methods = accessor.AnonymousMethods;
6523 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6524 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6528 public override Iterator Iterator {
6529 get { return iterator; }
6532 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6534 if (a.IsInternalMethodImplAttribute) {
6535 method.is_external_implementation = true;
6538 base.ApplyAttributeBuilder (a, cb);
6541 public override AttributeTargets AttributeTargets {
6543 return AttributeTargets.Method;
6547 public override bool IsClsComplianceRequired ()
6549 return method.IsClsComplianceRequired ();
6552 public override bool ResolveMembers ()
6555 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6556 if (iterator == null)
6560 if (anonymous_methods != null) {
6561 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6562 if (!ame.CreateAnonymousHelpers ())
6570 public virtual MethodBuilder Define (DeclSpace parent)
6572 TypeContainer container = parent.PartialContainer;
6575 // Check for custom access modifier
6577 if ((ModFlags & Modifiers.Accessibility) == 0) {
6578 ModFlags |= method.ModFlags;
6579 flags = method.flags;
6581 if (container.Kind == Kind.Interface)
6582 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6583 GetSignatureForError ());
6585 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6586 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6589 CheckModifiers (ModFlags);
6590 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6591 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6592 flags = Modifiers.MethodAttr (ModFlags);
6593 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6596 CheckAbstractAndExtern (block != null);
6600 public bool HasCustomAccessModifier
6603 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6607 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6609 return new EmitContext (method,
6610 ds, method.ds, method.Location, ig, ReturnType,
6611 method.ModFlags, false);
6614 public override ObsoleteAttribute GetObsoleteAttribute ()
6616 return method.GetObsoleteAttribute ();
6619 public override string GetSignatureForError()
6621 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6624 void CheckModifiers (int modflags)
6626 modflags &= Modifiers.Accessibility;
6628 int mflags = method.ModFlags & Modifiers.Accessibility;
6630 if ((mflags & Modifiers.PUBLIC) != 0) {
6631 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6633 else if ((mflags & Modifiers.PROTECTED) != 0) {
6634 if ((mflags & Modifiers.INTERNAL) != 0)
6635 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6637 flags |= Modifiers.PRIVATE;
6639 else if ((mflags & Modifiers.INTERNAL) != 0)
6640 flags |= Modifiers.PRIVATE;
6642 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6643 Report.Error (273, Location,
6644 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6645 GetSignatureForError (), method.GetSignatureForError ());
6649 protected bool CheckForDuplications ()
6651 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6654 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6658 public PropertyMethod Get, Set;
6659 public PropertyBuilder PropertyBuilder;
6660 public MethodBuilder GetBuilder, SetBuilder;
6662 protected bool define_set_first = false;
6664 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6665 int allowed_mod, bool is_iface, MemberName name,
6666 Attributes attrs, bool define_set_first)
6667 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6669 this.define_set_first = define_set_first;
6672 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6674 if (a.HasSecurityAttribute) {
6675 a.Error_InvalidSecurityParent ();
6679 PropertyBuilder.SetCustomAttribute (cb);
6682 public override AttributeTargets AttributeTargets {
6684 return AttributeTargets.Property;
6688 public override bool Define ()
6693 if (!IsTypePermitted ())
6699 protected override bool DoDefine ()
6701 if (!base.DoDefine ())
6705 // Accessors modifiers check
6707 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6708 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6709 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6710 GetSignatureForError ());
6714 if ((Get.IsDummy || Set.IsDummy)
6715 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6716 Report.Error (276, Location,
6717 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6718 GetSignatureForError ());
6723 if (MemberType.IsGenericParameter)
6727 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6728 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6737 GetBuilder = Get.Define (Parent);
6738 return (Get.IsDummy) ? true : GetBuilder != null;
6741 bool DefineSet (bool define)
6746 SetBuilder = Set.Define (Parent);
6747 return (Set.IsDummy) ? true : SetBuilder != null;
6750 protected bool DefineAccessors ()
6752 return DefineSet (define_set_first) &&
6754 DefineSet (!define_set_first);
6757 protected abstract PropertyInfo ResolveBaseProperty ();
6759 // TODO: rename to Resolve......
6760 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6762 PropertyInfo base_property = ResolveBaseProperty ();
6763 if (base_property == null)
6766 base_ret_type = base_property.PropertyType;
6767 MethodInfo get_accessor = base_property.GetGetMethod (true);
6768 MethodInfo set_accessor = base_property.GetSetMethod (true);
6769 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6771 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6772 if (Get != null && !Get.IsDummy && get_accessor == null) {
6773 Report.SymbolRelatedToPreviousError (base_property);
6774 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6777 if (Set != null && !Set.IsDummy && set_accessor == null) {
6778 Report.SymbolRelatedToPreviousError (base_property);
6779 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6783 // Check base class accessors access
6786 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6787 get_accessor_access = set_accessor_access = 0;
6788 if ((ModFlags & Modifiers.NEW) == 0) {
6789 if (get_accessor != null) {
6790 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6791 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6793 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6794 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6797 if (set_accessor != null) {
6798 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6799 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6801 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6802 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6807 // When one accessor does not exist and property hides base one
6808 // we need to propagate this upwards
6809 if (set_accessor == null)
6810 set_accessor = get_accessor;
6813 // Get the less restrictive access
6815 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6818 public override void Emit ()
6821 // The PropertyBuilder can be null for explicit implementations, in that
6822 // case, we do not actually emit the ".property", so there is nowhere to
6823 // put the attribute
6825 if (PropertyBuilder != null && OptAttributes != null)
6826 OptAttributes.Emit ();
6838 /// Tests whether accessors are not in collision with some method (CS0111)
6840 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6842 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6845 public override bool IsUsed
6851 return Get.IsUsed | Set.IsUsed;
6855 protected override void SetMemberName (MemberName new_name)
6857 base.SetMemberName (new_name);
6859 Get.UpdateName (this);
6860 Set.UpdateName (this);
6863 public override string[] ValidAttributeTargets {
6865 return attribute_targets;
6870 // Represents header string for documentation comment.
6872 public override string DocCommentHeader {
6873 get { return "P:"; }
6877 public class Property : PropertyBase {
6878 const int AllowedModifiers =
6881 Modifiers.PROTECTED |
6882 Modifiers.INTERNAL |
6886 Modifiers.OVERRIDE |
6887 Modifiers.ABSTRACT |
6890 Modifiers.METHOD_YIELDS |
6893 const int AllowedInterfaceModifiers =
6896 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6899 Field field = new Field (
6901 Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6902 "<" + Name + ">k__BackingField", null, Location);
6903 ((TypeContainer)Parent).AddField (field);
6906 get_block.Block = new ToplevelBlock (block, null, Location);
6907 Return r = new Return (new SimpleName(field.Name, Location), Location);
6908 get_block.Block.AddStatement (r);
6909 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6912 Parameters parameters = new Parameters (new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location));
6913 set_block.Block = new ToplevelBlock (block, parameters, Location);
6914 Assign a = new Assign (new SimpleName(field.Name, Location), new SimpleName ("value", Location));
6915 set_block.Block.AddStatement (new StatementExpression(a));
6916 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6919 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6920 MemberName name, Attributes attrs, Accessor get_block,
6921 Accessor set_block, bool define_set_first)
6922 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6923 define_set_first, null)
6927 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6928 MemberName name, Attributes attrs, Accessor get_block,
6929 Accessor set_block, bool define_set_first, Block current_block)
6930 : base (parent, type, mod,
6931 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6932 is_iface, name, attrs, define_set_first)
6934 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6935 get_block != null && get_block.Block == null &&
6936 set_block != null && set_block.Block == null) {
6937 if (RootContext.Version <= LanguageVersion.ISO_2)
6938 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6940 CreateAutomaticProperty (current_block, get_block, set_block);
6943 if (get_block == null)
6944 Get = new GetMethod (this);
6946 Get = new GetMethod (this, get_block);
6948 if (set_block == null)
6949 Set = new SetMethod (this);
6951 Set = new SetMethod (this, set_block);
6954 public override bool Define ()
6956 if (!DoDefineBase ())
6959 if (!base.Define ())
6965 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6967 if (!DefineAccessors ())
6970 // FIXME - PropertyAttributes.HasDefault ?
6972 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6973 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6976 PropertyBuilder.SetGetMethod (GetBuilder);
6977 Parent.MemberCache.AddMember (GetBuilder, Get);
6981 PropertyBuilder.SetSetMethod (SetBuilder);
6982 Parent.MemberCache.AddMember (SetBuilder, Set);
6985 TypeManager.RegisterProperty (PropertyBuilder, this);
6986 Parent.MemberCache.AddMember (PropertyBuilder, this);
6990 protected override PropertyInfo ResolveBaseProperty ()
6992 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6993 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6998 /// Gigantic workaround for lameness in SRE follows :
6999 /// This class derives from EventInfo and attempts to basically
7000 /// wrap around the EventBuilder so that FindMembers can quickly
7001 /// return this in it search for members
7003 public class MyEventBuilder : EventInfo {
7006 // We use this to "point" to our Builder which is
7007 // not really a MemberInfo
7009 EventBuilder MyBuilder;
7012 // We "catch" and wrap these methods
7014 MethodInfo raise, remove, add;
7016 EventAttributes attributes;
7017 Type declaring_type, reflected_type, event_type;
7022 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7024 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7026 // And now store the values in our own fields.
7028 declaring_type = type_builder;
7030 reflected_type = type_builder;
7032 attributes = event_attr;
7035 this.event_type = event_type;
7039 // Methods that you have to override. Note that you only need
7040 // to "implement" the variants that take the argument (those are
7041 // the "abstract" methods, the others (GetAddMethod()) are
7044 public override MethodInfo GetAddMethod (bool nonPublic)
7049 public override MethodInfo GetRemoveMethod (bool nonPublic)
7054 public override MethodInfo GetRaiseMethod (bool nonPublic)
7060 // These methods make "MyEventInfo" look like a Builder
7062 public void SetRaiseMethod (MethodBuilder raiseMethod)
7064 raise = raiseMethod;
7065 MyBuilder.SetRaiseMethod (raiseMethod);
7068 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7070 remove = removeMethod;
7071 MyBuilder.SetRemoveOnMethod (removeMethod);
7074 public void SetAddOnMethod (MethodBuilder addMethod)
7077 MyBuilder.SetAddOnMethod (addMethod);
7080 public void SetCustomAttribute (CustomAttributeBuilder cb)
7082 MyBuilder.SetCustomAttribute (cb);
7085 public override object [] GetCustomAttributes (bool inherit)
7087 // FIXME : There's nothing which can be seemingly done here because
7088 // we have no way of getting at the custom attribute objects of the
7093 public override object [] GetCustomAttributes (Type t, bool inherit)
7095 // FIXME : Same here !
7099 public override bool IsDefined (Type t, bool b)
7104 public override EventAttributes Attributes {
7110 public override string Name {
7116 public override Type DeclaringType {
7118 return declaring_type;
7122 public override Type ReflectedType {
7124 return reflected_type;
7128 public Type EventType {
7134 public void SetUsed ()
7136 if (my_event != null) {
7137 // my_event.SetAssigned ();
7138 my_event.SetMemberIsUsed ();
7144 /// For case when event is declared like property (with add and remove accessors).
7146 public class EventProperty: Event {
7147 abstract class AEventPropertyAccessor : AEventAccessor
7149 readonly ArrayList anonymous_methods;
7151 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7152 base (method, accessor, prefix)
7154 this.anonymous_methods = accessor.AnonymousMethods;
7157 public override MethodBuilder Define (DeclSpace ds)
7159 CheckAbstractAndExtern (block != null);
7160 return base.Define (ds);
7163 public override string GetSignatureForError ()
7165 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7168 public override bool ResolveMembers ()
7170 if (anonymous_methods == null)
7173 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7174 if (!ame.CreateAnonymousHelpers ())
7183 sealed class AddDelegateMethod: AEventPropertyAccessor
7185 public AddDelegateMethod (Event method, Accessor accessor):
7186 base (method, accessor, "add_")
7190 protected override MethodInfo DelegateMethodInfo {
7192 return TypeManager.delegate_combine_delegate_delegate;
7197 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7199 public RemoveDelegateMethod (Event method, Accessor accessor):
7200 base (method, accessor, "remove_")
7204 protected override MethodInfo DelegateMethodInfo {
7206 return TypeManager.delegate_remove_delegate_delegate;
7212 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7214 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
7215 bool is_iface, MemberName name,
7216 Attributes attrs, Accessor add, Accessor remove)
7217 : base (parent, type, mod_flags, is_iface, name, attrs)
7219 Add = new AddDelegateMethod (this, add);
7220 Remove = new RemoveDelegateMethod (this, remove);
7223 public override bool Define()
7225 if (!base.Define ())
7232 public override string[] ValidAttributeTargets {
7234 return attribute_targets;
7240 /// Event is declared like field.
7242 public class EventField : Event {
7243 abstract class EventFieldAccessor : AEventAccessor
7245 protected EventFieldAccessor (Event method, string prefix)
7246 : base (method, prefix)
7250 protected override void EmitMethod(DeclSpace parent)
7252 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7255 MethodBuilder mb = method_data.MethodBuilder;
7256 ILGenerator ig = mb.GetILGenerator ();
7258 // TODO: because we cannot use generics yet
7259 FieldInfo field_info = ((EventField)method).FieldBuilder;
7261 if (parent is Class) {
7262 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7265 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7266 ig.Emit (OpCodes.Ldsfld, field_info);
7267 ig.Emit (OpCodes.Ldarg_0);
7268 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7269 ig.Emit (OpCodes.Castclass, method.MemberType);
7270 ig.Emit (OpCodes.Stsfld, field_info);
7272 ig.Emit (OpCodes.Ldarg_0);
7273 ig.Emit (OpCodes.Ldarg_0);
7274 ig.Emit (OpCodes.Ldfld, field_info);
7275 ig.Emit (OpCodes.Ldarg_1);
7276 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7277 ig.Emit (OpCodes.Castclass, method.MemberType);
7278 ig.Emit (OpCodes.Stfld, field_info);
7280 ig.Emit (OpCodes.Ret);
7284 sealed class AddDelegateMethod: EventFieldAccessor
7286 public AddDelegateMethod (Event method):
7287 base (method, "add_")
7291 protected override MethodInfo DelegateMethodInfo {
7293 return TypeManager.delegate_combine_delegate_delegate;
7298 sealed class RemoveDelegateMethod: EventFieldAccessor
7300 public RemoveDelegateMethod (Event method):
7301 base (method, "remove_")
7305 protected override MethodInfo DelegateMethodInfo {
7307 return TypeManager.delegate_remove_delegate_delegate;
7313 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7314 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7316 public FieldBuilder FieldBuilder;
7317 public Expression Initializer;
7319 public EventField (DeclSpace parent, Expression type, int mod_flags,
7320 bool is_iface, MemberName name,
7322 : base (parent, type, mod_flags, is_iface, name, attrs)
7324 Add = new AddDelegateMethod (this);
7325 Remove = new RemoveDelegateMethod (this);
7328 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7330 if (a.Target == AttributeTargets.Field) {
7331 FieldBuilder.SetCustomAttribute (cb);
7335 if (a.Target == AttributeTargets.Method) {
7336 int errors = Report.Errors;
7337 Add.ApplyAttributeBuilder (a, cb);
7338 if (errors == Report.Errors)
7339 Remove.ApplyAttributeBuilder (a, cb);
7343 base.ApplyAttributeBuilder (a, cb);
7346 public override bool Define()
7348 if (!base.Define ())
7354 // FIXME: We are unable to detect whether generic event is used because
7355 // we are using FieldExpr instead of EventExpr for event access in that
7356 // case. When this issue will be fixed this hack can be removed.
7357 if (TypeManager.IsGenericType (MemberType))
7360 if (Add.IsInterfaceImplementation)
7363 FieldBuilder = Parent.TypeBuilder.DefineField (
7365 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7366 TypeManager.RegisterEventField (EventBuilder, this);
7368 if (Initializer != null) {
7369 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7370 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7371 GetSignatureForError ());
7375 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7376 new FieldInitializer (FieldBuilder, Initializer));
7382 public override string[] ValidAttributeTargets
7385 return IsInterface ? attribute_targets_interface : attribute_targets;
7390 public abstract class Event : PropertyBasedMember {
7391 public abstract class AEventAccessor : AbstractPropertyEventMethod
7393 protected readonly Event method;
7394 ImplicitParameter param_attr;
7396 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7398 protected AEventAccessor (Event method, string prefix)
7399 : base (method, prefix)
7401 this.method = method;
7402 this.ModFlags = method.ModFlags;
7405 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7406 : base (method, accessor, prefix)
7408 this.method = method;
7409 this.ModFlags = method.ModFlags;
7412 public override Iterator Iterator {
7413 get { return null; }
7416 public bool IsInterfaceImplementation {
7417 get { return method_data.implementing != null; }
7420 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7422 if (a.IsInternalMethodImplAttribute) {
7423 method.is_external_implementation = true;
7426 base.ApplyAttributeBuilder (a, cb);
7429 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7431 if (a.Target == AttributeTargets.Parameter) {
7432 if (param_attr == null)
7433 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7435 param_attr.ApplyAttributeBuilder (a, cb);
7439 base.ApplyAttributeBuilder (a, cb);
7442 public override AttributeTargets AttributeTargets {
7444 return AttributeTargets.Method;
7448 public override bool IsClsComplianceRequired ()
7450 return method.IsClsComplianceRequired ();
7453 public virtual MethodBuilder Define (DeclSpace parent)
7455 method_data = new MethodData (method, method.ModFlags,
7456 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7458 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7461 MethodBuilder mb = method_data.MethodBuilder;
7462 ParameterInfo.ApplyAttributes (mb);
7466 protected abstract MethodInfo DelegateMethodInfo { get; }
7468 public override Type ReturnType {
7470 return TypeManager.void_type;
7474 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7476 return new EmitContext (
7477 ds, method.Parent, Location, ig, ReturnType,
7478 method.ModFlags, false);
7481 public override ObsoleteAttribute GetObsoleteAttribute ()
7483 return method.GetObsoleteAttribute ();
7486 public override string[] ValidAttributeTargets {
7488 return attribute_targets;
7492 public override Parameters ParameterInfo {
7494 return method.parameters;
7500 const int AllowedModifiers =
7503 Modifiers.PROTECTED |
7504 Modifiers.INTERNAL |
7509 Modifiers.OVERRIDE |
7511 Modifiers.ABSTRACT |
7514 const int AllowedInterfaceModifiers =
7517 public AEventAccessor Add, Remove;
7518 public MyEventBuilder EventBuilder;
7519 public MethodBuilder AddBuilder, RemoveBuilder;
7521 Parameters parameters;
7523 protected Event (DeclSpace parent, Expression type, int mod_flags,
7524 bool is_iface, MemberName name, Attributes attrs)
7525 : base (parent, null, type, mod_flags,
7526 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7531 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7533 if ((a.HasSecurityAttribute)) {
7534 a.Error_InvalidSecurityParent ();
7538 EventBuilder.SetCustomAttribute (cb);
7541 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7543 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7546 public override AttributeTargets AttributeTargets {
7548 return AttributeTargets.Event;
7552 public override bool Define ()
7554 if (!DoDefineBase ())
7560 if (!TypeManager.IsDelegateType (MemberType)) {
7561 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7565 parameters = Parameters.CreateFullyResolved (
7566 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7571 if (TypeManager.delegate_combine_delegate_delegate == null) {
7572 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7573 TypeManager.delegate_type, "Combine", Location,
7574 TypeManager.delegate_type, TypeManager.delegate_type);
7576 if (TypeManager.delegate_remove_delegate_delegate == null) {
7577 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7578 TypeManager.delegate_type, "Remove", Location,
7579 TypeManager.delegate_type, TypeManager.delegate_type);
7583 // Now define the accessors
7586 AddBuilder = Add.Define (Parent);
7587 if (AddBuilder == null)
7590 RemoveBuilder = Remove.Define (Parent);
7591 if (RemoveBuilder == null)
7594 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7595 EventBuilder.SetAddOnMethod (AddBuilder);
7596 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7598 Parent.MemberCache.AddMember (EventBuilder, this);
7599 Parent.MemberCache.AddMember (AddBuilder, Add);
7600 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7605 public override void Emit ()
7607 if (OptAttributes != null) {
7608 OptAttributes.Emit ();
7612 Remove.Emit (Parent);
7617 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7619 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7620 Parent.TypeBuilder, Name);
7625 ParameterData pd = TypeManager.GetParameterData (mi);
7626 base_ret_type = pd.ParameterType (0);
7631 // Represents header string for documentation comment.
7633 public override string DocCommentHeader {
7634 get { return "E:"; }
7639 public class Indexer : PropertyBase
7641 class GetIndexerMethod : GetMethod
7643 public GetIndexerMethod (PropertyBase method):
7648 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7649 base (method, accessor)
7653 public override bool EnableOverloadChecks (MemberCore overload)
7655 if (base.EnableOverloadChecks (overload)) {
7656 overload.caching_flags |= Flags.MethodOverloadsExist;
7663 public override Parameters ParameterInfo {
7665 return ((Indexer)method).parameters;
7670 class SetIndexerMethod: SetMethod
7672 public SetIndexerMethod (PropertyBase method):
7677 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7678 base (method, accessor)
7682 protected override void DefineParameters ()
7684 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7685 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7688 public override bool EnableOverloadChecks (MemberCore overload)
7690 if (base.EnableOverloadChecks (overload)) {
7691 overload.caching_flags |= Flags.MethodOverloadsExist;
7699 const int AllowedModifiers =
7702 Modifiers.PROTECTED |
7703 Modifiers.INTERNAL |
7707 Modifiers.OVERRIDE |
7712 const int AllowedInterfaceModifiers =
7715 public readonly Parameters parameters;
7717 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7718 bool is_iface, Parameters parameters, Attributes attrs,
7719 Accessor get_block, Accessor set_block, bool define_set_first)
7720 : base (parent, type, mod,
7721 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7722 is_iface, name, attrs, define_set_first)
7724 if (type == TypeManager.system_void_expr)
7725 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7727 this.parameters = parameters;
7729 if (get_block == null)
7730 Get = new GetIndexerMethod (this);
7732 Get = new GetIndexerMethod (this, get_block);
7734 if (set_block == null)
7735 Set = new SetIndexerMethod (this);
7737 Set = new SetIndexerMethod (this, set_block);
7740 public override bool Define ()
7742 if (!DoDefineBase ())
7745 if (!base.Define ())
7748 if (!DefineParameters (parameters))
7751 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7752 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7753 if (indexer_attr != null) {
7754 // Remove the attribute from the list because it is not emitted
7755 OptAttributes.Attrs.Remove (indexer_attr);
7757 string name = indexer_attr.GetIndexerAttributeValue ();
7763 if (IsExplicitImpl) {
7764 Report.Error (415, indexer_attr.Location,
7765 "The `IndexerName' attribute is valid only on an " +
7766 "indexer that is not an explicit interface member declaration");
7770 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7771 Report.Error (609, indexer_attr.Location,
7772 "Cannot set the `IndexerName' attribute on an indexer marked override");
7778 if (InterfaceType != null) {
7779 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7780 if (base_IndexerName != Name)
7781 ShortName = base_IndexerName;
7784 if (!Parent.PartialContainer.AddMember (this) ||
7785 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7792 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7793 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7797 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7799 if (!DefineAccessors ())
7803 // Setup iterator if we are one
7804 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7805 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7806 if (iterator == null)
7812 // Now name the parameters
7814 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7815 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7818 PropertyBuilder.SetGetMethod (GetBuilder);
7819 Parent.MemberCache.AddMember (GetBuilder, Get);
7823 PropertyBuilder.SetSetMethod (SetBuilder);
7824 Parent.MemberCache.AddMember (SetBuilder, Set);
7827 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7828 Parent.MemberCache.AddMember (PropertyBuilder, this);
7832 public override bool EnableOverloadChecks (MemberCore overload)
7834 if (overload is Indexer) {
7835 caching_flags |= Flags.MethodOverloadsExist;
7842 public override string GetDocCommentName (DeclSpace ds)
7844 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7847 public override string GetSignatureForError ()
7849 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7850 if (MemberName.Left != null) {
7852 sb.Append (MemberName.Left.GetSignatureForError ());
7855 sb.Append (".this");
7856 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7857 return sb.ToString ();
7860 protected override PropertyInfo ResolveBaseProperty ()
7862 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7863 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7866 protected override bool VerifyClsCompliance ()
7868 if (!base.VerifyClsCompliance ())
7871 parameters.VerifyClsCompliance ();
7876 public class Operator : MethodOrOperator, IAnonymousHost {
7878 const int AllowedModifiers =
7884 public enum OpType : byte {
7894 // Unary and Binary operators
7917 // Implicit and Explicit
7921 // Just because of enum
7925 public readonly OpType OperatorType;
7927 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7928 int mod_flags, Parameters parameters,
7929 ToplevelBlock block, Attributes attrs, Location loc)
7930 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7931 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7933 OperatorType = type;
7937 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7939 if (a.Type == TypeManager.conditional_attribute_type) {
7940 Error_ConditionalAttributeIsNotValid ();
7944 base.ApplyAttributeBuilder (a, cb);
7947 public override bool Define ()
7949 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7950 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7951 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7955 if (!base.Define ())
7958 // imlicit and explicit operator of same types are not allowed
7959 if (OperatorType == OpType.Explicit)
7960 Parent.MemberCache.CheckExistingMembersOverloads (this, "op_Implicit", Parameters);
7961 else if (OperatorType == OpType.Implicit)
7962 Parent.MemberCache.CheckExistingMembersOverloads (this, "op_Explicit", Parameters);
7964 if (MemberType == TypeManager.void_type) {
7965 Report.Error (590, Location, "User-defined operators cannot return void");
7969 Type declaring_type = MethodData.DeclaringType;
7970 Type return_type = MemberType;
7971 Type first_arg_type = ParameterTypes [0];
7973 Type first_arg_type_unwrap = first_arg_type;
7974 if (TypeManager.IsNullableType (first_arg_type))
7975 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7977 Type return_type_unwrap = return_type;
7978 if (TypeManager.IsNullableType (return_type))
7979 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7982 // Rules for conversion operators
7984 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7985 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7986 Report.Error (555, Location,
7987 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7992 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7993 conv_type = first_arg_type;
7994 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7995 conv_type = return_type;
7997 Report.Error (556, Location,
7998 "User-defined conversion must convert to or from the enclosing type");
8003 // Because IsInterface and IsClass are not supported
8005 if (!TypeManager.IsGenericParameter (conv_type)) {
8006 if (conv_type.IsInterface) {
8007 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8008 GetSignatureForError ());
8012 if (conv_type.IsClass) {
8013 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
8014 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
8015 GetSignatureForError ());
8019 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
8020 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
8021 GetSignatureForError ());
8026 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8027 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8028 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");
8031 } else if (Parameters.Count == 1) {
8032 // Checks for Unary operators
8034 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8035 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8036 Report.Error (448, Location,
8037 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8040 if (first_arg_type != declaring_type) {
8042 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8047 if (first_arg_type != declaring_type){
8050 "The parameter of a unary operator must be the " +
8055 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8056 if (return_type != TypeManager.bool_type){
8059 "The return type of operator True or False " +
8066 // Checks for Binary operators
8068 if (first_arg_type != declaring_type &&
8069 ParameterTypes [1] != declaring_type){
8072 "One of the parameters of a binary operator must " +
8073 "be the containing type");
8081 protected override bool DoDefine ()
8083 if (!base.DoDefine ())
8086 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8090 public override void Emit ()
8094 Parameters.ApplyAttributes (MethodBuilder);
8097 // abstract or extern methods have no bodies
8099 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8103 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8104 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8106 ec = CreateEmitContext (Parent, null);
8108 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8109 ec.EmitTopBlock (this, Block);
8112 source.CloseMethod ();
8117 // Operator cannot be override
8118 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8123 public static string GetName (OpType ot)
8126 case OpType.LogicalNot:
8128 case OpType.OnesComplement:
8130 case OpType.Increment:
8132 case OpType.Decrement:
8138 case OpType.Addition:
8140 case OpType.Subtraction:
8142 case OpType.UnaryPlus:
8144 case OpType.UnaryNegation:
8146 case OpType.Multiply:
8148 case OpType.Division:
8150 case OpType.Modulus:
8152 case OpType.BitwiseAnd:
8154 case OpType.BitwiseOr:
8156 case OpType.ExclusiveOr:
8158 case OpType.LeftShift:
8160 case OpType.RightShift:
8162 case OpType.Equality:
8164 case OpType.Inequality:
8166 case OpType.GreaterThan:
8168 case OpType.LessThan:
8170 case OpType.GreaterThanOrEqual:
8172 case OpType.LessThanOrEqual:
8174 case OpType.Implicit:
8176 case OpType.Explicit:
8182 public OpType GetMatchingOperator ()
8184 switch (OperatorType) {
8185 case OpType.Equality:
8186 return OpType.Inequality;
8187 case OpType.Inequality:
8188 return OpType.Equality;
8190 return OpType.False;
8193 case OpType.GreaterThan:
8194 return OpType.LessThan;
8195 case OpType.LessThan:
8196 return OpType.GreaterThan;
8197 case OpType.GreaterThanOrEqual:
8198 return OpType.LessThanOrEqual;
8199 case OpType.LessThanOrEqual:
8200 return OpType.GreaterThanOrEqual;
8206 public static OpType GetOperatorType (string name)
8208 if (name.StartsWith ("op_")){
8209 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8210 if (Unary.oper_names [i] == name)
8214 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8215 if (Binary.oper_names [i] == name)
8222 public override string GetSignatureForError ()
8224 StringBuilder sb = new StringBuilder ();
8225 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8226 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8229 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8232 sb.Append (Parameters.GetSignatureForError ());
8233 return sb.ToString ();
8238 // This is used to compare method signatures
8240 struct MethodSignature {
8242 public Type RetType;
8243 public Type [] Parameters;
8246 /// This delegate is used to extract methods which have the
8247 /// same signature as the argument
8249 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8251 public MethodSignature (string name, Type ret_type, Type [] parameters)
8256 if (parameters == null)
8257 Parameters = Type.EmptyTypes;
8259 Parameters = parameters;
8262 public override string ToString ()
8265 if (Parameters.Length != 0){
8266 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8267 for (int i = 0; i < Parameters.Length; i++){
8268 sb.Append (Parameters [i]);
8269 if (i+1 < Parameters.Length)
8272 pars = sb.ToString ();
8275 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8278 public override int GetHashCode ()
8280 return Name.GetHashCode ();
8283 public override bool Equals (Object o)
8285 MethodSignature other = (MethodSignature) o;
8287 if (other.Name != Name)
8290 if (other.RetType != RetType)
8293 if (Parameters == null){
8294 if (other.Parameters == null)
8299 if (other.Parameters == null)
8302 int c = Parameters.Length;
8303 if (other.Parameters.Length != c)
8306 for (int i = 0; i < c; i++)
8307 if (other.Parameters [i] != Parameters [i])
8313 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8315 MethodSignature sig = (MethodSignature) filter_criteria;
8317 if (m.Name != sig.Name)
8321 MethodInfo mi = m as MethodInfo;
8322 PropertyInfo pi = m as PropertyInfo;
8325 ReturnType = mi.ReturnType;
8326 else if (pi != null)
8327 ReturnType = pi.PropertyType;
8332 // we use sig.RetType == null to mean `do not check the
8333 // method return value.
8335 if (sig.RetType != null) {
8336 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8342 args = TypeManager.GetParameterData (mi).Types;
8344 args = TypeManager.GetArgumentTypes (pi);
8345 Type [] sigp = sig.Parameters;
8347 if (args.Length != sigp.Length)
8350 for (int i = args.Length - 1; i >= 0; i--)
8351 if (!TypeManager.IsEqual (args [i], sigp [i]))