2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
34 using System.Collections;
35 using System.Collections.Specialized;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Security;
41 using System.Security.Permissions;
44 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
45 using XmlElement = System.Object;
50 using Mono.CompilerServices.SymbolWriter;
52 namespace Mono.CSharp {
64 /// This is the base class for structs and classes.
66 public abstract class TypeContainer : DeclSpace, IMemberContainer {
68 public class MemberCoreArrayList: ArrayList
71 /// Defines the MemberCore objects that are in this array
73 public virtual void DefineContainerMembers ()
75 foreach (MemberCore mc in this) {
78 } catch (Exception e) {
79 throw new InternalErrorException (mc, e);
84 public virtual void Emit ()
86 foreach (MemberCore mc in this)
91 public class OperatorArrayList: MemberCoreArrayList
93 TypeContainer container;
95 public OperatorArrayList (TypeContainer container)
97 this.container = container;
101 // Checks that some operators come in pairs:
107 // They are matched based on the return type and the argument types
109 void CheckPairedOperators ()
111 bool has_equality_or_inequality = false;
112 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
113 bool [] has_pair = new bool [operators.Length];
115 for (int i = 0; i < Count; ++i) {
116 if (operators [i] == null)
119 Operator o_a = operators [i];
120 Operator.OpType o_type = o_a.OperatorType;
121 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
122 has_equality_or_inequality = true;
124 Operator.OpType matching_type = o_a.GetMatchingOperator ();
125 if (matching_type == Operator.OpType.TOP) {
126 operators [i] = null;
130 for (int ii = 0; ii < Count; ++ii) {
131 Operator o_b = operators [ii];
132 if (o_b == null || o_b.OperatorType != matching_type)
135 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
138 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
141 operators [i] = null;
144 // Used to ignore duplicate user conversions
146 has_pair [ii] = true;
150 for (int i = 0; i < Count; ++i) {
151 if (operators [i] == null || has_pair [i])
154 Operator o = operators [i];
155 Report.Error (216, o.Location,
156 "The operator `{0}' requires a matching operator `{1}' to also be defined",
157 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
160 if (has_equality_or_inequality && Report.WarningLevel > 2) {
161 if (container.Methods == null || !container.HasEquals)
162 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
164 if (container.Methods == null || !container.HasGetHashCode)
165 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
169 public override void DefineContainerMembers ()
171 base.DefineContainerMembers ();
172 CheckPairedOperators ();
180 GetHashCode = 1 << 1,
181 HasStaticFieldInitializer = 1 << 2
185 // Whether this is a struct, class or interface
186 public readonly Kind Kind;
188 // Holds a list of classes and structures
189 protected ArrayList types;
191 MemberCoreArrayList ordered_explicit_member_list;
192 MemberCoreArrayList ordered_member_list;
194 // Holds the list of properties
195 MemberCoreArrayList properties;
197 // Holds the list of delegates
198 MemberCoreArrayList delegates;
200 // Holds the list of constructors
201 protected MemberCoreArrayList instance_constructors;
203 // Holds the list of fields
204 MemberCoreArrayList fields;
206 // Holds a list of fields that have initializers
207 protected ArrayList initialized_fields;
209 // Holds a list of static fields that have initializers
210 protected ArrayList initialized_static_fields;
212 // Holds the list of constants
213 protected MemberCoreArrayList constants;
215 // Holds the methods.
216 MemberCoreArrayList methods;
219 protected MemberCoreArrayList events;
221 // Holds the indexers
224 // Holds the operators
225 MemberCoreArrayList operators;
227 // Holds the compiler generated classes
228 ArrayList compiler_generated;
231 // Pointers to the default constructor and the default static constructor
233 protected Constructor default_constructor;
234 protected Constructor default_static_constructor;
237 // Points to the first non-static field added to the container.
239 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
240 // and the first one's as good as any.
242 FieldBase first_nonstatic_field = null;
245 // This one is computed after we can distinguish interfaces
246 // from classes from the arraylist `type_bases'
249 TypeExpr[] iface_exprs;
252 protected ArrayList type_bases;
254 bool members_resolved;
255 bool members_resolved_ok;
256 bool members_defined;
257 bool members_defined_ok;
259 // The interfaces we implement.
260 protected Type[] ifaces;
262 // The base member cache and our member cache
263 MemberCache base_cache;
264 protected MemberCache member_cache;
266 public const string DefaultIndexerName = "Item";
268 private bool seen_normal_indexers = false;
269 private string indexer_name = DefaultIndexerName;
271 private CachedMethods cached_method;
273 ArrayList partial_parts;
276 /// The pending methods that need to be implemented
277 // (interfaces or abstract methods)
279 PendingImplementation pending;
281 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
282 Attributes attrs, Kind kind)
283 : base (ns, parent, name, attrs)
285 if (parent != null && parent.NamespaceEntry != ns)
286 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
289 this.PartialContainer = this;
292 public bool AddMember (MemberCore symbol)
294 return AddToContainer (symbol, symbol.MemberName.MethodName);
297 protected virtual bool AddMemberType (DeclSpace ds)
299 return AddToContainer (ds, ds.Basename);
302 public void AddConstant (Const constant)
304 if (!AddMember (constant))
307 if (constants == null)
308 constants = new MemberCoreArrayList ();
310 constants.Add (constant);
313 public TypeContainer AddTypeContainer (TypeContainer tc)
315 if (!AddMemberType (tc))
319 types = new MemberCoreArrayList ();
325 public virtual TypeContainer AddPartial (TypeContainer next_part)
327 return AddPartial (next_part, next_part.Basename);
330 protected TypeContainer AddPartial (TypeContainer next_part, string name)
332 next_part.ModFlags |= Modifiers.PARTIAL;
333 TypeContainer tc = defined_names [name] as TypeContainer;
336 return AddTypeContainer (next_part);
338 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
339 Report.SymbolRelatedToPreviousError (tc);
340 Error_MissingPartialModifier (next_part);
343 if (tc.Kind != next_part.Kind) {
344 Report.SymbolRelatedToPreviousError (tc);
345 Report.Error (261, next_part.Location,
346 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
347 next_part.GetSignatureForError ());
350 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
351 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
352 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
353 Report.SymbolRelatedToPreviousError (tc);
354 Report.Error (262, next_part.Location,
355 "Partial declarations of `{0}' have conflicting accessibility modifiers",
356 next_part.GetSignatureForError ());
359 if (tc.partial_parts == null)
360 tc.partial_parts = new ArrayList (1);
362 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
363 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
364 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
365 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
366 tc.ModFlags |= next_part.ModFlags;
368 tc.ModFlags |= next_part.ModFlags;
371 if (next_part.attributes != null) {
372 if (tc.attributes == null)
373 tc.attributes = next_part.attributes;
375 tc.attributes.AddAttributes (next_part.attributes.Attrs);
378 next_part.PartialContainer = tc;
379 tc.partial_parts.Add (next_part);
383 public void AddDelegate (Delegate d)
385 if (!AddMemberType (d))
388 if (delegates == null)
389 delegates = new MemberCoreArrayList ();
394 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
396 if (ordered_explicit_member_list == null) {
397 ordered_explicit_member_list = new MemberCoreArrayList ();
398 ordered_member_list = new MemberCoreArrayList ();
402 ordered_explicit_member_list.Add (mc);
403 alist.Insert (0, mc);
406 ordered_member_list.Add (mc);
412 public void AddMethod (Method method)
414 MemberName mn = method.MemberName;
415 if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
419 methods = new MemberCoreArrayList ();
421 if (method.MemberName.Left != null)
422 AddMemberToList (method, methods, true);
424 AddMemberToList (method, methods, false);
428 // Do not use this method: use AddMethod.
430 // This is only used by iterators.
432 public void AppendMethod (Method method)
434 if (!AddMember (method))
438 methods = new MemberCoreArrayList ();
440 AddMemberToList (method, methods, false);
443 public void AddConstructor (Constructor c)
445 if (c.Name != MemberName.Name) {
446 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
449 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
450 if (!AddToContainer (c, is_static ?
451 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
454 if (is_static && c.Parameters.Empty){
455 if (default_static_constructor != null) {
456 Report.SymbolRelatedToPreviousError (default_static_constructor);
457 Report.Error (111, c.Location,
458 "A member `{0}' is already defined. Rename this member or use different parameter types",
459 c.GetSignatureForError ());
463 default_static_constructor = c;
465 if (c.Parameters.Empty)
466 default_constructor = c;
468 if (instance_constructors == null)
469 instance_constructors = new MemberCoreArrayList ();
471 instance_constructors.Add (c);
475 public bool AddField (FieldBase field)
477 if (!AddMember (field))
481 fields = new MemberCoreArrayList ();
485 if ((field.ModFlags & Modifiers.STATIC) != 0)
488 if (first_nonstatic_field == null) {
489 first_nonstatic_field = field;
493 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
494 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
495 Report.Warning (282, 3, field.Location,
496 "struct instance field `{0}' found in different declaration from instance field `{1}'",
497 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
502 public void AddProperty (Property prop)
504 if (!AddMember (prop) ||
505 !AddMember (prop.Get) || !AddMember (prop.Set))
508 if (properties == null)
509 properties = new MemberCoreArrayList ();
511 if (prop.MemberName.Left != null)
512 AddMemberToList (prop, properties, true);
514 AddMemberToList (prop, properties, false);
517 public void AddEvent (Event e)
522 if (e is EventProperty) {
523 if (!AddMember (e.Add))
526 if (!AddMember (e.Remove))
531 events = new MemberCoreArrayList ();
537 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
539 public void AddIndexer (Indexer i)
541 if (indexers == null)
542 indexers = new ArrayList ();
544 if (i.IsExplicitImpl)
545 AddMemberToList (i, indexers, true);
547 AddMemberToList (i, indexers, false);
550 public void AddOperator (Operator op)
555 if (operators == null)
556 operators = new OperatorArrayList (this);
561 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
563 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
565 if (compiler_generated == null)
566 compiler_generated = new ArrayList ();
568 compiler_generated.Add (c);
571 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
573 if (a.Type == TypeManager.default_member_type) {
574 if (Indexers != null) {
575 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
580 base.ApplyAttributeBuilder (a, cb);
583 public override AttributeTargets AttributeTargets {
585 throw new NotSupportedException ();
589 public ArrayList Types {
595 public MemberCoreArrayList Methods {
601 public ArrayList Constants {
607 public ArrayList CompilerGenerated {
609 return compiler_generated;
613 protected Type BaseType {
615 return TypeBuilder.BaseType;
619 public ArrayList Fields {
625 public ArrayList InstanceConstructors {
627 return instance_constructors;
631 public ArrayList Properties {
637 public ArrayList Events {
643 public ArrayList Indexers {
649 public ArrayList Operators {
655 public ArrayList Delegates {
661 protected override TypeAttributes TypeAttr {
663 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
667 public string IndexerName {
669 return indexers == null ? DefaultIndexerName : indexer_name;
673 public bool IsComImport {
675 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
678 return OptAttributes.Contains (TypeManager.comimport_attr_type);
682 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
684 if ((field.ModFlags & Modifiers.STATIC) != 0){
685 if (initialized_static_fields == null) {
686 PartialContainer.HasStaticFieldInitializer = true;
687 initialized_static_fields = new ArrayList (4);
690 initialized_static_fields.Add (expression);
692 if (initialized_fields == null)
693 initialized_fields = new ArrayList (4);
695 initialized_fields.Add (expression);
699 public void ResolveFieldInitializers (EmitContext ec)
701 // Field initializers are tricky for partial classes. They have to
702 // share same costructor (block) but they have they own resolve scope.
703 DeclSpace orig = ec.DeclContainer;
705 if (partial_parts != null) {
706 foreach (TypeContainer part in partial_parts) {
707 ec.DeclContainer = part;
708 part.DoResolveFieldInitializers (ec);
711 ec.DeclContainer = PartialContainer;
712 DoResolveFieldInitializers (ec);
713 ec.DeclContainer = orig;
716 void DoResolveFieldInitializers (EmitContext ec)
719 if (initialized_static_fields == null)
722 bool has_complex_initializer = false;
723 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
724 foreach (FieldInitializer fi in initialized_static_fields) {
725 fi.ResolveStatement (ec);
726 if (!fi.IsComplexInitializer)
729 has_complex_initializer = true;
732 // Need special check to not optimize code like this
733 // static int a = b = 5;
735 if (!has_complex_initializer && RootContext.Optimize) {
736 for (int i = 0; i < initialized_static_fields.Count; ++i) {
737 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
738 if (fi.IsDefaultInitializer) {
739 initialized_static_fields.RemoveAt (i);
749 if (initialized_fields == null)
752 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
753 for (int i = 0; i < initialized_fields.Count; ++i) {
754 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
755 fi.ResolveStatement (ec);
756 if (fi.IsDefaultInitializer && RootContext.Optimize) {
757 // Field is re-initialized to its default value => removed
758 initialized_fields.RemoveAt (i);
766 // Emits the instance field initializers
768 public bool EmitFieldInitializers (EmitContext ec)
770 if (partial_parts != null) {
771 foreach (TypeContainer part in partial_parts)
772 part.EmitFieldInitializers (ec);
778 fields = initialized_static_fields;
780 fields = initialized_fields;
786 foreach (FieldInitializer f in fields) {
787 f.EmitStatement (ec);
792 public override string DocComment {
804 public PendingImplementation PendingImplementations {
805 get { return pending; }
808 public override bool GetClsCompliantAttributeValue ()
810 if (PartialContainer != this)
811 return PartialContainer.GetClsCompliantAttributeValue ();
813 return base.GetClsCompliantAttributeValue ();
816 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
818 // FIXME: get rid of partial_parts and store lists of bases of each part here
819 // assumed, not verified: 'part' is in 'partial_parts'
820 ((TypeContainer) part).type_bases = bases;
823 TypeExpr[] GetNormalBases (out TypeExpr base_class)
826 if (type_bases == null)
829 int count = type_bases.Count;
832 if (Kind == Kind.Class){
833 TypeExpr name = ((Expression) type_bases [0]).ResolveAsBaseTerminal (this, false);
839 if (!name.IsInterface) {
840 // base_class could be a class, struct, enum, delegate.
841 // This is validated in GetClassBases.
847 TypeExpr [] ifaces = new TypeExpr [count-start];
849 for (i = start, j = 0; i < count; i++, j++){
850 TypeExpr resolved = ((Expression) type_bases [i]).ResolveAsBaseTerminal (this, false);
851 if (resolved == null) {
855 ifaces [j] = resolved;
858 return ifaces.Length == 0 ? null : ifaces;
862 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
864 ArrayList ifaces = new ArrayList (0);
865 if (iface_exprs != null)
866 ifaces.AddRange (iface_exprs);
868 foreach (TypeContainer part in partial_parts) {
869 TypeExpr new_base_class;
870 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
871 if (new_base_class != TypeManager.system_object_expr) {
872 if (base_class == TypeManager.system_object_expr)
873 base_class = new_base_class;
875 if (new_base_class != null && !new_base_class.Equals (base_class)) {
876 Report.SymbolRelatedToPreviousError (base_class.Location, "");
877 Report.Error (263, part.Location,
878 "Partial declarations of `{0}' must not specify different base classes",
879 part.GetSignatureForError ());
886 if (new_ifaces == null)
889 foreach (TypeExpr iface in new_ifaces) {
890 if (ifaces.Contains (iface))
897 if (ifaces.Count == 0)
900 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
904 /// This function computes the Base class and also the
905 /// list of interfaces that the class or struct @c implements.
907 /// The return value is an array (might be null) of
908 /// interfaces implemented (as Types).
910 /// The @base_class argument is set to the base object or null
911 /// if this is `System.Object'.
913 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
915 TypeExpr[] ifaces = GetNormalBases (out base_class);
920 int count = ifaces.Length;
922 for (int i = 0; i < count; i++) {
923 TypeExpr iface = (TypeExpr) ifaces [i];
925 if (!iface.IsInterface) {
926 if (Kind != Kind.Class) {
927 // TODO: location of symbol related ....
928 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
930 else if (base_class != null)
931 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
932 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
934 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
935 GetSignatureForError (), iface.GetSignatureForError ());
940 for (int x = 0; x < i; x++) {
941 if (iface.Equals (ifaces [x])) {
942 Report.Error (528, Location,
943 "`{0}' is already listed in " +
944 "interface list", iface.GetSignatureForError ());
949 if ((Kind == Kind.Interface) &&
950 !iface.AsAccessible (this)) {
951 Report.Error (61, Location,
952 "Inconsistent accessibility: base " +
953 "interface `{0}' is less accessible " +
954 "than interface `{1}'", iface.GetSignatureForError (),
962 bool CheckGenericInterfaces (Type[] ifaces)
965 ArrayList already_checked = new ArrayList ();
967 for (int i = 0; i < ifaces.Length; i++) {
968 Type iface = ifaces [i];
969 foreach (Type t in already_checked) {
973 Type[] inferred = new Type [CountTypeParameters];
974 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
977 Report.Error (695, Location,
978 "`{0}' cannot implement both `{1}' and `{2}' " +
979 "because they may unify for some type parameter substitutions",
980 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
981 TypeManager.CSharpName (t));
985 already_checked.Add (iface);
994 protected void Error_TypeInListIsNotInterface (Location loc, string type)
996 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
999 bool CreateTypeBuilder ()
1002 Type default_parent = null;
1003 if (Kind == Kind.Struct)
1004 default_parent = TypeManager.value_type;
1005 else if (Kind == Kind.Enum)
1006 default_parent = TypeManager.enum_type;
1009 if (TypeManager.NamespaceClash (Name, Location)) {
1013 ModuleBuilder builder = CodeGen.Module.Builder;
1014 TypeBuilder = builder.DefineType (
1015 Name, TypeAttr, default_parent, null);
1017 TypeBuilder builder = Parent.TypeBuilder;
1019 TypeBuilder = builder.DefineNestedType (
1020 Basename, TypeAttr, default_parent, null);
1022 } catch (ArgumentException) {
1023 Report.RuntimeMissingSupport (Location, "static classes");
1027 TypeManager.AddUserType (this);
1031 string[] param_names = new string [TypeParameters.Length];
1032 for (int i = 0; i < TypeParameters.Length; i++)
1033 param_names [i] = TypeParameters [i].Name;
1035 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
1037 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1038 for (int i = offset; i < gen_params.Length; i++)
1039 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1046 bool DefineBaseTypes ()
1048 iface_exprs = GetClassBases (out base_type);
1049 if (partial_parts != null) {
1050 iface_exprs = GetNormalPartialBases (ref base_type);
1054 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1055 // which in turn should have called DefineType()s on base types if necessary.
1057 // None of the code below should trigger DefineType()s on classes that we depend on.
1058 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1060 // Let's do it as soon as possible, since code below can call DefineType() on classes
1061 // that depend on us to be populated before they are.
1063 if (!(this is CompilerGeneratedClass))
1064 RootContext.RegisterOrder (this);
1066 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1067 Report.Error (698, base_type.Location,
1068 "A generic type cannot derive from `{0}' because it is an attribute class",
1069 base_type.GetSignatureForError ());
1073 if (!CheckRecursiveDefinition (this))
1076 if (base_type != null && base_type.Type != null) {
1077 TypeBuilder.SetParent (base_type.Type);
1079 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1080 if (obsolete_attr != null && !IsInObsoleteScope)
1081 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1084 // add interfaces that were not added at type creation
1085 if (iface_exprs != null) {
1086 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1090 foreach (Type itype in ifaces)
1091 TypeBuilder.AddInterfaceImplementation (itype);
1093 foreach (TypeExpr ie in iface_exprs) {
1094 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1095 if ((oa != null) && !IsInObsoleteScope)
1096 AttributeTester.Report_ObsoleteMessage (
1097 oa, ie.GetSignatureForError (), Location);
1100 if (!CheckGenericInterfaces (ifaces))
1103 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1110 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1112 public TypeBuilder CreateType ()
1114 if (TypeBuilder != null)
1120 if (!CreateTypeBuilder ()) {
1125 if (partial_parts != null) {
1126 foreach (TypeContainer part in partial_parts)
1127 part.TypeBuilder = TypeBuilder;
1130 if (Types != null) {
1131 foreach (TypeContainer tc in Types) {
1132 if (tc.CreateType () == null) {
1144 public override TypeBuilder DefineType ()
1151 type_defined = true;
1153 if (CreateType () == null) {
1158 if (!DefineBaseTypes ()) {
1163 if (!(this is CompilerGeneratedClass)) {
1164 if (!ResolveMembers ()) {
1170 if (!DefineNestedTypes ()) {
1178 public bool ResolveMembers ()
1180 if (members_resolved)
1181 return members_resolved_ok;
1183 members_resolved_ok = DoResolveMembers ();
1184 members_resolved = true;
1186 return members_resolved_ok;
1189 protected virtual bool DoResolveMembers ()
1191 if (methods != null) {
1192 foreach (Method method in methods) {
1193 if (!method.ResolveMembers ())
1198 if (instance_constructors != null) {
1199 foreach (Constructor c in instance_constructors) {
1200 if (!c.ResolveMembers ())
1205 if (default_static_constructor != null) {
1206 if (!default_static_constructor.ResolveMembers ())
1210 if (operators != null) {
1211 foreach (Operator o in operators) {
1212 if (!o.ResolveMembers ())
1217 if (properties != null) {
1218 foreach (PropertyBase p in properties) {
1219 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1221 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1226 if (indexers != null) {
1227 foreach (PropertyBase p in indexers) {
1228 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1230 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1235 if (events != null) {
1236 foreach (Event e in events) {
1237 if (!e.Add.ResolveMembers ())
1239 if (!e.Remove.ResolveMembers ())
1244 if (compiler_generated != null) {
1245 foreach (CompilerGeneratedClass c in compiler_generated) {
1246 if (c.DefineType () == null)
1254 public override void SetParameterInfo (ArrayList constraints_list)
1256 base.SetParameterInfo (constraints_list);
1258 if (!is_generic || PartialContainer == this)
1261 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1262 for (int i = 0; i < tc_names.Length; ++i) {
1263 if (tc_names [i].Name != type_params [i].Name) {
1264 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1265 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1266 GetSignatureForError ());
1272 void UpdateTypeParameterConstraints (TypeContainer part)
1274 TypeParameter[] current_params = CurrentTypeParameters;
1275 for (int i = 0; i < current_params.Length; i++) {
1276 Constraints c = part.CurrentTypeParameters [i].Constraints;
1280 if (current_params [i].UpdateConstraints (part, c))
1283 Report.SymbolRelatedToPreviousError (Location, "");
1284 Report.Error (265, part.Location,
1285 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1286 GetSignatureForError (), current_params [i].GetSignatureForError ());
1290 public bool ResolveType ()
1292 if (!DoResolveType ())
1295 if (compiler_generated != null) {
1296 foreach (CompilerGeneratedClass c in compiler_generated)
1297 if (!c.ResolveType ())
1304 protected virtual bool DoResolveType ()
1306 if ((base_type != null) &&
1307 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1315 if (PartialContainer != this)
1316 throw new InternalErrorException ();
1318 TypeExpr current_type = null;
1320 foreach (TypeParameter type_param in CurrentTypeParameters) {
1321 if (!type_param.Resolve (this)) {
1327 if (partial_parts != null && is_generic) {
1328 foreach (TypeContainer part in partial_parts)
1329 UpdateTypeParameterConstraints (part);
1332 foreach (TypeParameter type_param in TypeParameters) {
1333 if (!type_param.DefineType (this)) {
1339 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1341 foreach (TypeParameter type_param in TypeParameters)
1342 if (!type_param.CheckDependencies ()) {
1347 if (current_type != null) {
1348 current_type = current_type.ResolveAsTypeTerminal (this, false);
1349 if (current_type == null) {
1354 CurrentType = current_type.Type;
1360 protected virtual bool DefineNestedTypes ()
1362 if (Types != null) {
1363 foreach (TypeContainer tc in Types)
1364 if (tc.DefineType () == null)
1368 if (Delegates != null) {
1369 foreach (Delegate d in Delegates)
1370 if (d.DefineType () == null)
1377 TypeContainer InTransit;
1379 protected bool CheckRecursiveDefinition (TypeContainer tc)
1381 if (InTransit != null) {
1382 Report.SymbolRelatedToPreviousError (this);
1383 if (this is Interface)
1385 529, tc.Location, "Inherited interface `{0}' causes a " +
1386 "cycle in the interface hierarchy of `{1}'",
1387 GetSignatureForError (), tc.GetSignatureForError ());
1390 146, tc.Location, "Circular base class dependency " +
1391 "involving `{0}' and `{1}'",
1392 tc.GetSignatureForError (), GetSignatureForError ());
1398 if (base_type != null && base_type.Type != null) {
1399 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1400 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1401 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1405 if (iface_exprs != null) {
1406 foreach (TypeExpr iface in iface_exprs) {
1407 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1408 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1409 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1414 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1421 public static void Error_KeywordNotAllowed (Location loc)
1423 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1427 /// Populates our TypeBuilder with fields and methods
1429 public override bool DefineMembers ()
1431 if (members_defined)
1432 return members_defined_ok;
1434 if (!base.DefineMembers ())
1437 members_defined_ok = DoDefineMembers ();
1438 members_defined = true;
1440 return members_defined_ok;
1443 protected virtual bool DoDefineMembers ()
1445 if (iface_exprs != null) {
1446 foreach (TypeExpr iface in iface_exprs) {
1447 ConstructedType ct = iface as ConstructedType;
1448 if ((ct != null) && !ct.CheckConstraints (this))
1453 if (base_type != null) {
1454 ConstructedType ct = base_type as ConstructedType;
1455 if ((ct != null) && !ct.CheckConstraints (this))
1458 member_cache = new MemberCache (base_type.Type, this);
1459 } else if (Kind == Kind.Interface) {
1460 member_cache = new MemberCache (null, this);
1461 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1462 for (int i = 0; i < ifaces.Length; ++i)
1463 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1465 member_cache = new MemberCache (null, this);
1469 foreach (TypeContainer tc in types)
1470 member_cache.AddNestedType (tc);
1472 if (delegates != null)
1473 foreach (Delegate d in delegates)
1474 member_cache.AddNestedType (d);
1476 if (partial_parts != null) {
1477 foreach (TypeContainer part in partial_parts)
1478 part.member_cache = member_cache;
1482 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1483 if (conflict_symbol == null) {
1484 if ((ModFlags & Modifiers.NEW) != 0)
1485 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1487 if ((ModFlags & Modifiers.NEW) == 0) {
1488 Report.SymbolRelatedToPreviousError (conflict_symbol);
1489 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1490 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1495 DefineContainerMembers (constants);
1496 DefineContainerMembers (fields);
1498 if (Kind == Kind.Struct || Kind == Kind.Class) {
1499 pending = PendingImplementation.GetPendingImplementations (this);
1503 // Constructors are not in the defined_names array
1505 DefineContainerMembers (instance_constructors);
1507 DefineContainerMembers (events);
1508 DefineContainerMembers (ordered_explicit_member_list);
1509 DefineContainerMembers (ordered_member_list);
1511 DefineContainerMembers (operators);
1512 DefineContainerMembers (delegates);
1514 ComputeIndexerName();
1515 CheckEqualsAndGetHashCode();
1517 if (CurrentType != null) {
1518 GenericType = CurrentType;
1523 // FIXME: This hack is needed because member cache does not work
1524 // with generic types, we rely on runtime to inflate dynamic types.
1525 // TODO: This hack requires member cache refactoring to be removed
1527 if (TypeBuilder.IsGenericType)
1528 member_cache = new MemberCache (this);
1534 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1537 mcal.DefineContainerMembers ();
1540 protected virtual void ComputeIndexerName ()
1542 if (indexers == null)
1545 string class_indexer_name = null;
1548 // If there's both an explicit and an implicit interface implementation, the
1549 // explicit one actually implements the interface while the other one is just
1550 // a normal indexer. See bug #37714.
1553 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1554 foreach (Indexer i in indexers) {
1555 if (i.InterfaceType != null) {
1556 if (seen_normal_indexers)
1557 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1561 seen_normal_indexers = true;
1563 if (class_indexer_name == null) {
1564 class_indexer_name = i.ShortName;
1568 if (i.ShortName != class_indexer_name)
1569 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");
1572 if (class_indexer_name != null)
1573 indexer_name = class_indexer_name;
1576 protected virtual void EmitIndexerName ()
1578 if (!seen_normal_indexers)
1581 if (TypeManager.default_member_ctor == null) {
1582 if (TypeManager.default_member_type == null) {
1583 TypeManager.default_member_type = TypeManager.CoreLookupType (
1584 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1586 if (TypeManager.default_member_type == null)
1590 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1591 TypeManager.default_member_type, Location, TypeManager.string_type);
1593 if (TypeManager.default_member_ctor == null)
1597 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1598 TypeBuilder.SetCustomAttribute (cb);
1601 protected virtual void CheckEqualsAndGetHashCode ()
1603 if (methods == null)
1606 if (HasEquals && !HasGetHashCode) {
1607 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1611 public override bool Define ()
1613 CheckProtectedModifier ();
1615 if (compiler_generated != null) {
1616 foreach (CompilerGeneratedClass c in compiler_generated) {
1625 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1627 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1631 /// This function is based by a delegate to the FindMembers routine
1633 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1639 /// This filter is used by FindMembers, and we just keep
1640 /// a global for the filter to `AlwaysAccept'
1642 static MemberFilter accepting_filter;
1645 static TypeContainer ()
1647 accepting_filter = new MemberFilter (AlwaysAccept);
1650 public MethodInfo[] GetMethods ()
1652 ArrayList members = new ArrayList ();
1656 if (methods != null) {
1657 int len = methods.Count;
1658 for (int i = 0; i < len; i++) {
1659 Method m = (Method) methods [i];
1661 members.Add (m.MethodBuilder);
1665 if (operators != null) {
1666 int len = operators.Count;
1667 for (int i = 0; i < len; i++) {
1668 Operator o = (Operator) operators [i];
1670 members.Add (o.MethodBuilder);
1674 if (properties != null) {
1675 int len = properties.Count;
1676 for (int i = 0; i < len; i++) {
1677 Property p = (Property) properties [i];
1679 if (p.GetBuilder != null)
1680 members.Add (p.GetBuilder);
1681 if (p.SetBuilder != null)
1682 members.Add (p.SetBuilder);
1686 if (indexers != null) {
1687 int len = indexers.Count;
1688 for (int i = 0; i < len; i++) {
1689 Indexer ix = (Indexer) indexers [i];
1691 if (ix.GetBuilder != null)
1692 members.Add (ix.GetBuilder);
1693 if (ix.SetBuilder != null)
1694 members.Add (ix.SetBuilder);
1698 if (events != null) {
1699 int len = events.Count;
1700 for (int i = 0; i < len; i++) {
1701 Event e = (Event) events [i];
1703 if (e.AddBuilder != null)
1704 members.Add (e.AddBuilder);
1705 if (e.RemoveBuilder != null)
1706 members.Add (e.RemoveBuilder);
1710 MethodInfo[] retMethods = new MethodInfo [members.Count];
1711 members.CopyTo (retMethods, 0);
1715 // Indicated whether container has StructLayout attribute set Explicit
1716 public bool HasExplicitLayout {
1717 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1718 set { caching_flags |= Flags.HasExplicitLayout; }
1722 // Return the nested type with name @name. Ensures that the nested type
1723 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1725 public Type FindNestedType (string name)
1727 if (PartialContainer != this)
1728 throw new InternalErrorException ("should not happen");
1730 ArrayList [] lists = { types, delegates };
1732 for (int j = 0; j < lists.Length; ++j) {
1733 ArrayList list = lists [j];
1737 int len = list.Count;
1738 for (int i = 0; i < len; ++i) {
1739 DeclSpace ds = (DeclSpace) list [i];
1740 if (ds.Basename == name) {
1741 return ds.DefineType ();
1749 private void FindMembers_NestedTypes (int modflags,
1750 BindingFlags bf, MemberFilter filter, object criteria,
1751 ref ArrayList members)
1753 ArrayList [] lists = { types, delegates };
1755 for (int j = 0; j < lists.Length; ++j) {
1756 ArrayList list = lists [j];
1760 int len = list.Count;
1761 for (int i = 0; i < len; i++) {
1762 DeclSpace ds = (DeclSpace) list [i];
1764 if ((ds.ModFlags & modflags) == 0)
1767 TypeBuilder tb = ds.TypeBuilder;
1769 if (!(criteria is string) || ds.Basename.Equals (criteria))
1770 tb = ds.DefineType ();
1773 if (tb != null && (filter (tb, criteria) == true)) {
1774 if (members == null)
1775 members = new ArrayList ();
1784 /// This method returns the members of this type just like Type.FindMembers would
1785 /// Only, we need to use this for types which are _being_ defined because MS'
1786 /// implementation can't take care of that.
1789 // FIXME: return an empty static array instead of null, that cleans up
1790 // some code and is consistent with some coding conventions I just found
1794 // Notice that in various cases we check if our field is non-null,
1795 // something that would normally mean that there was a bug elsewhere.
1797 // The problem happens while we are defining p-invoke methods, as those
1798 // will trigger a FindMembers, but this happens before things are defined
1800 // Since the whole process is a no-op, it is fine to check for null here.
1802 // TODO: This approach will be one day completely removed, it's already
1803 // used at few places only
1806 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1807 MemberFilter filter, object criteria)
1809 ArrayList members = null;
1812 if ((bf & BindingFlags.Public) != 0)
1813 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1815 if ((bf & BindingFlags.NonPublic) != 0)
1816 modflags |= Modifiers.PRIVATE;
1818 int static_mask = 0, static_flags = 0;
1819 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1820 case BindingFlags.Static:
1821 static_mask = static_flags = Modifiers.STATIC;
1824 case BindingFlags.Instance:
1825 static_mask = Modifiers.STATIC;
1830 static_mask = static_flags = 0;
1834 Timer.StartTimer (TimerType.TcFindMembers);
1837 filter = accepting_filter;
1839 if ((mt & MemberTypes.Field) != 0) {
1840 if (fields != null) {
1841 int len = fields.Count;
1842 for (int i = 0; i < len; i++) {
1843 FieldBase f = (FieldBase) fields [i];
1845 if ((f.ModFlags & modflags) == 0)
1847 if ((f.ModFlags & static_mask) != static_flags)
1850 FieldBuilder fb = f.FieldBuilder;
1851 if (fb != null && filter (fb, criteria) == true) {
1852 if (members == null)
1853 members = new ArrayList ();
1860 if (constants != null) {
1861 int len = constants.Count;
1862 for (int i = 0; i < len; i++) {
1863 Const con = (Const) constants [i];
1865 if ((con.ModFlags & modflags) == 0)
1867 if ((con.ModFlags & static_mask) != static_flags)
1870 FieldBuilder fb = con.FieldBuilder;
1873 fb = con.FieldBuilder;
1875 if (fb != null && filter (fb, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1885 if ((mt & MemberTypes.Method) != 0) {
1886 if (methods != null) {
1887 int len = methods.Count;
1888 for (int i = 0; i < len; i++) {
1889 Method m = (Method) methods [i];
1891 if ((m.ModFlags & modflags) == 0)
1893 if ((m.ModFlags & static_mask) != static_flags)
1896 MethodBuilder mb = m.MethodBuilder;
1898 if (mb != null && filter (mb, criteria) == true) {
1899 if (members == null)
1900 members = new ArrayList ();
1907 if (operators != null) {
1908 int len = operators.Count;
1909 for (int i = 0; i < len; i++) {
1910 Operator o = (Operator) operators [i];
1912 if ((o.ModFlags & modflags) == 0)
1914 if ((o.ModFlags & static_mask) != static_flags)
1917 MethodBuilder ob = o.MethodBuilder;
1918 if (ob != null && filter (ob, criteria) == true) {
1919 if (members == null)
1920 members = new ArrayList ();
1927 if (events != null) {
1928 foreach (Event e in events) {
1929 if ((e.ModFlags & modflags) == 0)
1931 if ((e.ModFlags & static_mask) != static_flags)
1934 MethodBuilder b = e.AddBuilder;
1935 if (b != null && filter (b, criteria)) {
1936 if (members == null)
1937 members = new ArrayList (4);
1942 b = e.RemoveBuilder;
1943 if (b != null && filter (b, criteria)) {
1944 if (members == null)
1945 members = new ArrayList (4);
1952 if (properties != null) {
1953 int len = properties.Count;
1954 for (int i = 0; i < len; i++) {
1955 Property p = (Property) properties [i];
1957 if ((p.ModFlags & modflags) == 0)
1959 if ((p.ModFlags & static_mask) != static_flags)
1965 if (b != null && filter (b, criteria) == true) {
1966 if (members == null)
1967 members = new ArrayList ();
1973 if (b != null && filter (b, criteria) == true) {
1974 if (members == null)
1975 members = new ArrayList ();
1982 if (indexers != null) {
1983 int len = indexers.Count;
1984 for (int i = 0; i < len; i++) {
1985 Indexer ix = (Indexer) indexers [i];
1987 if ((ix.ModFlags & modflags) == 0)
1989 if ((ix.ModFlags & static_mask) != static_flags)
1995 if (b != null && filter (b, criteria) == true) {
1996 if (members == null)
1997 members = new ArrayList ();
2003 if (b != null && filter (b, criteria) == true) {
2004 if (members == null)
2005 members = new ArrayList ();
2013 if ((mt & MemberTypes.Event) != 0) {
2014 if (events != null) {
2015 int len = events.Count;
2016 for (int i = 0; i < len; i++) {
2017 Event e = (Event) events [i];
2019 if ((e.ModFlags & modflags) == 0)
2021 if ((e.ModFlags & static_mask) != static_flags)
2024 MemberInfo eb = e.EventBuilder;
2025 if (eb != null && filter (eb, criteria) == true) {
2026 if (members == null)
2027 members = new ArrayList ();
2029 members.Add (e.EventBuilder);
2035 if ((mt & MemberTypes.Property) != 0){
2036 if (properties != null) {
2037 int len = properties.Count;
2038 for (int i = 0; i < len; i++) {
2039 Property p = (Property) properties [i];
2041 if ((p.ModFlags & modflags) == 0)
2043 if ((p.ModFlags & static_mask) != static_flags)
2046 MemberInfo pb = p.PropertyBuilder;
2047 if (pb != null && filter (pb, criteria) == true) {
2048 if (members == null)
2049 members = new ArrayList ();
2051 members.Add (p.PropertyBuilder);
2056 if (indexers != null) {
2057 int len = indexers.Count;
2058 for (int i = 0; i < len; i++) {
2059 Indexer ix = (Indexer) indexers [i];
2061 if ((ix.ModFlags & modflags) == 0)
2063 if ((ix.ModFlags & static_mask) != static_flags)
2066 MemberInfo ib = ix.PropertyBuilder;
2067 if (ib != null && filter (ib, criteria) == true) {
2068 if (members == null)
2069 members = new ArrayList ();
2071 members.Add (ix.PropertyBuilder);
2077 if ((mt & MemberTypes.NestedType) != 0)
2078 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2080 if ((mt & MemberTypes.Constructor) != 0){
2081 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2082 int len = instance_constructors.Count;
2083 for (int i = 0; i < len; i++) {
2084 Constructor c = (Constructor) instance_constructors [i];
2086 ConstructorBuilder cb = c.ConstructorBuilder;
2087 if (cb != null && filter (cb, criteria) == true) {
2088 if (members == null)
2089 members = new ArrayList ();
2096 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2097 ConstructorBuilder cb =
2098 default_static_constructor.ConstructorBuilder;
2100 if (cb != null && filter (cb, criteria) == true) {
2101 if (members == null)
2102 members = new ArrayList ();
2110 // Lookup members in base if requested.
2112 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2113 if (TypeBuilder.BaseType != null) {
2114 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2115 if (list.Count > 0) {
2116 if (members == null)
2117 members = new ArrayList ();
2119 members.AddRange (list);
2124 Timer.StopTimer (TimerType.TcFindMembers);
2126 if (members == null)
2127 return MemberList.Empty;
2129 return new MemberList (members);
2132 public override MemberCache MemberCache {
2134 return member_cache;
2138 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2139 MemberFilter filter, object criteria)
2141 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2144 return ds.FindMembers (mt, bf, filter, criteria);
2146 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2150 /// Emits the values for the constants
2152 public void EmitConstants ()
2154 if (constants != null)
2155 foreach (Const con in constants)
2160 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2165 foreach (MemberCore mc in al) {
2166 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2169 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2170 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2175 public virtual void VerifyMembers ()
2178 // Check for internal or private fields that were never assigned
2180 if (Report.WarningLevel >= 3) {
2181 CheckMemberUsage (properties, "property");
2182 CheckMemberUsage (methods, "method");
2183 CheckMemberUsage (constants, "constant");
2185 if (fields != null){
2186 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2187 foreach (FieldBase f in fields) {
2188 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2189 if (is_type_exposed)
2192 f.SetMemberIsUsed ();
2196 if ((f.caching_flags & Flags.IsAssigned) == 0)
2197 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2200 const int error_code = 414;
2202 const int error_code = 169;
2204 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2205 f.GetSignatureForError ());
2211 // Only report 649 on level 4
2213 if (Report.WarningLevel < 4)
2216 if ((f.caching_flags & Flags.IsAssigned) != 0)
2219 Constant c = New.Constantify (f.MemberType);
2220 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2221 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2227 // TODO: move to ClassOrStruct
2228 void EmitConstructors ()
2230 if (instance_constructors == null)
2233 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2234 bool has_compliant_args = false;
2236 foreach (Constructor c in instance_constructors) {
2240 catch (Exception e) {
2241 throw new InternalErrorException (c, e);
2244 if (has_compliant_args)
2247 has_compliant_args = c.HasCompliantArgs;
2249 if (!has_compliant_args)
2250 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2252 foreach (Constructor c in instance_constructors) {
2256 catch (Exception e) {
2257 throw new InternalErrorException (c, e);
2264 /// Emits the code, this step is performed after all
2265 /// the types, enumerations, constructors
2267 public virtual void EmitType ()
2269 if (OptAttributes != null)
2270 OptAttributes.Emit ();
2273 // Structs with no fields need to have at least one byte.
2274 // The right thing would be to set the PackingSize in a DefineType
2275 // but there are no functions that allow interfaces *and* the size to
2279 if (Kind == Kind.Struct && first_nonstatic_field == null){
2280 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2281 FieldAttributes.Private);
2283 if (HasExplicitLayout){
2284 object [] ctor_args = new object [] { 0 };
2286 if (TypeManager.field_offset_attribute_ctor == null) {
2288 if (TypeManager.field_offset_attribute_type == null) {
2289 TypeManager.field_offset_attribute_type = TypeManager.CoreLookupType (
2290 "System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, true);
2293 TypeManager.field_offset_attribute_ctor = TypeManager.GetPredefinedConstructor (
2294 TypeManager.field_offset_attribute_type, Location, TypeManager.int32_type);
2297 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2298 TypeManager.field_offset_attribute_ctor, ctor_args);
2299 fb.SetCustomAttribute (cba);
2305 EmitConstructors ();
2307 // Can not continue if constants are broken
2309 if (Report.Errors > 0)
2312 if (default_static_constructor != null)
2313 default_static_constructor.Emit ();
2315 if (methods != null){
2316 for (int i = 0; i < methods.Count; ++i)
2317 ((Method)methods[i]).Emit ();
2320 if (operators != null)
2321 foreach (Operator o in operators)
2324 if (properties != null)
2325 foreach (Property p in properties)
2328 if (indexers != null) {
2329 foreach (Indexer indx in indexers)
2335 foreach (FieldBase f in fields)
2338 if (events != null){
2339 foreach (Event e in Events)
2343 if (delegates != null) {
2344 foreach (Delegate d in Delegates) {
2349 if (pending != null)
2350 if (pending.VerifyPendingMethods ())
2353 if (Report.Errors > 0)
2356 if (compiler_generated != null) {
2357 foreach (CompilerGeneratedClass c in compiler_generated) {
2358 if (!c.DefineMembers ())
2359 throw new InternalErrorException ();
2361 foreach (CompilerGeneratedClass c in compiler_generated)
2366 public override void CloseType ()
2368 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2372 caching_flags |= Flags.CloseTypeCreated;
2373 TypeBuilder.CreateType ();
2374 } catch (TypeLoadException){
2376 // This is fine, the code still created the type
2378 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2379 // Console.WriteLine (e.Message);
2380 } catch (Exception e) {
2381 throw new InternalErrorException (this, e);
2385 foreach (TypeContainer tc in Types)
2386 if (tc.Kind == Kind.Struct)
2389 foreach (TypeContainer tc in Types)
2390 if (tc.Kind != Kind.Struct)
2394 if (Delegates != null)
2395 foreach (Delegate d in Delegates)
2398 if (CompilerGenerated != null)
2399 foreach (CompilerGeneratedClass c in CompilerGenerated)
2406 initialized_fields = null;
2407 initialized_static_fields = null;
2409 ordered_explicit_member_list = null;
2410 ordered_member_list = null;
2415 compiler_generated = null;
2416 default_constructor = null;
2417 default_static_constructor = null;
2419 OptAttributes = null;
2422 member_cache = null;
2426 // Performs the validation on a Method's modifiers (properties have
2427 // the same properties).
2429 public bool MethodModifiersValid (MemberCore mc)
2431 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2432 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2433 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2435 int flags = mc.ModFlags;
2438 // At most one of static, virtual or override
2440 if ((flags & Modifiers.STATIC) != 0){
2441 if ((flags & vao) != 0){
2442 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2443 mc.GetSignatureForError ());
2448 if (Kind == Kind.Struct){
2449 if ((flags & va) != 0){
2450 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2455 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2456 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2457 mc.GetSignatureForError ());
2462 // If the declaration includes the abstract modifier, then the
2463 // declaration does not include static, virtual or extern
2465 if ((flags & Modifiers.ABSTRACT) != 0){
2466 if ((flags & Modifiers.EXTERN) != 0){
2468 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2472 if ((flags & Modifiers.SEALED) != 0) {
2473 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2477 if ((flags & Modifiers.VIRTUAL) != 0){
2478 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2482 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2483 Report.SymbolRelatedToPreviousError (this);
2484 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2485 mc.GetSignatureForError (), GetSignatureForError ());
2490 if ((flags & Modifiers.PRIVATE) != 0){
2491 if ((flags & vao) != 0){
2492 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2497 if ((flags & Modifiers.SEALED) != 0){
2498 if ((flags & Modifiers.OVERRIDE) == 0){
2499 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2507 public Constructor DefaultStaticConstructor {
2508 get { return default_static_constructor; }
2511 protected override bool VerifyClsCompliance ()
2513 if (!base.VerifyClsCompliance ())
2518 Type base_type = TypeBuilder.BaseType;
2519 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2520 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2527 /// Checks whether container name is CLS Compliant
2529 void VerifyClsName ()
2531 Hashtable base_members = base_cache == null ?
2533 base_cache.GetPublicMembers ();
2534 Hashtable this_members = new Hashtable ();
2536 foreach (DictionaryEntry entry in defined_names) {
2537 MemberCore mc = (MemberCore)entry.Value;
2538 if (!mc.IsClsComplianceRequired ())
2541 string name = (string) entry.Key;
2542 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2544 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2545 object found = base_members [lcase];
2546 if (found == null) {
2547 found = this_members [lcase];
2548 if (found == null) {
2549 this_members.Add (lcase, mc);
2554 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2557 if (found is MemberInfo) {
2558 if (basename == ((MemberInfo) found).Name)
2560 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2562 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2565 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2567 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2574 /// Performs checks for an explicit interface implementation. First it
2575 /// checks whether the `interface_type' is a base inteface implementation.
2576 /// Then it checks whether `name' exists in the interface type.
2578 public bool VerifyImplements (InterfaceMemberBase mb)
2580 if (ifaces != null) {
2581 foreach (Type t in ifaces){
2582 if (TypeManager.IsEqual (t, mb.InterfaceType))
2587 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2588 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2589 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2593 public override Type LookupAnyGeneric (string typeName)
2595 if (types != null) {
2596 foreach (TypeContainer tc in types) {
2600 int pos = tc.Basename.LastIndexOf ('`');
2601 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2602 return tc.TypeBuilder;
2606 return base.LookupAnyGeneric (typeName);
2609 public void Mark_HasEquals ()
2611 cached_method |= CachedMethods.Equals;
2614 public void Mark_HasGetHashCode ()
2616 cached_method |= CachedMethods.GetHashCode;
2620 /// Method container contains Equals method
2622 public bool HasEquals {
2624 return (cached_method & CachedMethods.Equals) != 0;
2629 /// Method container contains GetHashCode method
2631 public bool HasGetHashCode {
2633 return (cached_method & CachedMethods.GetHashCode) != 0;
2637 public bool HasStaticFieldInitializer {
2639 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2643 cached_method |= CachedMethods.HasStaticFieldInitializer;
2645 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2653 string IMemberContainer.Name {
2659 Type IMemberContainer.Type {
2665 bool IMemberContainer.IsInterface {
2667 return Kind == Kind.Interface;
2671 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2673 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2675 if (GenericType != null)
2676 return TypeManager.FindMembers (GenericType, mt, new_bf,
2679 return FindMembers (mt, new_bf, null, null);
2683 // Generates xml doc comments (if any), and if required,
2684 // handle warning report.
2686 internal override void GenerateDocComment (DeclSpace ds)
2688 DocUtil.GenerateTypeDocComment (this, ds);
2691 public override string DocCommentHeader {
2692 get { return "T:"; }
2695 public MemberCache BaseCache {
2697 if (base_cache != null)
2699 if (TypeBuilder.BaseType != null)
2700 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2701 if (TypeBuilder.IsInterface)
2702 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2708 public abstract class ClassOrStruct : TypeContainer {
2709 ListDictionary declarative_security;
2711 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2712 MemberName name, Attributes attrs, Kind kind)
2713 : base (ns, parent, name, attrs, kind)
2717 protected override bool AddToContainer (MemberCore symbol, string name)
2719 if (name == MemberName.Name) {
2720 if (symbol is TypeParameter) {
2721 Report.Error (694, symbol.Location,
2722 "Type parameter `{0}' has same name as " +
2723 "containing type, or method", name);
2727 Report.SymbolRelatedToPreviousError (this);
2728 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2729 symbol.GetSignatureForError ());
2733 return base.AddToContainer (symbol, name);
2736 public override void VerifyMembers ()
2738 base.VerifyMembers ();
2740 if ((events != null) && Report.WarningLevel >= 3) {
2741 foreach (Event e in events){
2742 // Note: The event can be assigned from same class only, so we can report
2743 // this warning for all accessibility modes
2744 if ((e.caching_flags & Flags.IsUsed) == 0)
2745 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2750 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2752 if (a.IsValidSecurityAttribute ()) {
2753 if (declarative_security == null)
2754 declarative_security = new ListDictionary ();
2756 a.ExtractSecurityPermissionSet (declarative_security);
2760 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2761 HasExplicitLayout = true;
2764 base.ApplyAttributeBuilder (a, cb);
2768 /// Defines the default constructors
2770 protected void DefineDefaultConstructor (bool is_static)
2772 // The default instance constructor is public
2773 // If the class is abstract, the default constructor is protected
2774 // The default static constructor is private
2778 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2780 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2783 Constructor c = new Constructor (this, MemberName.Name, mods,
2784 Parameters.EmptyReadOnlyParameters,
2785 new GeneratedBaseInitializer (Location),
2789 c.Block = new ToplevelBlock (null, Location);
2792 public override bool Define ()
2794 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2795 DefineDefaultConstructor (true);
2797 if (default_static_constructor != null)
2798 default_static_constructor.Define ();
2800 return base.Define ();
2803 public override void Emit ()
2807 if (declarative_security != null) {
2808 foreach (DictionaryEntry de in declarative_security) {
2809 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2814 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2816 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2819 protected override TypeAttributes TypeAttr {
2821 if (default_static_constructor == null)
2822 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2824 return base.TypeAttr;
2830 // TODO: should be sealed
2831 public class Class : ClassOrStruct {
2832 const int AllowedModifiers =
2835 Modifiers.PROTECTED |
2836 Modifiers.INTERNAL |
2838 Modifiers.ABSTRACT |
2843 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2845 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2847 : base (ns, parent, name, attrs, Kind.Class)
2849 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2850 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2852 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2853 Report.FeatureIsNotAvailable (Location, "static classes");
2857 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2859 if (part.Name == "System.Object")
2860 Report.Error (537, part.Location,
2861 "The class System.Object cannot have a base class or implement an interface.");
2862 base.AddBasesForPart (part, bases);
2865 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2867 if (a.Type == TypeManager.attribute_usage_type) {
2868 if (!TypeManager.IsAttributeType (BaseType) &&
2869 TypeBuilder.FullName != "System.Attribute") {
2870 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2874 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2875 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2879 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2880 !attributes.Contains (TypeManager.guid_attr_type)) {
2881 a.Error_MissingGuidAttribute ();
2885 if (a.Type == TypeManager.extension_attribute_type) {
2886 a.Error_MisusedExtensionAttribute ();
2890 if (AttributeTester.IsAttributeExcluded (a.Type))
2893 base.ApplyAttributeBuilder (a, cb);
2896 public override AttributeTargets AttributeTargets {
2898 return AttributeTargets.Class;
2902 protected override void DefineContainerMembers (MemberCoreArrayList list)
2908 base.DefineContainerMembers (list);
2912 foreach (MemberCore m in list) {
2913 if (m is Operator) {
2914 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2918 if (m is Destructor) {
2919 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2923 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2924 m.CheckProtectedModifier ();
2929 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2933 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2936 if (m is Constructor) {
2937 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2941 Method method = m as Method;
2942 if (method != null && method.Parameters.HasExtensionMethodType) {
2943 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2947 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2950 base.DefineContainerMembers (list);
2953 public override TypeBuilder DefineType ()
2955 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2956 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2960 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2961 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2965 return base.DefineType ();
2968 protected override bool DoDefineMembers ()
2970 if (InstanceConstructors == null && !IsStatic)
2971 DefineDefaultConstructor (false);
2973 return base.DoDefineMembers ();
2976 public override void Emit ()
2981 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2982 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2986 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2988 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2990 if (base_class == null) {
2991 if (RootContext.StdLib)
2992 base_class = TypeManager.system_object_expr;
2993 else if (Name != "System.Object")
2994 base_class = TypeManager.system_object_expr;
2996 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2998 689, base_class.Location,
2999 "Cannot derive from `{0}' because it is a type parameter",
3000 base_class.GetSignatureForError ());
3004 if (base_class.IsSealed){
3005 Report.SymbolRelatedToPreviousError (base_class.Type);
3006 if (base_class.Type.IsAbstract) {
3007 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3008 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3010 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3011 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3016 if (!base_class.CanInheritFrom ()){
3017 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3018 GetSignatureForError (), base_class.GetSignatureForError ());
3022 if (!base_class.AsAccessible (this)) {
3023 Report.SymbolRelatedToPreviousError (base_class.Type);
3024 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3025 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3029 if (PartialContainer.IsStaticClass) {
3030 if (base_class.Type != TypeManager.object_type) {
3031 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3032 GetSignatureForError (), base_class.GetSignatureForError ());
3036 if (ifaces != null) {
3037 foreach (TypeExpr t in ifaces)
3038 Report.SymbolRelatedToPreviousError (t.Type);
3039 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
3046 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3047 /// Valid only for attribute classes.
3048 public bool IsExcluded ()
3050 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3051 return (caching_flags & Flags.Excluded) != 0;
3053 caching_flags &= ~Flags.Excluded_Undetected;
3055 if (OptAttributes == null)
3058 if (TypeManager.conditional_attribute_type == null)
3061 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3066 foreach (Attribute a in attrs) {
3067 string condition = a.GetConditionalAttributeValue ();
3068 if (RootContext.AllDefines.Contains (condition))
3072 caching_flags |= Flags.Excluded;
3078 return (ModFlags & Modifiers.STATIC) != 0;
3083 // FIXME: How do we deal with the user specifying a different
3086 protected override TypeAttributes TypeAttr {
3088 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3090 ta |= StaticClassAttribute;
3096 public sealed class Struct : ClassOrStruct {
3098 // Modifiers allowed in a struct declaration
3100 const int AllowedModifiers =
3103 Modifiers.PROTECTED |
3104 Modifiers.INTERNAL |
3108 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3109 int mod, Attributes attrs)
3110 : base (ns, parent, name, attrs, Kind.Struct)
3114 if (parent.Parent == null)
3115 accmods = Modifiers.INTERNAL;
3117 accmods = Modifiers.PRIVATE;
3119 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3121 this.ModFlags |= Modifiers.SEALED;
3124 public override AttributeTargets AttributeTargets {
3126 return AttributeTargets.Struct;
3130 const TypeAttributes DefaultTypeAttributes =
3131 TypeAttributes.SequentialLayout |
3132 TypeAttributes.Sealed |
3133 TypeAttributes.BeforeFieldInit;
3136 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3138 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3140 // If we are compiling our runtime,
3141 // and we are defining ValueType, then our
3142 // base is `System.Object'.
3144 if (base_class == null) {
3145 if (!RootContext.StdLib && Name == "System.ValueType")
3146 base_class = TypeManager.system_object_expr;
3148 base_class = TypeManager.system_valuetype_expr;
3155 // FIXME: Allow the user to specify a different set of attributes
3156 // in some cases (Sealed for example is mandatory for a class,
3157 // but what SequentialLayout can be changed
3159 protected override TypeAttributes TypeAttr {
3161 return base.TypeAttr | DefaultTypeAttributes;
3165 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3167 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3168 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3169 field.GetSignatureForError ());
3172 base.RegisterFieldForInitialization (field, expression);
3180 public sealed class Interface : TypeContainer, IMemberContainer {
3183 /// Modifiers allowed in a class declaration
3185 public const int AllowedModifiers =
3188 Modifiers.PROTECTED |
3189 Modifiers.INTERNAL |
3193 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3195 : base (ns, parent, name, attrs, Kind.Interface)
3199 if (parent.Parent == null)
3200 accmods = Modifiers.INTERNAL;
3202 accmods = Modifiers.PRIVATE;
3204 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3207 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3209 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3210 !attributes.Contains (TypeManager.guid_attr_type)) {
3211 a.Error_MissingGuidAttribute ();
3214 base.ApplyAttributeBuilder (a, cb);
3218 public override AttributeTargets AttributeTargets {
3220 return AttributeTargets.Interface;
3224 const TypeAttributes DefaultTypeAttributes =
3225 TypeAttributes.AutoLayout |
3226 TypeAttributes.Abstract |
3227 TypeAttributes.Interface;
3229 protected override TypeAttributes TypeAttr {
3231 return base.TypeAttr | DefaultTypeAttributes;
3235 protected override bool VerifyClsCompliance ()
3237 if (!base.VerifyClsCompliance ())
3240 if (ifaces != null) {
3241 foreach (Type t in ifaces) {
3242 if (AttributeTester.IsClsCompliant (t))
3245 Report.SymbolRelatedToPreviousError (t);
3246 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3247 GetSignatureForError (), TypeManager.CSharpName (t));
3255 // It is used as a base class for all property based members
3256 // This includes properties, indexers, and events
3257 public abstract class PropertyBasedMember : InterfaceMemberBase
3259 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3260 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3261 MemberName name, Attributes attrs)
3262 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3266 protected override bool VerifyClsCompliance ()
3268 if (!base.VerifyClsCompliance ())
3271 if (!AttributeTester.IsClsCompliant (MemberType)) {
3272 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3273 GetSignatureForError ());
3281 public abstract class MethodCore : InterfaceMemberBase
3283 public readonly Parameters Parameters;
3284 protected ToplevelBlock block;
3286 public MethodCore (DeclSpace parent, GenericMethod generic,
3287 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3288 MemberName name, Attributes attrs, Parameters parameters)
3289 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3291 Parameters = parameters;
3295 // Returns the System.Type array for the parameters of this method
3297 public Type [] ParameterTypes {
3299 return Parameters.Types;
3303 public Parameters ParameterInfo
3310 public ToplevelBlock Block {
3320 protected override bool CheckBase ()
3322 // Check whether arguments were correct.
3323 if (!DefineParameters (Parameters))
3326 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3327 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3328 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3331 // TODO: Find a better way how to check reserved accessors collision
3332 Method m = this as Method;
3334 if (!m.CheckForDuplications ())
3339 if (!base.CheckBase ())
3346 // Returns a string that represents the signature for this
3347 // member which should be used in XML documentation.
3349 public override string GetDocCommentName (DeclSpace ds)
3351 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3355 // Raised (and passed an XmlElement that contains the comment)
3356 // when GenerateDocComment is writing documentation expectedly.
3358 // FIXME: with a few effort, it could be done with XmlReader,
3359 // that means removal of DOM use.
3361 internal override void OnGenerateDocComment (XmlElement el)
3363 DocUtil.OnMethodGenerateDocComment (this, el);
3367 // Represents header string for documentation comment.
3369 public override string DocCommentHeader
3371 get { return "M:"; }
3374 public override bool EnableOverloadChecks (MemberCore overload)
3376 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3377 caching_flags |= Flags.MethodOverloadsExist;
3384 public virtual void SetYields ()
3386 ModFlags |= Modifiers.METHOD_YIELDS;
3389 protected override bool VerifyClsCompliance ()
3391 if (!base.VerifyClsCompliance ())
3394 if (Parameters.HasArglist) {
3395 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3398 if (!AttributeTester.IsClsCompliant (MemberType)) {
3399 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3400 GetSignatureForError ());
3403 Parameters.VerifyClsCompliance ();
3409 public abstract class InterfaceMemberBase : MemberBase {
3411 // Whether this is an interface member.
3413 public bool IsInterface;
3416 // If true, this is an explicit interface implementation
3418 public bool IsExplicitImpl;
3420 protected bool is_external_implementation;
3423 // The interface type we are explicitly implementing
3425 public Type InterfaceType;
3428 // The method we're overriding if this is an override method.
3430 protected MethodInfo base_method;
3432 readonly int explicit_mod_flags;
3433 public MethodAttributes flags;
3435 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3436 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3437 MemberName name, Attributes attrs)
3438 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3441 IsInterface = is_iface;
3442 IsExplicitImpl = (MemberName.Left != null);
3443 explicit_mod_flags = mod;
3446 protected override bool CheckBase ()
3448 if (!base.CheckBase ())
3454 // Is null for System.Object while compiling corlib and base interfaces
3455 if (Parent.PartialContainer.BaseCache == null) {
3456 if ((ModFlags & Modifiers.NEW) != 0) {
3457 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3462 Type base_ret_type = null;
3463 base_method = FindOutBaseMethod (ref base_ret_type);
3465 // method is override
3466 if (base_method != null) {
3467 if (!CheckMethodAgainstBase (base_ret_type))
3470 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3471 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3473 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3474 Report.SymbolRelatedToPreviousError (base_method);
3475 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3476 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3479 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3480 Report.SymbolRelatedToPreviousError (base_method);
3481 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3482 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3489 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3490 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3491 if (conflict_symbol != null) {
3492 Report.SymbolRelatedToPreviousError (conflict_symbol);
3494 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3495 else if (this is PropertyBase)
3496 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3498 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3500 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3501 GetSignatureForError (), SimpleName.GetMemberType (this));
3506 if (conflict_symbol == null) {
3507 if ((ModFlags & Modifiers.NEW) != 0) {
3508 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3513 if ((ModFlags & Modifiers.NEW) == 0) {
3514 if (this is Method && conflict_symbol is MethodBase)
3517 Report.SymbolRelatedToPreviousError (conflict_symbol);
3518 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3519 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3526 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3527 // that have been defined.
3529 // `name' is the user visible name for reporting errors (this is used to
3530 // provide the right name regarding method names and properties)
3532 bool CheckMethodAgainstBase (Type base_method_type)
3536 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3537 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3538 Report.Error (506, Location,
3539 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3540 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3544 // Now we check that the overriden method is not final
3546 if (base_method.IsFinal) {
3547 Report.SymbolRelatedToPreviousError (base_method);
3548 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3549 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3553 // Check that the permissions are not being changed
3555 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3556 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3558 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3559 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3563 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3564 Report.SymbolRelatedToPreviousError (base_method);
3565 if (this is PropertyBasedMember) {
3566 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3567 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3570 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3571 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3577 if ((ModFlags & Modifiers.NEW) == 0) {
3578 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3579 ModFlags |= Modifiers.NEW;
3580 Report.SymbolRelatedToPreviousError (base_method);
3581 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3582 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",
3583 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3585 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3586 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3590 if (base_method.IsAbstract && !IsInterface) {
3591 Report.SymbolRelatedToPreviousError (base_method);
3592 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3593 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3601 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3603 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3605 // when overriding protected internal, the method can be declared
3606 // protected internal only within the same assembly or assembly
3607 // which has InternalsVisibleTo
3609 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3610 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3611 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3613 // if it's not "protected internal", it must be "protected"
3617 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3619 // protected within the same assembly - an error
3622 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3623 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3625 // protected ok, but other attributes differ - report an error
3631 return (thisp == base_classp);
3635 protected bool DefineParameters (Parameters parameters)
3637 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3639 if (!parameters.Resolve (rc))
3643 foreach (Parameter p in parameters.FixedParameters) {
3644 if (p.CheckAccessibility (this))
3647 Report.SymbolRelatedToPreviousError (p.ParameterType);
3648 if (this is Indexer)
3649 Report.Error (55, Location,
3650 "Inconsistent accessibility: parameter type `" +
3651 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3652 "accessible than indexer `" + GetSignatureForError () + "'");
3653 else if (this is Operator)
3654 Report.Error (57, Location,
3655 "Inconsistent accessibility: parameter type `" +
3656 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3657 "accessible than operator `" + GetSignatureForError () + "'");
3659 Report.Error (51, Location,
3660 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3661 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3667 protected override bool DoDefine()
3669 if (!base.DoDefine ())
3672 if (IsExplicitImpl) {
3673 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3677 InterfaceType = texpr.Type;
3679 if (!InterfaceType.IsInterface) {
3680 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3684 if (!Parent.PartialContainer.VerifyImplements (this))
3691 protected virtual bool DoDefineBase ()
3694 throw new InternalErrorException ();
3697 ModFlags = Modifiers.PUBLIC |
3698 Modifiers.ABSTRACT |
3699 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3701 flags = MethodAttributes.Public |
3702 MethodAttributes.Abstract |
3703 MethodAttributes.HideBySig |
3704 MethodAttributes.NewSlot |
3705 MethodAttributes.Virtual;
3707 if (!Parent.PartialContainer.MethodModifiersValid (this))
3710 flags = Modifiers.MethodAttr (ModFlags);
3713 if (IsExplicitImpl) {
3714 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3715 if (iface_texpr == null)
3718 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3719 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3720 GetSignatureForError ());
3724 InterfaceType = iface_texpr.Type;
3726 if (!InterfaceType.IsInterface) {
3727 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3731 if (!Parent.PartialContainer.VerifyImplements (this))
3734 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3740 public override void Emit()
3742 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3743 // We are more strict than Microsoft and report CS0626 as error
3744 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3745 Report.Error (626, Location,
3746 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3747 GetSignatureForError ());
3753 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3755 Report.SymbolRelatedToPreviousError (base_method);
3756 string base_name = TypeManager.GetFullNameSignature (base_method);
3757 string this_name = GetSignatureForError ();
3758 if (suffix != null) {
3759 base_name += suffix;
3760 this_name += suffix;
3763 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3764 this_name, Modifiers.GetDescription (ma), base_name);
3767 protected static string Error722 {
3769 return "`{0}': static types cannot be used as return types";
3774 /// Gets base method and its return type
3776 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3779 // The "short" name of this property / indexer / event. This is the
3780 // name without the explicit interface.
3782 public string ShortName
3784 get { return MemberName.Name; }
3785 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3788 public string GetFullName (MemberName name)
3790 if (!IsExplicitImpl)
3793 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3796 protected override bool VerifyClsCompliance ()
3798 if (!base.VerifyClsCompliance ()) {
3799 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3800 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3803 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3804 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3809 if (GenericMethod != null)
3810 GenericMethod.VerifyClsCompliance ();
3815 public override bool IsUsed
3817 get { return IsExplicitImpl || base.IsUsed; }
3822 public abstract class MethodOrOperator : MethodCore, IMethodData
3824 public MethodBuilder MethodBuilder;
3825 ReturnParameter return_attributes;
3826 ListDictionary declarative_security;
3827 protected MethodData MethodData;
3830 ArrayList anonymous_methods;
3832 static string[] attribute_targets = new string [] { "method", "return" };
3834 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3835 int allowed_mod, bool is_interface, MemberName name,
3836 Attributes attrs, Parameters parameters)
3837 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3842 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3844 if (a.Target == AttributeTargets.ReturnValue) {
3845 if (return_attributes == null)
3846 return_attributes = new ReturnParameter (MethodBuilder, Location);
3848 return_attributes.ApplyAttributeBuilder (a, cb);
3852 if (a.IsInternalMethodImplAttribute) {
3853 is_external_implementation = true;
3856 if (a.Type == TypeManager.dllimport_type) {
3857 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3858 if ((ModFlags & extern_static) != extern_static) {
3859 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3861 is_external_implementation = true;
3864 if (a.IsValidSecurityAttribute ()) {
3865 if (declarative_security == null)
3866 declarative_security = new ListDictionary ();
3867 a.ExtractSecurityPermissionSet (declarative_security);
3871 if (MethodBuilder != null)
3872 MethodBuilder.SetCustomAttribute (cb);
3875 public override AttributeTargets AttributeTargets {
3877 return AttributeTargets.Method;
3881 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3883 return new EmitContext (
3884 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3887 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
3889 if (anonymous_methods == null)
3890 anonymous_methods = new ArrayList ();
3891 anonymous_methods.Add (anonymous);
3894 protected bool DefineGenericMethod ()
3896 if (!DoDefineBase ())
3900 if (GenericMethod != null) {
3903 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags); //, ReturnType, null);
3905 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3908 if (!GenericMethod.Define (MethodBuilder, block))
3916 public bool ResolveMembers ()
3918 if (!DefineGenericMethod ())
3921 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
3922 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
3923 if (iterator == null)
3927 if (anonymous_methods != null) {
3928 foreach (AnonymousMethodExpression ame in anonymous_methods) {
3929 if (!ame.CreateAnonymousHelpers ())
3937 public override bool Define ()
3942 if (!CheckAbstractAndExtern (block != null))
3945 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3946 for (int i = 0; i < Parameters.Count; ++i ) {
3947 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
3948 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3949 GetSignatureForError ());
3958 if (IsPartialDefinition) {
3959 caching_flags &= ~Flags.Excluded_Undetected;
3960 caching_flags |= Flags.Excluded;
3961 // Add to member cache only when a partial method implementation is not there
3962 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3963 MethodBase mb = new PartialMethodDefinitionInfo (this);
3964 Parent.MemberCache.AddMember (mb, this);
3965 TypeManager.AddMethod (mb, this);
3971 MethodData = new MethodData (
3972 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3974 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3977 MethodBuilder = MethodData.MethodBuilder;
3980 if (MethodBuilder.IsGenericMethod)
3981 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3984 Parent.MemberCache.AddMember (MethodBuilder, this);
3986 if (!TypeManager.IsGenericParameter (MemberType)) {
3987 if (MemberType.IsAbstract && MemberType.IsSealed) {
3988 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3996 public override void Emit ()
3999 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
4000 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
4002 if (OptAttributes != null)
4003 OptAttributes.Emit ();
4005 if (declarative_security != null) {
4006 foreach (DictionaryEntry de in declarative_security) {
4007 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4014 protected void Error_ConditionalAttributeIsNotValid ()
4016 Report.Error (577, Location,
4017 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4018 GetSignatureForError ());
4021 public bool IsPartialDefinition {
4023 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
4027 public bool IsPartialImplementation {
4029 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
4033 public override string[] ValidAttributeTargets {
4035 return attribute_targets;
4039 #region IMethodData Members
4041 public CallingConventions CallingConventions {
4043 CallingConventions cc = Parameters.CallingConvention;
4045 if ((ModFlags & Modifiers.STATIC) == 0)
4046 cc |= CallingConventions.HasThis;
4048 // FIXME: How is `ExplicitThis' used in C#?
4054 public Type ReturnType {
4060 public MemberName MethodName {
4066 public Iterator Iterator {
4067 get { return iterator; }
4070 protected override bool CheckBase ()
4072 if (!base.CheckBase ())
4075 // TODO: Destructor should derive from MethodCore
4076 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4077 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4078 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4086 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4088 public bool IsExcluded () {
4089 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4090 return (caching_flags & Flags.Excluded) != 0;
4092 caching_flags &= ~Flags.Excluded_Undetected;
4094 if (base_method == null) {
4095 if (OptAttributes == null)
4098 if (TypeManager.conditional_attribute_type == null)
4101 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4106 foreach (Attribute a in attrs) {
4107 string condition = a.GetConditionalAttributeValue ();
4108 if (condition == null)
4111 if (RootContext.AllDefines.Contains (condition))
4115 caching_flags |= Flags.Excluded;
4119 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4121 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4122 caching_flags |= Flags.Excluded;
4128 if (md.IsExcluded ()) {
4129 caching_flags |= Flags.Excluded;
4135 GenericMethod IMethodData.GenericMethod {
4137 return GenericMethod;
4141 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4148 public class SourceMethod : IMethodDef
4152 SourceMethodBuilder builder;
4154 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4156 this.parent = parent;
4157 this.method = method;
4159 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4162 public string Name {
4163 get { return method.Name; }
4168 if (method is MethodBuilder)
4169 return ((MethodBuilder) method).GetToken ().Token;
4170 else if (method is ConstructorBuilder)
4171 return ((ConstructorBuilder) method).GetToken ().Token;
4173 throw new NotSupportedException ();
4177 public void CloseMethod ()
4179 SymbolWriter.CloseMethod ();
4182 public void SetCompilerGenerated ()
4184 if (builder != null)
4185 builder.SetCompilerGenerated ();
4188 public void SetRealMethodName (string name)
4190 if (builder != null)
4191 builder.SetRealMethodName (name);
4194 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4196 if (!SymbolWriter.HasSymbolWriter)
4201 Location start_loc = block.StartLocation;
4202 if (start_loc.IsNull)
4205 ICompileUnit compile_unit = start_loc.CompilationUnit;
4206 if (compile_unit == null)
4209 return new SourceMethod (parent, method, compile_unit);
4213 public class Method : MethodOrOperator, IAnonymousHost {
4216 /// Modifiers allowed in a class declaration
4218 const int AllowedModifiers =
4221 Modifiers.PROTECTED |
4222 Modifiers.INTERNAL |
4227 Modifiers.OVERRIDE |
4228 Modifiers.ABSTRACT |
4230 Modifiers.METHOD_YIELDS |
4233 const int AllowedInterfaceModifiers =
4234 Modifiers.NEW | Modifiers.UNSAFE;
4237 // return_type can be "null" for VOID values.
4239 public Method (DeclSpace parent, GenericMethod generic,
4240 FullNamedExpression return_type, int mod, bool is_iface,
4241 MemberName name, Parameters parameters, Attributes attrs)
4242 : base (parent, generic, return_type, mod,
4243 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4244 is_iface, name, attrs, parameters)
4248 public override string GetSignatureForError()
4250 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4253 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4255 Report.Error (17, location,
4256 "Program `{0}' has more than one entry point defined: `{1}'",
4257 CodeGen.FileName, TypeManager.CSharpSignature(b));
4260 bool IsEntryPoint ()
4262 if (ReturnType != TypeManager.void_type &&
4263 ReturnType != TypeManager.int32_type)
4266 if (Parameters.Count == 0)
4269 if (Parameters.Count > 1)
4272 Type t = Parameters.ParameterType (0);
4273 return t.IsArray && t.GetArrayRank () == 1 &&
4274 TypeManager.GetElementType (t) == TypeManager.string_type &&
4275 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4278 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4280 if (a.Type == TypeManager.conditional_attribute_type) {
4281 if (IsExplicitImpl) {
4282 Error_ConditionalAttributeIsNotValid ();
4286 if (ReturnType != TypeManager.void_type) {
4287 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4291 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4292 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4297 Report.Error (582, Location, "Conditional not valid on interface members");
4301 if (MethodData.implementing != null) {
4302 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4303 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4304 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4308 for (int i = 0; i < Parameters.Count; ++i) {
4309 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4310 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4316 if (a.Type == TypeManager.extension_attribute_type) {
4317 a.Error_MisusedExtensionAttribute ();
4321 base.ApplyAttributeBuilder (a, cb);
4324 public bool CheckForDuplications ()
4326 ArrayList ar = Parent.PartialContainer.Properties;
4328 for (int i = 0; i < ar.Count; ++i) {
4329 PropertyBase pb = (PropertyBase) ar [i];
4330 if (pb.AreAccessorsDuplicateImplementation (this))
4335 ar = Parent.PartialContainer.Indexers;
4337 for (int i = 0; i < ar.Count; ++i) {
4338 PropertyBase pb = (PropertyBase) ar [i];
4339 if (pb.AreAccessorsDuplicateImplementation (this))
4350 public override bool Define ()
4352 if (!base.Define ())
4355 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4356 Error1599 (Location, ReturnType);
4360 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4361 Name == "Finalize" && !(this is Destructor)) {
4362 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4365 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4366 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4367 Parent.PartialContainer.Mark_HasEquals ();
4368 else if (Parameters.Empty && Name == "GetHashCode")
4369 Parent.PartialContainer.Mark_HasGetHashCode ();
4372 if ((ModFlags & Modifiers.STATIC) == 0)
4375 if (Parameters.HasExtensionMethodType) {
4376 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4377 if (!Parent.IsTopLevel)
4378 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4379 GetSignatureForError ());
4381 if (TypeManager.extension_attribute_type == null) {
4382 Report.Error (1110, Location,
4383 "`{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",
4384 GetSignatureForError ());
4385 } else if (TypeManager.extension_attribute_attr == null) {
4386 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4387 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4390 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4393 ModFlags |= Modifiers.METHOD_EXTENSION;
4394 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4395 CodeGen.Assembly.HasExtensionMethods = true;
4397 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4398 GetSignatureForError ());
4403 // This is used to track the Entry Point,
4405 if (RootContext.NeedsEntryPoint &&
4407 (RootContext.MainClass == null ||
4408 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4409 if (IsEntryPoint ()) {
4411 if (RootContext.EntryPoint == null) {
4412 if (Parent.IsGeneric || MemberName.IsGeneric) {
4413 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4414 GetSignatureForError ());
4416 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4417 md.SetMemberIsUsed ();
4419 RootContext.EntryPoint = MethodBuilder;
4420 RootContext.EntryPointLocation = Location;
4423 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4424 Error_DuplicateEntryPoint (MethodBuilder, Location);
4427 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4428 GetSignatureForError ());
4438 public override void Emit ()
4441 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4442 if (IsPartialDefinition) {
4444 // Do attribute checks only when partial implementation does not exist
4446 if (MethodBuilder == null)
4452 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4453 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4454 GetSignatureForError ());
4456 MethodData.Emit (Parent);
4460 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4461 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4467 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4468 Location, MethodBuilder);
4473 public override bool EnableOverloadChecks (MemberCore overload)
4475 // TODO: It can be deleted when members will be defined in correct order
4476 if (overload is Operator)
4477 return overload.EnableOverloadChecks (this);
4479 if (overload is Indexer)
4482 return base.EnableOverloadChecks (overload);
4485 public static void Error1599 (Location loc, Type t)
4487 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4490 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4492 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4493 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4498 if (mi.IsSpecialName)
4501 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4505 public void SetPartialDefinition (Method methodDefinition)
4507 caching_flags |= Flags.PartialDefinitionExists;
4508 methodDefinition.MethodBuilder = MethodBuilder;
4509 if (methodDefinition.attributes == null)
4512 if (attributes == null) {
4513 attributes = methodDefinition.attributes;
4515 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4519 protected override bool VerifyClsCompliance ()
4521 if (!base.VerifyClsCompliance ())
4524 if (ParameterInfo.Count > 0) {
4525 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4527 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4534 public abstract class ConstructorInitializer : ExpressionStatement
4536 ArrayList argument_list;
4537 MethodGroupExpr base_constructor_group;
4539 public ConstructorInitializer (ArrayList argument_list, Location loc)
4541 this.argument_list = argument_list;
4545 public ArrayList Arguments {
4547 return argument_list;
4551 public override Expression CreateExpressionTree (EmitContext ec)
4553 throw new NotSupportedException ("ET");
4556 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4558 if (argument_list != null){
4559 foreach (Argument a in argument_list){
4560 if (!a.Resolve (ec, loc))
4565 if (this is ConstructorBaseInitializer) {
4566 if (ec.ContainerType.BaseType == null)
4569 type = ec.ContainerType.BaseType;
4570 if (ec.ContainerType.IsValueType) {
4571 Report.Error (522, loc,
4572 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4577 // It is legal to have "this" initializers that take no arguments
4578 // in structs, they are just no-ops.
4580 // struct D { public D (int a) : this () {}
4582 if (ec.ContainerType.IsValueType && argument_list == null)
4585 type = ec.ContainerType;
4588 base_constructor_group = MemberLookupFinal (
4589 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4590 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4591 loc) as MethodGroupExpr;
4593 if (base_constructor_group == null)
4596 base_constructor_group = base_constructor_group.OverloadResolve (
4597 ec, ref argument_list, false, loc);
4599 if (base_constructor_group == null)
4602 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4604 if (base_ctor == caller_builder){
4605 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4611 public override Expression DoResolve (EmitContext ec)
4613 throw new NotSupportedException ();
4616 public override void Emit (EmitContext ec)
4618 // It can be null for static initializers
4619 if (base_constructor_group == null)
4622 ec.Mark (loc, false);
4624 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4626 base_constructor_group.EmitCall (ec, argument_list);
4629 public override void EmitStatement (EmitContext ec)
4635 public class ConstructorBaseInitializer : ConstructorInitializer {
4636 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4637 base (argument_list, l)
4642 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4643 public GeneratedBaseInitializer (Location loc):
4649 public class ConstructorThisInitializer : ConstructorInitializer {
4650 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4651 base (argument_list, l)
4656 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4657 public ConstructorBuilder ConstructorBuilder;
4658 public ConstructorInitializer Initializer;
4659 ListDictionary declarative_security;
4660 ArrayList anonymous_methods;
4661 bool has_compliant_args;
4664 // Modifiers allowed for a constructor.
4666 public const int AllowedModifiers =
4668 Modifiers.PROTECTED |
4669 Modifiers.INTERNAL |
4675 static readonly string[] attribute_targets = new string [] { "method" };
4678 // The spec claims that static is not permitted, but
4679 // my very own code has static constructors.
4681 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4682 ConstructorInitializer init, Location loc)
4683 : base (parent, null, null, mod, AllowedModifiers, false,
4684 new MemberName (name, loc), null, args)
4689 public bool HasCompliantArgs {
4690 get { return has_compliant_args; }
4693 public override AttributeTargets AttributeTargets {
4694 get { return AttributeTargets.Constructor; }
4697 public Iterator Iterator {
4698 get { return null; }
4702 // Returns true if this is a default constructor
4704 public bool IsDefault ()
4706 if ((ModFlags & Modifiers.STATIC) != 0)
4707 return Parameters.Empty;
4709 return Parameters.Empty &&
4710 (Initializer is ConstructorBaseInitializer) &&
4711 (Initializer.Arguments == null);
4714 public bool IsCompilerGenerated {
4715 get { return Initializer is GeneratedBaseInitializer; }
4718 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4720 if (a.IsValidSecurityAttribute ()) {
4721 if (declarative_security == null) {
4722 declarative_security = new ListDictionary ();
4724 a.ExtractSecurityPermissionSet (declarative_security);
4728 if (a.IsInternalMethodImplAttribute) {
4729 is_external_implementation = true;
4732 ConstructorBuilder.SetCustomAttribute (cb);
4735 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4737 if (anonymous_methods == null)
4738 anonymous_methods = new ArrayList ();
4739 anonymous_methods.Add (anonymous);
4742 public bool ResolveMembers ()
4744 if (anonymous_methods != null) {
4745 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4746 if (!ame.CreateAnonymousHelpers ())
4754 protected override bool CheckBase ()
4756 if ((ModFlags & Modifiers.STATIC) != 0) {
4757 if (!Parameters.Empty) {
4758 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4759 GetSignatureForError ());
4763 // the rest can be ignored
4767 // Check whether arguments were correct.
4768 if (!DefineParameters (Parameters))
4771 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4772 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4775 if (Parent.PartialContainer.Kind == Kind.Struct) {
4776 if (ParameterTypes.Length == 0) {
4777 Report.Error (568, Location,
4778 "Structs cannot contain explicit parameterless constructors");
4783 CheckProtectedModifier ();
4789 // Creates the ConstructorBuilder
4791 public override bool Define ()
4793 if (ConstructorBuilder != null)
4796 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4797 MethodAttributes.SpecialName);
4799 if ((ModFlags & Modifiers.STATIC) != 0) {
4800 ca |= MethodAttributes.Static | MethodAttributes.Private;
4802 ca |= MethodAttributes.HideBySig;
4804 if ((ModFlags & Modifiers.PUBLIC) != 0)
4805 ca |= MethodAttributes.Public;
4806 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4807 if ((ModFlags & Modifiers.INTERNAL) != 0)
4808 ca |= MethodAttributes.FamORAssem;
4810 ca |= MethodAttributes.Family;
4811 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4812 ca |= MethodAttributes.Assembly;
4814 ca |= MethodAttributes.Private;
4817 if (!CheckAbstractAndExtern (block != null))
4820 // Check if arguments were correct.
4824 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4825 ca, CallingConventions,
4828 if ((ModFlags & Modifiers.UNSAFE) != 0)
4829 ConstructorBuilder.InitLocals = false;
4831 if (Parent.PartialContainer.IsComImport) {
4832 if (!IsDefault ()) {
4833 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4834 Parent.GetSignatureForError ());
4837 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4840 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4841 TypeManager.AddMethod (ConstructorBuilder, this);
4843 // It's here only to report an error
4844 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4845 member_type = TypeManager.void_type;
4846 Iterator.CreateIterator (this, Parent, null, ModFlags);
4855 public override void Emit ()
4857 if (OptAttributes != null)
4858 OptAttributes.Emit ();
4862 EmitContext ec = CreateEmitContext (null, null);
4865 // If we use a "this (...)" constructor initializer, then
4866 // do not emit field initializers, they are initialized in the other constructor
4868 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4869 !(Initializer is ConstructorThisInitializer);
4871 if (emit_field_initializers)
4872 Parent.PartialContainer.ResolveFieldInitializers (ec);
4874 if (block != null) {
4875 // If this is a non-static `struct' constructor and doesn't have any
4876 // initializer, it must initialize all of the struct's fields.
4877 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4878 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4879 block.AddThisVariable (Parent, Location);
4881 if (!block.ResolveMeta (ec, ParameterInfo))
4884 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4885 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4886 Initializer = new GeneratedBaseInitializer (Location);
4889 // Spec mandates that Initializers will not have `this' access
4891 if (Initializer != null) {
4893 Initializer.Resolve (ConstructorBuilder, ec);
4894 ec.IsStatic = false;
4895 block.AddScopeStatement (new StatementExpression (Initializer));
4900 Parameters.ApplyAttributes (ConstructorBuilder);
4902 SourceMethod source = null;
4904 ec.OmitDebuggingInfo = true;
4906 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4908 bool unreachable = false;
4909 if (block != null) {
4910 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4913 ec.EmitMeta (block);
4915 if (Report.Errors > 0)
4918 if (emit_field_initializers)
4919 Parent.PartialContainer.EmitFieldInitializers (ec);
4921 if (block.ScopeInfo != null) {
4922 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4923 init.EmitStatement (ec);
4926 ec.EmitResolvedTopBlock (block, unreachable);
4930 source.CloseMethod ();
4932 if (declarative_security != null) {
4933 foreach (DictionaryEntry de in declarative_security) {
4934 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4941 // Is never override
4942 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4947 public override string GetSignatureForError()
4949 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4952 public override string[] ValidAttributeTargets {
4954 return attribute_targets;
4958 protected override bool VerifyClsCompliance ()
4960 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4964 if (ParameterInfo.Count > 0) {
4965 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4967 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4969 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4970 foreach (Type param in ParameterTypes) {
4971 if (param.IsArray) {
4977 has_compliant_args = true;
4981 #region IMethodData Members
4983 public System.Reflection.CallingConventions CallingConventions {
4985 CallingConventions cc = Parameters.CallingConvention;
4987 if (Parent.PartialContainer.Kind == Kind.Class)
4988 if ((ModFlags & Modifiers.STATIC) == 0)
4989 cc |= CallingConventions.HasThis;
4991 // FIXME: How is `ExplicitThis' used in C#?
4997 public MemberName MethodName {
5003 public Type ReturnType {
5009 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5011 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5012 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5013 ec.CurrentBlock = block;
5017 public bool IsExcluded()
5022 GenericMethod IMethodData.GenericMethod {
5028 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
5035 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5037 public interface IMethodData
5039 CallingConventions CallingConventions { get; }
5040 Location Location { get; }
5041 MemberName MethodName { get; }
5042 Type ReturnType { get; }
5043 GenericMethod GenericMethod { get; }
5044 Parameters ParameterInfo { get; }
5046 Iterator Iterator { get; }
5048 Attributes OptAttributes { get; }
5049 ToplevelBlock Block { get; set; }
5051 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5052 ObsoleteAttribute GetObsoleteAttribute ();
5053 string GetSignatureForError ();
5055 bool IsClsComplianceRequired ();
5056 void SetMemberIsUsed ();
5057 void EmitExtraSymbolInfo (SourceMethod source);
5061 // Encapsulates most of the Method's state
5063 public class MethodData {
5065 static FieldInfo methodbuilder_attrs_field;
5067 readonly IMethodData method;
5069 public readonly GenericMethod GenericMethod;
5072 // Are we implementing an interface ?
5074 public MethodInfo implementing;
5079 protected InterfaceMemberBase member;
5080 protected int modifiers;
5081 protected MethodAttributes flags;
5082 protected Type declaring_type;
5083 protected MethodInfo parent_method;
5085 MethodBuilder builder = null;
5086 public MethodBuilder MethodBuilder {
5092 public Type DeclaringType {
5094 return declaring_type;
5098 public MethodData (InterfaceMemberBase member,
5099 int modifiers, MethodAttributes flags, IMethodData method)
5101 this.member = member;
5102 this.modifiers = modifiers;
5105 this.method = method;
5108 public MethodData (InterfaceMemberBase member,
5109 int modifiers, MethodAttributes flags,
5110 IMethodData method, MethodBuilder builder,
5111 GenericMethod generic, MethodInfo parent_method)
5112 : this (member, modifiers, flags, method)
5114 this.builder = builder;
5115 this.GenericMethod = generic;
5116 this.parent_method = parent_method;
5119 public bool Define (DeclSpace parent, string method_full_name)
5121 string name = method.MethodName.Basename;
5123 TypeContainer container = parent.PartialContainer;
5125 PendingImplementation pending = container.PendingImplementations;
5126 if (pending != null){
5127 if (member is Indexer) // TODO: test it, but it should work without this IF
5128 implementing = pending.IsInterfaceIndexer (
5129 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5131 implementing = pending.IsInterfaceMethod (
5132 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5134 if (member.InterfaceType != null){
5135 if (implementing == null){
5136 if (member is PropertyBase) {
5137 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5138 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5139 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5142 Report.Error (539, method.Location,
5143 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5144 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5148 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5149 Report.SymbolRelatedToPreviousError (implementing);
5150 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5151 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5155 if (implementing != null) {
5156 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5157 if (prop_method == null) {
5158 if (TypeManager.IsSpecialMethod (implementing)) {
5159 Report.SymbolRelatedToPreviousError (implementing);
5160 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5161 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5162 implementing.Name.StartsWith ("get_") ? "get" : "set");
5164 } else if (implementing.DeclaringType.IsInterface) {
5165 if (!implementing.IsSpecialName) {
5166 Report.SymbolRelatedToPreviousError (implementing);
5167 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5168 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5171 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5172 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5173 Report.SymbolRelatedToPreviousError (implementing);
5174 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5175 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5184 // For implicit implementations, make sure we are public, for
5185 // explicit implementations, make sure we are private.
5187 if (implementing != null){
5189 // Setting null inside this block will trigger a more
5190 // verbose error reporting for missing interface implementations
5192 // The "candidate" function has been flagged already
5193 // but it wont get cleared
5195 if (member.IsExplicitImpl){
5196 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5197 Report.SymbolRelatedToPreviousError (implementing);
5198 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5199 method.GetSignatureForError ());
5203 if (implementing.DeclaringType.IsInterface) {
5205 // If this is an interface method implementation,
5206 // check for public accessibility
5208 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5210 implementing = null;
5212 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5213 // We may never be private.
5214 implementing = null;
5216 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5218 // We may be protected if we're overriding something.
5220 implementing = null;
5225 // Static is not allowed
5227 if ((modifiers & Modifiers.STATIC) != 0){
5228 implementing = null;
5233 // If implementing is still valid, set flags
5235 if (implementing != null){
5237 // When implementing interface methods, set NewSlot
5238 // unless, we are overwriting a method.
5240 if (implementing.DeclaringType.IsInterface){
5241 if ((modifiers & Modifiers.OVERRIDE) == 0)
5242 flags |= MethodAttributes.NewSlot;
5245 MethodAttributes.Virtual |
5246 MethodAttributes.HideBySig;
5248 // Set Final unless we're virtual, abstract or already overriding a method.
5249 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5250 flags |= MethodAttributes.Final;
5253 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5255 if (builder == null)
5258 if (container.CurrentType != null)
5259 declaring_type = container.CurrentType;
5261 declaring_type = container.TypeBuilder;
5263 if ((modifiers & Modifiers.UNSAFE) != 0)
5264 builder.InitLocals = false;
5267 if (implementing != null){
5269 // clear the pending implemntation flag
5271 if (member is Indexer) {
5272 pending.ImplementIndexer (
5273 member.InterfaceType, builder, method.ReturnType,
5274 method.ParameterInfo, member.IsExplicitImpl);
5276 pending.ImplementMethod (
5277 member.InterfaceType, name, method.ReturnType,
5278 method.ParameterInfo, member.IsExplicitImpl);
5280 if (member.IsExplicitImpl)
5281 container.TypeBuilder.DefineMethodOverride (
5282 builder, implementing);
5285 TypeManager.AddMethod (builder, method);
5287 if (GenericMethod != null) {
5288 bool is_override = member.IsExplicitImpl |
5289 ((modifiers & Modifiers.OVERRIDE) != 0);
5291 if (implementing != null)
5292 parent_method = implementing;
5294 EmitContext ec = method.CreateEmitContext (container, null);
5295 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5304 /// Create the MethodBuilder for the method
5306 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5308 if (builder == null) {
5309 builder = container.TypeBuilder.DefineMethod (
5310 method_name, flags, method.CallingConventions,
5311 method.ReturnType, ParameterTypes);
5317 // Generic method has been already defined to resolve method parameters
5318 // correctly when they use type parameters
5320 builder.SetParameters (ParameterTypes);
5321 builder.SetReturnType (method.ReturnType);
5323 if (builder.Attributes != flags) {
5325 if (methodbuilder_attrs_field == null)
5326 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5327 methodbuilder_attrs_field.SetValue (builder, flags);
5329 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5333 throw new InternalErrorException ();
5340 public void Emit (DeclSpace parent)
5342 ToplevelBlock block = method.Block;
5346 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5348 ec = method.CreateEmitContext (parent, null);
5350 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5352 if (GenericMethod != null)
5353 GenericMethod.EmitAttributes ();
5355 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5358 // Handle destructors specially
5360 // FIXME: This code generates buggy code
5362 if (member is Destructor)
5363 EmitDestructor (ec, block);
5365 ec.EmitTopBlock (method, block);
5367 if (source != null) {
5368 method.EmitExtraSymbolInfo (source);
5369 if (method.Iterator != null)
5370 source.SetCompilerGenerated ();
5371 source.CloseMethod ();
5375 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5377 ILGenerator ig = ec.ig;
5379 Label finish = ig.DefineLabel ();
5381 block.SetDestructor ();
5383 ig.BeginExceptionBlock ();
5384 ec.ReturnLabel = finish;
5385 ec.HasReturnLabel = true;
5386 ec.EmitTopBlock (method, block);
5388 // ig.MarkLabel (finish);
5389 ig.BeginFinallyBlock ();
5391 if (ec.ContainerType.BaseType != null) {
5392 Expression member_lookup = Expression.MemberLookup (
5393 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5394 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5396 if (member_lookup != null){
5397 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5399 ig.Emit (OpCodes.Ldarg_0);
5400 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5404 ig.EndExceptionBlock ();
5405 //ig.MarkLabel (ec.ReturnLabel);
5406 ig.Emit (OpCodes.Ret);
5410 // TODO: Should derive from MethodCore
5411 public class Destructor : Method {
5413 static string[] attribute_targets = new string [] { "method" };
5415 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5416 string name, Parameters parameters, Attributes attrs,
5418 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5422 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5424 if (a.Type == TypeManager.conditional_attribute_type) {
5425 Error_ConditionalAttributeIsNotValid ();
5429 base.ApplyAttributeBuilder (a, cb);
5432 public override string GetSignatureForError ()
5434 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5437 public override string[] ValidAttributeTargets {
5439 return attribute_targets;
5444 abstract public class MemberBase : MemberCore {
5445 protected FullNamedExpression type_name;
5446 public readonly DeclSpace ds;
5447 public readonly GenericMethod GenericMethod;
5450 // The type of this property / indexer / event
5452 protected Type member_type;
5453 public Type MemberType {
5455 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5456 if (member_type == null && type_name != null) {
5457 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5458 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5459 if (type_name != null) {
5460 member_type = type_name.Type;
5468 // The constructor is only exposed to our children
5470 protected MemberBase (DeclSpace parent, GenericMethod generic,
5471 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5472 MemberName name, Attributes attrs)
5473 : base (parent, name, attrs)
5475 this.ds = generic != null ? generic : (DeclSpace) parent;
5476 this.type_name = type;
5477 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5478 GenericMethod = generic;
5479 if (GenericMethod != null)
5480 GenericMethod.ModFlags = ModFlags;
5483 protected virtual bool CheckBase ()
5485 CheckProtectedModifier ();
5490 protected virtual bool DoDefine ()
5492 if (MemberType == null)
5495 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5496 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5497 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5498 GetSignatureForError (), Parent.GetSignatureForError ());
5502 // verify accessibility
5503 if (!IsAccessibleAs (MemberType)) {
5504 Report.SymbolRelatedToPreviousError (MemberType);
5505 if (this is Property)
5506 Report.Error (53, Location,
5507 "Inconsistent accessibility: property type `" +
5508 TypeManager.CSharpName (MemberType) + "' is less " +
5509 "accessible than property `" + GetSignatureForError () + "'");
5510 else if (this is Indexer)
5511 Report.Error (54, Location,
5512 "Inconsistent accessibility: indexer return type `" +
5513 TypeManager.CSharpName (MemberType) + "' is less " +
5514 "accessible than indexer `" + GetSignatureForError () + "'");
5515 else if (this is MethodCore) {
5516 if (this is Operator)
5517 Report.Error (56, Location,
5518 "Inconsistent accessibility: return type `" +
5519 TypeManager.CSharpName (MemberType) + "' is less " +
5520 "accessible than operator `" + GetSignatureForError () + "'");
5522 Report.Error (50, Location,
5523 "Inconsistent accessibility: return type `" +
5524 TypeManager.CSharpName (MemberType) + "' is less " +
5525 "accessible than method `" + GetSignatureForError () + "'");
5527 Report.Error (52, Location,
5528 "Inconsistent accessibility: field type `" +
5529 TypeManager.CSharpName (MemberType) + "' is less " +
5530 "accessible than field `" + GetSignatureForError () + "'");
5538 protected bool IsTypePermitted ()
5540 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5541 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5549 // Abstract class for all fields
5551 abstract public class FieldBase : MemberBase {
5552 public FieldBuilder FieldBuilder;
5553 public Status status;
5554 protected Expression initializer;
5557 public enum Status : byte {
5558 HAS_OFFSET = 4 // Used by FieldMember.
5561 static readonly string[] attribute_targets = new string [] { "field" };
5563 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5564 int allowed_mod, MemberName name, Attributes attrs)
5565 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5568 if ((mod & Modifiers.ABSTRACT) != 0)
5569 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5572 public override AttributeTargets AttributeTargets {
5574 return AttributeTargets.Field;
5578 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5580 if (a.Type == TypeManager.field_offset_attribute_type) {
5581 status |= Status.HAS_OFFSET;
5583 if (!Parent.PartialContainer.HasExplicitLayout) {
5584 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5588 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5589 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5595 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5596 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5601 if (a.Type == TypeManager.marshal_as_attr_type) {
5602 UnmanagedMarshal marshal = a.GetMarshal (this);
5603 if (marshal != null) {
5604 FieldBuilder.SetMarshal (marshal);
5609 if ((a.HasSecurityAttribute)) {
5610 a.Error_InvalidSecurityParent ();
5614 FieldBuilder.SetCustomAttribute (cb);
5617 protected override bool CheckBase ()
5619 if (!base.CheckBase ())
5622 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5623 if (conflict_symbol == null) {
5624 if ((ModFlags & Modifiers.NEW) != 0) {
5625 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5630 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5631 Report.SymbolRelatedToPreviousError (conflict_symbol);
5632 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5633 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5639 public override bool Define()
5641 if (MemberType == null || member_type == null)
5644 if (TypeManager.IsGenericParameter (MemberType))
5647 if (MemberType == TypeManager.void_type) {
5648 // TODO: wrong location
5649 Expression.Error_VoidInvalidInTheContext (Location);
5653 if (MemberType.IsSealed && MemberType.IsAbstract) {
5654 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5664 if (!IsTypePermitted ())
5671 // Represents header string for documentation comment.
5673 public override string DocCommentHeader {
5674 get { return "F:"; }
5677 public override void Emit ()
5680 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5681 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5685 if (OptAttributes != null) {
5686 OptAttributes.Emit ();
5689 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5690 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5696 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5698 Report.SymbolRelatedToPreviousError (static_class);
5699 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5703 public Expression Initializer {
5705 if (value != null) {
5706 this.initializer = value;
5711 protected virtual bool IsFieldClsCompliant {
5713 if (FieldBuilder == null)
5716 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5720 public override string[] ValidAttributeTargets
5723 return attribute_targets;
5727 protected override bool VerifyClsCompliance ()
5729 if (!base.VerifyClsCompliance ())
5732 if (!IsFieldClsCompliant) {
5733 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5738 public void SetAssigned ()
5740 caching_flags |= Flags.IsAssigned;
5744 interface IFixedBuffer
5746 FieldInfo Element { get; }
5747 Type ElementType { get; }
5750 public class FixedFieldExternal: IFixedBuffer
5752 FieldInfo element_field;
5754 public FixedFieldExternal (FieldInfo fi)
5756 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5759 #region IFixedField Members
5761 public FieldInfo Element {
5763 return element_field;
5767 public Type ElementType {
5769 return element_field.FieldType;
5777 /// Fixed buffer implementation
5779 public class FixedField : FieldBase, IFixedBuffer
5781 public const string FixedElementName = "FixedElementField";
5782 static int GlobalCounter = 0;
5783 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5784 static FieldInfo[] fi;
5786 TypeBuilder fixed_buffer_type;
5787 FieldBuilder element;
5788 Expression size_expr;
5790 const int AllowedModifiers =
5793 Modifiers.PROTECTED |
5794 Modifiers.INTERNAL |
5797 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5798 Expression size_expr, Attributes attrs, Location loc):
5799 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5801 if (RootContext.Version == LanguageVersion.ISO_1)
5802 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5804 this.size_expr = size_expr;
5807 public override bool Define()
5809 if (!Parent.IsInUnsafeScope)
5810 Expression.UnsafeError (Location);
5812 if (!base.Define ())
5815 if (!TypeManager.IsPrimitiveType (MemberType)) {
5816 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",
5817 GetSignatureForError ());
5820 // Create nested fixed buffer container
5821 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5822 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5823 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5825 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5826 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5828 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5829 Parent.MemberCache.AddMember (FieldBuilder, this);
5830 TypeManager.RegisterFieldBase (FieldBuilder, this);
5835 public override void Emit()
5837 if (Parent.PartialContainer.Kind != Kind.Struct) {
5838 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5839 GetSignatureForError ());
5842 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5843 Constant c = size_expr.ResolveAsConstant (ec, this);
5847 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5848 if (buffer_size_const == null)
5851 int buffer_size = buffer_size_const.Value;
5853 if (buffer_size <= 0) {
5854 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5858 int type_size = Expression.GetTypeSize (MemberType);
5860 if (buffer_size > int.MaxValue / type_size) {
5861 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5862 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5866 buffer_size *= type_size;
5867 EmitFieldSize (buffer_size);
5871 void EmitFieldSize (int buffer_size)
5873 if (TypeManager.struct_layout_attribute_type == null) {
5874 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5875 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5877 if (TypeManager.struct_layout_attribute_type == null)
5882 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5884 object [] fi_val = new object [] { buffer_size };
5886 if (TypeManager.struct_layout_attribute_ctor == null) {
5887 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5888 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5889 if (TypeManager.struct_layout_attribute_ctor == null)
5893 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5894 ctor_args, fi, fi_val);
5895 fixed_buffer_type.SetCustomAttribute (cab);
5898 // Don't emit FixedBufferAttribute attribute for private types
5900 if ((ModFlags & Modifiers.PRIVATE) != 0)
5903 if (TypeManager.fixed_buffer_attr_ctor == null) {
5904 if (TypeManager.fixed_buffer_attr_type == null) {
5905 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5906 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5908 if (TypeManager.fixed_buffer_attr_type == null)
5912 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5913 Location, TypeManager.type_type, TypeManager.int32_type);
5915 if (TypeManager.fixed_buffer_attr_ctor == null)
5919 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5920 FieldBuilder.SetCustomAttribute (cab);
5923 protected override bool IsFieldClsCompliant {
5929 #region IFixedField Members
5931 public FieldInfo Element {
5937 public Type ElementType {
5947 // The Field class is used to represents class/struct fields during parsing.
5949 public class Field : FieldBase {
5951 // Modifiers allowed in a class declaration
5953 const int AllowedModifiers =
5956 Modifiers.PROTECTED |
5957 Modifiers.INTERNAL |
5960 Modifiers.VOLATILE |
5964 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5965 Attributes attrs, Location loc)
5966 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5971 bool CanBeVolatile ()
5973 if (TypeManager.IsReferenceType (MemberType))
5976 if (MemberType.IsEnum)
5979 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5980 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5981 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5982 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5983 MemberType == TypeManager.float_type)
5989 public override bool Define ()
5991 if (!base.Define ())
5994 if ((ModFlags & Modifiers.VOLATILE) != 0){
5995 if (!CanBeVolatile ()) {
5996 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5997 GetSignatureForError (), TypeManager.CSharpName (MemberType));
6000 if ((ModFlags & Modifiers.READONLY) != 0){
6001 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6002 GetSignatureForError ());
6006 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6010 Type[] required_modifier = null;
6011 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6012 if (TypeManager.isvolatile_type == null)
6013 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
6014 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
6016 if (TypeManager.isvolatile_type != null)
6017 required_modifier = new Type [] { TypeManager.isvolatile_type };
6020 FieldBuilder = Parent.TypeBuilder.DefineField (
6021 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
6023 FieldBuilder = Parent.TypeBuilder.DefineField (
6024 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6026 Parent.MemberCache.AddMember (FieldBuilder, this);
6027 TypeManager.RegisterFieldBase (FieldBuilder, this);
6029 catch (ArgumentException) {
6030 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6034 if (initializer != null)
6035 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
6036 new FieldInitializer (FieldBuilder, initializer));
6038 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
6039 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
6040 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
6041 GetSignatureForError ());
6048 public override string GetSignatureForError ()
6050 string s = base.GetSignatureForError ();
6051 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
6054 // Undecorate name mangling
6055 int l = s.LastIndexOf ('>');
6056 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
6059 protected override bool VerifyClsCompliance ()
6061 if (!base.VerifyClsCompliance ())
6064 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6065 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6073 // `set' and `get' accessors are represented with an Accessor.
6075 public class Accessor : IAnonymousHost {
6077 // Null if the accessor is empty, or a Block if not
6079 public const int AllowedModifiers =
6081 Modifiers.PROTECTED |
6082 Modifiers.INTERNAL |
6085 public ToplevelBlock Block;
6086 public Attributes Attributes;
6087 public Location Location;
6088 public int ModFlags;
6090 public ArrayList AnonymousMethods;
6092 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6097 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6100 public void SetYields ()
6105 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6107 if (AnonymousMethods == null)
6108 AnonymousMethods = new ArrayList ();
6109 AnonymousMethods.Add (ame);
6113 // Ooouh Martin, templates are missing here.
6114 // When it will be possible move here a lot of child code and template method type.
6115 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6116 protected MethodData method_data;
6117 protected ToplevelBlock block;
6118 protected ListDictionary declarative_security;
6120 // The accessor are created event if they are not wanted.
6121 // But we need them because their names are reserved.
6122 // Field says whether accessor will be emited or not
6123 public readonly bool IsDummy;
6125 protected readonly string prefix;
6127 ReturnParameter return_attributes;
6129 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6130 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6132 this.prefix = prefix;
6136 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6138 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6139 accessor.Attributes)
6141 this.prefix = prefix;
6142 this.block = accessor.Block;
6145 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6147 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6150 public void UpdateName (InterfaceMemberBase member)
6152 SetMemberName (SetupName (prefix, member, Location));
6155 #region IMethodData Members
6157 public abstract Iterator Iterator {
6161 public ToplevelBlock Block {
6171 public CallingConventions CallingConventions {
6173 return CallingConventions.Standard;
6177 public bool IsExcluded ()
6182 GenericMethod IMethodData.GenericMethod {
6188 public MemberName MethodName {
6194 public Type[] ParameterTypes {
6196 return ParameterInfo.Types;
6200 public abstract Parameters ParameterInfo { get ; }
6201 public abstract Type ReturnType { get; }
6202 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6206 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6208 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6209 a.Type == TypeManager.conditional_attribute_type) {
6210 Report.Error (1667, a.Location,
6211 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6212 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6216 if (a.IsValidSecurityAttribute ()) {
6217 if (declarative_security == null)
6218 declarative_security = new ListDictionary ();
6219 a.ExtractSecurityPermissionSet (declarative_security);
6223 if (a.Target == AttributeTargets.Method) {
6224 method_data.MethodBuilder.SetCustomAttribute (cb);
6228 if (a.Target == AttributeTargets.ReturnValue) {
6229 if (return_attributes == null)
6230 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6232 return_attributes.ApplyAttributeBuilder (a, cb);
6236 ApplyToExtraTarget (a, cb);
6239 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6241 throw new NotSupportedException ("You forgot to define special attribute target handling");
6244 // It is not supported for the accessors
6245 public sealed override bool Define()
6247 throw new NotSupportedException ();
6250 public void Emit (DeclSpace parent)
6252 EmitMethod (parent);
6255 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6256 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6258 if (OptAttributes != null)
6259 OptAttributes.Emit ();
6261 if (declarative_security != null) {
6262 foreach (DictionaryEntry de in declarative_security) {
6263 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6270 protected virtual void EmitMethod (DeclSpace parent)
6272 method_data.Emit (parent);
6275 public override bool EnableOverloadChecks (MemberCore overload)
6277 // This can only happen with indexers and it will
6278 // be catched as indexer difference
6279 if (overload is AbstractPropertyEventMethod)
6282 if (overload is MethodCore) {
6283 caching_flags |= Flags.MethodOverloadsExist;
6289 public override bool IsClsComplianceRequired()
6294 public bool IsDuplicateImplementation (MethodCore method)
6296 if (!MemberName.Equals (method.MemberName))
6299 Type[] param_types = method.ParameterTypes;
6301 if (param_types == null || param_types.Length != ParameterTypes.Length)
6304 for (int i = 0; i < param_types.Length; i++)
6305 if (param_types [i] != ParameterTypes [i])
6308 Report.SymbolRelatedToPreviousError (method);
6309 Report.Error (82, Location, "A member `{0}' is already reserved",
6310 method.GetSignatureForError ());
6314 public override bool IsUsed
6324 public virtual bool ResolveMembers ()
6330 // Represents header string for documentation comment.
6332 public override string DocCommentHeader {
6333 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6336 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6341 // Properties and Indexers both generate PropertyBuilders, we use this to share
6342 // their common bits.
6344 abstract public class PropertyBase : PropertyBasedMember {
6346 public class GetMethod : PropertyMethod
6348 static string[] attribute_targets = new string [] { "method", "return" };
6350 public GetMethod (PropertyBase method):
6351 base (method, "get_")
6355 public GetMethod (PropertyBase method, Accessor accessor):
6356 base (method, accessor, "get_")
6360 public override MethodBuilder Define (DeclSpace parent)
6362 if (!CheckForDuplications ())
6368 base.Define (parent);
6370 method_data = new MethodData (method, ModFlags, flags, this);
6372 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6375 return method_data.MethodBuilder;
6378 public override Type ReturnType {
6380 return method.MemberType;
6384 public override Parameters ParameterInfo {
6386 return Parameters.EmptyReadOnlyParameters;
6390 public override string[] ValidAttributeTargets {
6392 return attribute_targets;
6397 public class SetMethod : PropertyMethod {
6399 static string[] attribute_targets = new string [] { "method", "param", "return" };
6400 ImplicitParameter param_attr;
6401 protected Parameters parameters;
6403 public SetMethod (PropertyBase method):
6404 base (method, "set_")
6408 public SetMethod (PropertyBase method, Accessor accessor):
6409 base (method, accessor, "set_")
6413 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6415 if (a.Target == AttributeTargets.Parameter) {
6416 if (param_attr == null)
6417 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6419 param_attr.ApplyAttributeBuilder (a, cb);
6423 base.ApplyAttributeBuilder (a, cb);
6426 public override Parameters ParameterInfo {
6428 if (parameters == null)
6429 DefineParameters ();
6434 protected virtual void DefineParameters ()
6436 parameters = Parameters.CreateFullyResolved (
6437 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6440 public override MethodBuilder Define (DeclSpace parent)
6442 if (!CheckForDuplications ())
6448 base.Define (parent);
6450 method_data = new MethodData (method, ModFlags, flags, this);
6452 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6455 return method_data.MethodBuilder;
6458 public override Type ReturnType {
6460 return TypeManager.void_type;
6464 public override string[] ValidAttributeTargets {
6466 return attribute_targets;
6471 static string[] attribute_targets = new string [] { "property" };
6473 public abstract class PropertyMethod : AbstractPropertyEventMethod
6475 protected readonly PropertyBase method;
6476 protected MethodAttributes flags;
6478 ArrayList anonymous_methods;
6481 public PropertyMethod (PropertyBase method, string prefix)
6482 : base (method, prefix)
6484 this.method = method;
6487 public PropertyMethod (PropertyBase method, Accessor accessor,
6489 : base (method, accessor, prefix)
6491 this.method = method;
6492 this.ModFlags = accessor.ModFlags;
6493 yields = accessor.Yields;
6494 anonymous_methods = accessor.AnonymousMethods;
6496 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6497 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6501 public override Iterator Iterator {
6502 get { return iterator; }
6505 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6507 if (a.IsInternalMethodImplAttribute) {
6508 method.is_external_implementation = true;
6511 base.ApplyAttributeBuilder (a, cb);
6514 public override AttributeTargets AttributeTargets {
6516 return AttributeTargets.Method;
6520 public override bool IsClsComplianceRequired ()
6522 return method.IsClsComplianceRequired ();
6525 public override bool ResolveMembers ()
6528 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6529 if (iterator == null)
6533 if (anonymous_methods != null) {
6534 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6535 if (!ame.CreateAnonymousHelpers ())
6543 public virtual MethodBuilder Define (DeclSpace parent)
6545 TypeContainer container = parent.PartialContainer;
6548 // Check for custom access modifier
6550 if ((ModFlags & Modifiers.Accessibility) == 0) {
6551 ModFlags |= method.ModFlags;
6552 flags = method.flags;
6554 if (container.Kind == Kind.Interface)
6555 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6556 GetSignatureForError ());
6558 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6559 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6562 CheckModifiers (ModFlags);
6563 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6564 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6565 flags = Modifiers.MethodAttr (ModFlags);
6566 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6569 CheckAbstractAndExtern (block != null);
6573 public bool HasCustomAccessModifier
6576 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6580 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6582 return new EmitContext (method,
6583 ds, method.ds, method.Location, ig, ReturnType,
6584 method.ModFlags, false);
6587 public override ObsoleteAttribute GetObsoleteAttribute ()
6589 return method.GetObsoleteAttribute ();
6592 public override string GetSignatureForError()
6594 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6597 void CheckModifiers (int modflags)
6599 modflags &= Modifiers.Accessibility;
6601 int mflags = method.ModFlags & Modifiers.Accessibility;
6603 if ((mflags & Modifiers.PUBLIC) != 0) {
6604 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6606 else if ((mflags & Modifiers.PROTECTED) != 0) {
6607 if ((mflags & Modifiers.INTERNAL) != 0)
6608 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6610 flags |= Modifiers.PRIVATE;
6612 else if ((mflags & Modifiers.INTERNAL) != 0)
6613 flags |= Modifiers.PRIVATE;
6615 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6616 Report.Error (273, Location,
6617 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6618 GetSignatureForError (), method.GetSignatureForError ());
6622 protected bool CheckForDuplications ()
6624 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6627 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6631 public PropertyMethod Get, Set;
6632 public PropertyBuilder PropertyBuilder;
6633 public MethodBuilder GetBuilder, SetBuilder;
6635 protected bool define_set_first = false;
6637 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6638 int allowed_mod, bool is_iface, MemberName name,
6639 Attributes attrs, bool define_set_first)
6640 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6642 this.define_set_first = define_set_first;
6645 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6647 if (a.HasSecurityAttribute) {
6648 a.Error_InvalidSecurityParent ();
6652 PropertyBuilder.SetCustomAttribute (cb);
6655 public override AttributeTargets AttributeTargets {
6657 return AttributeTargets.Property;
6661 public override bool Define ()
6666 if (!IsTypePermitted ())
6672 protected override bool DoDefine ()
6674 if (!base.DoDefine ())
6678 // Accessors modifiers check
6680 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6681 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6682 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6683 GetSignatureForError ());
6687 if ((Get.IsDummy || Set.IsDummy)
6688 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6689 Report.Error (276, Location,
6690 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6691 GetSignatureForError ());
6696 if (MemberType.IsGenericParameter)
6700 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6701 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6710 GetBuilder = Get.Define (Parent);
6711 return (Get.IsDummy) ? true : GetBuilder != null;
6714 bool DefineSet (bool define)
6719 SetBuilder = Set.Define (Parent);
6720 return (Set.IsDummy) ? true : SetBuilder != null;
6723 protected bool DefineAccessors ()
6725 return DefineSet (define_set_first) &&
6727 DefineSet (!define_set_first);
6730 protected abstract PropertyInfo ResolveBaseProperty ();
6732 // TODO: rename to Resolve......
6733 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6735 PropertyInfo base_property = ResolveBaseProperty ();
6736 if (base_property == null)
6739 base_ret_type = base_property.PropertyType;
6740 MethodInfo get_accessor = base_property.GetGetMethod (true);
6741 MethodInfo set_accessor = base_property.GetSetMethod (true);
6742 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6745 // Check base property accessors conflict
6747 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6748 if (get_accessor == null) {
6749 if (Get != null && !Get.IsDummy) {
6750 Report.SymbolRelatedToPreviousError (base_property);
6751 Report.Error (545, Location,
6752 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6753 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6756 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6758 if (!Get.IsDummy && !CheckAccessModifiers (
6759 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6760 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6763 if (set_accessor == null) {
6764 if (Set != null && !Set.IsDummy) {
6765 Report.SymbolRelatedToPreviousError (base_property);
6766 Report.Error (546, Location,
6767 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6768 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6771 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6773 if (!Set.IsDummy && !CheckAccessModifiers (
6774 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6775 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6779 // When one accessor does not exist and property hides base one
6780 // we need to propagate this upwards
6781 if (set_accessor == null)
6782 set_accessor = get_accessor;
6785 // Get the less restrictive access
6787 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6790 public override void Emit ()
6793 // The PropertyBuilder can be null for explicit implementations, in that
6794 // case, we do not actually emit the ".property", so there is nowhere to
6795 // put the attribute
6797 if (PropertyBuilder != null && OptAttributes != null)
6798 OptAttributes.Emit ();
6810 /// Tests whether accessors are not in collision with some method (CS0111)
6812 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6814 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6817 public override bool IsUsed
6823 return Get.IsUsed | Set.IsUsed;
6827 protected override void SetMemberName (MemberName new_name)
6829 base.SetMemberName (new_name);
6831 Get.UpdateName (this);
6832 Set.UpdateName (this);
6835 public override string[] ValidAttributeTargets {
6837 return attribute_targets;
6842 // Represents header string for documentation comment.
6844 public override string DocCommentHeader {
6845 get { return "P:"; }
6849 public class Property : PropertyBase {
6850 const int AllowedModifiers =
6853 Modifiers.PROTECTED |
6854 Modifiers.INTERNAL |
6858 Modifiers.OVERRIDE |
6859 Modifiers.ABSTRACT |
6862 Modifiers.METHOD_YIELDS |
6865 const int AllowedInterfaceModifiers =
6868 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6871 Field field = new Field (
6873 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6874 "<" + Name + ">k__BackingField", null, Location);
6875 ((TypeContainer)Parent).PartialContainer.AddField (field);
6878 get_block.Block = new ToplevelBlock (block, null, Location);
6879 Return r = new Return (new SimpleName(field.Name, Location), Location);
6880 get_block.Block.AddStatement (r);
6881 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6884 Parameters parameters = new Parameters (new Parameter (type_name, "value", Parameter.Modifier.NONE, null, Location));
6885 set_block.Block = new ToplevelBlock (block, parameters, Location);
6886 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6887 set_block.Block.AddStatement (new StatementExpression(a));
6888 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6891 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6892 MemberName name, Attributes attrs, Accessor get_block,
6893 Accessor set_block, bool define_set_first)
6894 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6895 define_set_first, null)
6899 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6900 MemberName name, Attributes attrs, Accessor get_block,
6901 Accessor set_block, bool define_set_first, Block current_block)
6902 : base (parent, type, mod,
6903 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6904 is_iface, name, attrs, define_set_first)
6906 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6907 get_block != null && get_block.Block == null &&
6908 set_block != null && set_block.Block == null) {
6909 if (RootContext.Version <= LanguageVersion.ISO_2)
6910 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6912 CreateAutomaticProperty (current_block, get_block, set_block);
6915 if (get_block == null)
6916 Get = new GetMethod (this);
6918 Get = new GetMethod (this, get_block);
6920 if (set_block == null)
6921 Set = new SetMethod (this);
6923 Set = new SetMethod (this, set_block);
6926 public override bool Define ()
6928 if (!DoDefineBase ())
6931 if (!base.Define ())
6934 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6936 if (!DefineAccessors ())
6942 // FIXME - PropertyAttributes.HasDefault ?
6944 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6945 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6948 PropertyBuilder.SetGetMethod (GetBuilder);
6949 Parent.MemberCache.AddMember (GetBuilder, Get);
6953 PropertyBuilder.SetSetMethod (SetBuilder);
6954 Parent.MemberCache.AddMember (SetBuilder, Set);
6957 TypeManager.RegisterProperty (PropertyBuilder, this);
6958 Parent.MemberCache.AddMember (PropertyBuilder, this);
6962 protected override PropertyInfo ResolveBaseProperty ()
6964 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6965 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6970 /// Gigantic workaround for lameness in SRE follows :
6971 /// This class derives from EventInfo and attempts to basically
6972 /// wrap around the EventBuilder so that FindMembers can quickly
6973 /// return this in it search for members
6975 public class MyEventBuilder : EventInfo {
6978 // We use this to "point" to our Builder which is
6979 // not really a MemberInfo
6981 EventBuilder MyBuilder;
6984 // We "catch" and wrap these methods
6986 MethodInfo raise, remove, add;
6988 EventAttributes attributes;
6989 Type declaring_type, reflected_type, event_type;
6994 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6996 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6998 // And now store the values in our own fields.
7000 declaring_type = type_builder;
7002 reflected_type = type_builder;
7004 attributes = event_attr;
7007 this.event_type = event_type;
7011 // Methods that you have to override. Note that you only need
7012 // to "implement" the variants that take the argument (those are
7013 // the "abstract" methods, the others (GetAddMethod()) are
7016 public override MethodInfo GetAddMethod (bool nonPublic)
7021 public override MethodInfo GetRemoveMethod (bool nonPublic)
7026 public override MethodInfo GetRaiseMethod (bool nonPublic)
7032 // These methods make "MyEventInfo" look like a Builder
7034 public void SetRaiseMethod (MethodBuilder raiseMethod)
7036 raise = raiseMethod;
7037 MyBuilder.SetRaiseMethod (raiseMethod);
7040 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7042 remove = removeMethod;
7043 MyBuilder.SetRemoveOnMethod (removeMethod);
7046 public void SetAddOnMethod (MethodBuilder addMethod)
7049 MyBuilder.SetAddOnMethod (addMethod);
7052 public void SetCustomAttribute (CustomAttributeBuilder cb)
7054 MyBuilder.SetCustomAttribute (cb);
7057 public override object [] GetCustomAttributes (bool inherit)
7059 // FIXME : There's nothing which can be seemingly done here because
7060 // we have no way of getting at the custom attribute objects of the
7065 public override object [] GetCustomAttributes (Type t, bool inherit)
7067 // FIXME : Same here !
7071 public override bool IsDefined (Type t, bool b)
7076 public override EventAttributes Attributes {
7082 public override string Name {
7088 public override Type DeclaringType {
7090 return declaring_type;
7094 public override Type ReflectedType {
7096 return reflected_type;
7100 public Type EventType {
7106 public void SetUsed ()
7108 if (my_event != null) {
7109 // my_event.SetAssigned ();
7110 my_event.SetMemberIsUsed ();
7116 /// For case when event is declared like property (with add and remove accessors).
7118 public class EventProperty: Event {
7119 abstract class AEventPropertyAccessor : AEventAccessor
7121 readonly ArrayList anonymous_methods;
7123 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7124 base (method, accessor, prefix)
7126 this.anonymous_methods = accessor.AnonymousMethods;
7129 public override MethodBuilder Define (DeclSpace ds)
7131 CheckAbstractAndExtern (block != null);
7132 return base.Define (ds);
7135 public override string GetSignatureForError ()
7137 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7140 public override bool ResolveMembers ()
7142 if (anonymous_methods == null)
7145 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7146 if (!ame.CreateAnonymousHelpers ())
7155 sealed class AddDelegateMethod: AEventPropertyAccessor
7157 public AddDelegateMethod (Event method, Accessor accessor):
7158 base (method, accessor, "add_")
7162 protected override MethodInfo DelegateMethodInfo {
7164 return TypeManager.delegate_combine_delegate_delegate;
7169 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7171 public RemoveDelegateMethod (Event method, Accessor accessor):
7172 base (method, accessor, "remove_")
7176 protected override MethodInfo DelegateMethodInfo {
7178 return TypeManager.delegate_remove_delegate_delegate;
7184 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7186 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7187 bool is_iface, MemberName name,
7188 Attributes attrs, Accessor add, Accessor remove)
7189 : base (parent, type, mod_flags, is_iface, name, attrs)
7191 Add = new AddDelegateMethod (this, add);
7192 Remove = new RemoveDelegateMethod (this, remove);
7195 public override bool Define()
7197 if (!base.Define ())
7204 public override string[] ValidAttributeTargets {
7206 return attribute_targets;
7212 /// Event is declared like field.
7214 public class EventField : Event {
7215 abstract class EventFieldAccessor : AEventAccessor
7217 protected EventFieldAccessor (Event method, string prefix)
7218 : base (method, prefix)
7222 protected override void EmitMethod(DeclSpace parent)
7224 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7227 MethodBuilder mb = method_data.MethodBuilder;
7228 ILGenerator ig = mb.GetILGenerator ();
7230 // TODO: because we cannot use generics yet
7231 FieldInfo field_info = ((EventField)method).FieldBuilder;
7233 if (parent is Class) {
7234 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7237 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7238 ig.Emit (OpCodes.Ldsfld, field_info);
7239 ig.Emit (OpCodes.Ldarg_0);
7240 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7241 ig.Emit (OpCodes.Castclass, method.MemberType);
7242 ig.Emit (OpCodes.Stsfld, field_info);
7244 ig.Emit (OpCodes.Ldarg_0);
7245 ig.Emit (OpCodes.Ldarg_0);
7246 ig.Emit (OpCodes.Ldfld, field_info);
7247 ig.Emit (OpCodes.Ldarg_1);
7248 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7249 ig.Emit (OpCodes.Castclass, method.MemberType);
7250 ig.Emit (OpCodes.Stfld, field_info);
7252 ig.Emit (OpCodes.Ret);
7256 sealed class AddDelegateMethod: EventFieldAccessor
7258 public AddDelegateMethod (Event method):
7259 base (method, "add_")
7263 protected override MethodInfo DelegateMethodInfo {
7265 return TypeManager.delegate_combine_delegate_delegate;
7270 sealed class RemoveDelegateMethod: EventFieldAccessor
7272 public RemoveDelegateMethod (Event method):
7273 base (method, "remove_")
7277 protected override MethodInfo DelegateMethodInfo {
7279 return TypeManager.delegate_remove_delegate_delegate;
7285 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7286 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7288 public FieldBuilder FieldBuilder;
7289 public Expression Initializer;
7291 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags,
7292 bool is_iface, MemberName name,
7294 : base (parent, type, mod_flags, is_iface, name, attrs)
7296 Add = new AddDelegateMethod (this);
7297 Remove = new RemoveDelegateMethod (this);
7300 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7302 if (a.Target == AttributeTargets.Field) {
7303 FieldBuilder.SetCustomAttribute (cb);
7307 if (a.Target == AttributeTargets.Method) {
7308 int errors = Report.Errors;
7309 Add.ApplyAttributeBuilder (a, cb);
7310 if (errors == Report.Errors)
7311 Remove.ApplyAttributeBuilder (a, cb);
7315 base.ApplyAttributeBuilder (a, cb);
7318 public override bool Define()
7320 if (!base.Define ())
7326 // FIXME: We are unable to detect whether generic event is used because
7327 // we are using FieldExpr instead of EventExpr for event access in that
7328 // case. When this issue will be fixed this hack can be removed.
7329 if (TypeManager.IsGenericType (MemberType))
7332 if (Add.IsInterfaceImplementation)
7335 FieldBuilder = Parent.TypeBuilder.DefineField (
7337 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7338 TypeManager.RegisterEventField (EventBuilder, this);
7340 if (Initializer != null) {
7341 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7342 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7343 GetSignatureForError ());
7347 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7348 new FieldInitializer (FieldBuilder, Initializer));
7354 public override string[] ValidAttributeTargets
7357 return IsInterface ? attribute_targets_interface : attribute_targets;
7362 public abstract class Event : PropertyBasedMember {
7363 public abstract class AEventAccessor : AbstractPropertyEventMethod
7365 protected readonly Event method;
7366 ImplicitParameter param_attr;
7368 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7370 protected AEventAccessor (Event method, string prefix)
7371 : base (method, prefix)
7373 this.method = method;
7374 this.ModFlags = method.ModFlags;
7377 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7378 : base (method, accessor, prefix)
7380 this.method = method;
7381 this.ModFlags = method.ModFlags;
7384 public override Iterator Iterator {
7385 get { return null; }
7388 public bool IsInterfaceImplementation {
7389 get { return method_data.implementing != null; }
7392 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7394 if (a.IsInternalMethodImplAttribute) {
7395 method.is_external_implementation = true;
7398 base.ApplyAttributeBuilder (a, cb);
7401 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7403 if (a.Target == AttributeTargets.Parameter) {
7404 if (param_attr == null)
7405 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7407 param_attr.ApplyAttributeBuilder (a, cb);
7411 base.ApplyAttributeBuilder (a, cb);
7414 public override AttributeTargets AttributeTargets {
7416 return AttributeTargets.Method;
7420 public override bool IsClsComplianceRequired ()
7422 return method.IsClsComplianceRequired ();
7425 public virtual MethodBuilder Define (DeclSpace parent)
7427 method_data = new MethodData (method, method.ModFlags,
7428 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7430 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7433 MethodBuilder mb = method_data.MethodBuilder;
7434 ParameterInfo.ApplyAttributes (mb);
7438 protected abstract MethodInfo DelegateMethodInfo { get; }
7440 public override Type ReturnType {
7442 return TypeManager.void_type;
7446 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7448 return new EmitContext (
7449 ds, method.Parent, Location, ig, ReturnType,
7450 method.ModFlags, false);
7453 public override ObsoleteAttribute GetObsoleteAttribute ()
7455 return method.GetObsoleteAttribute ();
7458 public override string[] ValidAttributeTargets {
7460 return attribute_targets;
7464 public override Parameters ParameterInfo {
7466 return method.parameters;
7472 const int AllowedModifiers =
7475 Modifiers.PROTECTED |
7476 Modifiers.INTERNAL |
7481 Modifiers.OVERRIDE |
7483 Modifiers.ABSTRACT |
7486 const int AllowedInterfaceModifiers =
7489 public AEventAccessor Add, Remove;
7490 public MyEventBuilder EventBuilder;
7491 public MethodBuilder AddBuilder, RemoveBuilder;
7493 Parameters parameters;
7495 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags,
7496 bool is_iface, MemberName name, Attributes attrs)
7497 : base (parent, null, type, mod_flags,
7498 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7503 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7505 if ((a.HasSecurityAttribute)) {
7506 a.Error_InvalidSecurityParent ();
7510 EventBuilder.SetCustomAttribute (cb);
7513 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7515 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7518 public override AttributeTargets AttributeTargets {
7520 return AttributeTargets.Event;
7524 public override bool Define ()
7526 if (!DoDefineBase ())
7532 if (!TypeManager.IsDelegateType (MemberType)) {
7533 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7537 parameters = Parameters.CreateFullyResolved (
7538 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7543 if (TypeManager.delegate_combine_delegate_delegate == null) {
7544 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7545 TypeManager.delegate_type, "Combine", Location,
7546 TypeManager.delegate_type, TypeManager.delegate_type);
7548 if (TypeManager.delegate_remove_delegate_delegate == null) {
7549 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7550 TypeManager.delegate_type, "Remove", Location,
7551 TypeManager.delegate_type, TypeManager.delegate_type);
7555 // Now define the accessors
7558 AddBuilder = Add.Define (Parent);
7559 if (AddBuilder == null)
7562 RemoveBuilder = Remove.Define (Parent);
7563 if (RemoveBuilder == null)
7566 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7567 EventBuilder.SetAddOnMethod (AddBuilder);
7568 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7570 Parent.MemberCache.AddMember (EventBuilder, this);
7571 Parent.MemberCache.AddMember (AddBuilder, Add);
7572 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7577 public override void Emit ()
7579 if (OptAttributes != null) {
7580 OptAttributes.Emit ();
7584 Remove.Emit (Parent);
7589 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7591 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7592 Parent.TypeBuilder, Name);
7597 ParameterData pd = TypeManager.GetParameterData (mi);
7598 base_ret_type = pd.ParameterType (0);
7603 // Represents header string for documentation comment.
7605 public override string DocCommentHeader {
7606 get { return "E:"; }
7611 public class Indexer : PropertyBase
7613 class GetIndexerMethod : GetMethod
7615 public GetIndexerMethod (PropertyBase method):
7620 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7621 base (method, accessor)
7625 public override bool EnableOverloadChecks (MemberCore overload)
7627 if (base.EnableOverloadChecks (overload)) {
7628 overload.caching_flags |= Flags.MethodOverloadsExist;
7635 public override Parameters ParameterInfo {
7637 return ((Indexer)method).parameters;
7642 class SetIndexerMethod: SetMethod
7644 public SetIndexerMethod (PropertyBase method):
7649 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7650 base (method, accessor)
7654 protected override void DefineParameters ()
7656 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7657 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7660 public override bool EnableOverloadChecks (MemberCore overload)
7662 if (base.EnableOverloadChecks (overload)) {
7663 overload.caching_flags |= Flags.MethodOverloadsExist;
7671 const int AllowedModifiers =
7674 Modifiers.PROTECTED |
7675 Modifiers.INTERNAL |
7679 Modifiers.OVERRIDE |
7684 const int AllowedInterfaceModifiers =
7687 public readonly Parameters parameters;
7689 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7690 bool is_iface, Parameters parameters, Attributes attrs,
7691 Accessor get_block, Accessor set_block, bool define_set_first)
7692 : base (parent, type, mod,
7693 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7694 is_iface, name, attrs, define_set_first)
7696 if (type == TypeManager.system_void_expr)
7697 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7699 this.parameters = parameters;
7701 if (get_block == null)
7702 Get = new GetIndexerMethod (this);
7704 Get = new GetIndexerMethod (this, get_block);
7706 if (set_block == null)
7707 Set = new SetIndexerMethod (this);
7709 Set = new SetIndexerMethod (this, set_block);
7712 public override bool Define ()
7714 if (!DoDefineBase ())
7717 if (!base.Define ())
7720 if (!DefineParameters (parameters))
7723 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7724 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7725 if (indexer_attr != null) {
7726 // Remove the attribute from the list because it is not emitted
7727 OptAttributes.Attrs.Remove (indexer_attr);
7729 string name = indexer_attr.GetIndexerAttributeValue ();
7735 if (IsExplicitImpl) {
7736 Report.Error (415, indexer_attr.Location,
7737 "The `IndexerName' attribute is valid only on an " +
7738 "indexer that is not an explicit interface member declaration");
7742 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7743 Report.Error (609, indexer_attr.Location,
7744 "Cannot set the `IndexerName' attribute on an indexer marked override");
7750 if (InterfaceType != null) {
7751 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7752 if (base_IndexerName != Name)
7753 ShortName = base_IndexerName;
7756 if (!Parent.PartialContainer.AddMember (this) ||
7757 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7760 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7761 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7765 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7767 if (!DefineAccessors ())
7774 // Setup iterator if we are one
7775 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7776 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7777 if (iterator == null)
7783 // Now name the parameters
7785 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7786 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7789 PropertyBuilder.SetGetMethod (GetBuilder);
7790 Parent.MemberCache.AddMember (GetBuilder, Get);
7794 PropertyBuilder.SetSetMethod (SetBuilder);
7795 Parent.MemberCache.AddMember (SetBuilder, Set);
7798 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7799 Parent.MemberCache.AddMember (PropertyBuilder, this);
7803 public override bool EnableOverloadChecks (MemberCore overload)
7805 if (overload is Indexer) {
7806 caching_flags |= Flags.MethodOverloadsExist;
7813 public override string GetDocCommentName (DeclSpace ds)
7815 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7818 public override string GetSignatureForError ()
7820 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7821 if (MemberName.Left != null) {
7823 sb.Append (MemberName.Left.GetSignatureForError ());
7826 sb.Append (".this");
7827 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7828 return sb.ToString ();
7831 protected override PropertyInfo ResolveBaseProperty ()
7833 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7834 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7837 protected override bool VerifyClsCompliance ()
7839 if (!base.VerifyClsCompliance ())
7842 parameters.VerifyClsCompliance ();
7847 public class Operator : MethodOrOperator, IAnonymousHost {
7849 const int AllowedModifiers =
7855 public enum OpType : byte {
7865 // Unary and Binary operators
7888 // Implicit and Explicit
7892 // Just because of enum
7896 public readonly OpType OperatorType;
7898 static readonly string [] [] names;
7902 names = new string[(int)OpType.TOP][];
7903 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7904 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7905 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7906 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7907 names [(int) OpType.True] = new string [] { "true", "op_True" };
7908 names [(int) OpType.False] = new string [] { "false", "op_False" };
7909 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7910 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7911 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7912 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7913 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7914 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7915 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7916 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7917 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7918 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7919 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7920 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7921 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7922 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7923 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7924 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7925 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7926 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7927 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7928 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7931 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7932 int mod_flags, Parameters parameters,
7933 ToplevelBlock block, Attributes attrs, Location loc)
7934 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7935 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7937 OperatorType = type;
7941 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7943 if (a.Type == TypeManager.conditional_attribute_type) {
7944 Error_ConditionalAttributeIsNotValid ();
7948 base.ApplyAttributeBuilder (a, cb);
7951 public override bool Define ()
7953 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7954 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7955 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7959 if (!base.Define ())
7962 // imlicit and explicit operator of same types are not allowed
7963 if (OperatorType == OpType.Explicit)
7964 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7965 else if (OperatorType == OpType.Implicit)
7966 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7968 if (MemberType == TypeManager.void_type) {
7969 Report.Error (590, Location, "User-defined operators cannot return void");
7973 Type declaring_type = MethodData.DeclaringType;
7974 Type return_type = MemberType;
7975 Type first_arg_type = ParameterTypes [0];
7977 Type first_arg_type_unwrap = first_arg_type;
7978 if (TypeManager.IsNullableType (first_arg_type))
7979 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7981 Type return_type_unwrap = return_type;
7982 if (TypeManager.IsNullableType (return_type))
7983 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7986 // Rules for conversion operators
7988 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7989 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7990 Report.Error (555, Location,
7991 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7996 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7997 conv_type = first_arg_type;
7998 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7999 conv_type = return_type;
8001 Report.Error (556, Location,
8002 "User-defined conversion must convert to or from the enclosing type");
8007 // Because IsInterface and IsClass are not supported
8009 if (!TypeManager.IsGenericParameter (conv_type)) {
8010 if (conv_type.IsInterface) {
8011 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8012 GetSignatureForError ());
8016 if (conv_type.IsClass) {
8017 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
8018 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
8019 GetSignatureForError ());
8023 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
8024 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
8025 GetSignatureForError ());
8030 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8031 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8032 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");
8035 } else if (Parameters.Count == 1) {
8036 // Checks for Unary operators
8038 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8039 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8040 Report.Error (448, Location,
8041 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8044 if (first_arg_type != declaring_type) {
8046 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8051 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
8052 Report.Error (562, Location,
8053 "The parameter type of a unary operator must be the containing type");
8057 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8058 if (return_type != TypeManager.bool_type){
8061 "The return type of operator True or False " +
8068 // Checks for Binary operators
8070 if (first_arg_type != declaring_type &&
8071 ParameterTypes [1] != declaring_type){
8074 "One of the parameters of a binary operator must " +
8075 "be the containing type");
8083 protected override bool DoDefine ()
8085 if (!base.DoDefine ())
8088 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8092 public override void Emit ()
8096 Parameters.ApplyAttributes (MethodBuilder);
8099 // abstract or extern methods have no bodies
8101 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8105 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8106 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8108 ec = CreateEmitContext (Parent, null);
8110 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8111 ec.EmitTopBlock (this, Block);
8114 source.CloseMethod ();
8119 // Operator cannot be override
8120 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8125 public static string GetName (OpType ot)
8127 return names [(int) ot] [0];
8130 public static string GetName (string metadata_name)
8132 for (int i = 0; i < names.Length; ++i) {
8133 if (names [i] [1] == metadata_name)
8134 return names [i] [0];
8139 public static string GetMetadataName (OpType ot)
8141 return names [(int) ot] [1];
8144 public static string GetMetadataName (string name)
8146 for (int i = 0; i < names.Length; ++i) {
8147 if (names [i] [0] == name)
8148 return names [i] [1];
8153 public OpType GetMatchingOperator ()
8155 switch (OperatorType) {
8156 case OpType.Equality:
8157 return OpType.Inequality;
8158 case OpType.Inequality:
8159 return OpType.Equality;
8161 return OpType.False;
8164 case OpType.GreaterThan:
8165 return OpType.LessThan;
8166 case OpType.LessThan:
8167 return OpType.GreaterThan;
8168 case OpType.GreaterThanOrEqual:
8169 return OpType.LessThanOrEqual;
8170 case OpType.LessThanOrEqual:
8171 return OpType.GreaterThanOrEqual;
8177 public override string GetSignatureForError ()
8179 StringBuilder sb = new StringBuilder ();
8180 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8181 sb.AppendFormat ("{0}.{1} operator {2}",
8182 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
8185 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8188 sb.Append (Parameters.GetSignatureForError ());
8189 return sb.ToString ();
8194 // This is used to compare method signatures
8196 struct MethodSignature {
8198 public Type RetType;
8199 public Type [] Parameters;
8202 /// This delegate is used to extract methods which have the
8203 /// same signature as the argument
8205 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8207 public MethodSignature (string name, Type ret_type, Type [] parameters)
8212 if (parameters == null)
8213 Parameters = Type.EmptyTypes;
8215 Parameters = parameters;
8218 public override string ToString ()
8221 if (Parameters.Length != 0){
8222 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8223 for (int i = 0; i < Parameters.Length; i++){
8224 sb.Append (Parameters [i]);
8225 if (i+1 < Parameters.Length)
8228 pars = sb.ToString ();
8231 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8234 public override int GetHashCode ()
8236 return Name.GetHashCode ();
8239 public override bool Equals (Object o)
8241 MethodSignature other = (MethodSignature) o;
8243 if (other.Name != Name)
8246 if (other.RetType != RetType)
8249 if (Parameters == null){
8250 if (other.Parameters == null)
8255 if (other.Parameters == null)
8258 int c = Parameters.Length;
8259 if (other.Parameters.Length != c)
8262 for (int i = 0; i < c; i++)
8263 if (other.Parameters [i] != Parameters [i])
8269 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8271 MethodSignature sig = (MethodSignature) filter_criteria;
8273 if (m.Name != sig.Name)
8277 MethodInfo mi = m as MethodInfo;
8278 PropertyInfo pi = m as PropertyInfo;
8281 ReturnType = mi.ReturnType;
8282 else if (pi != null)
8283 ReturnType = pi.PropertyType;
8288 // we use sig.RetType == null to mean `do not check the
8289 // method return value.
8291 if (sig.RetType != null) {
8292 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8298 args = TypeManager.GetParameterData (mi).Types;
8300 args = TypeManager.GetArgumentTypes (pi);
8301 Type [] sigp = sig.Parameters;
8303 if (args.Length != sigp.Length)
8306 for (int i = args.Length - 1; i >= 0; i--)
8307 if (!TypeManager.IsEqual (args [i], sigp [i]))