2009-04-15 Atsushi Enomoto <atsushi@ximian.com>
[mcs.git] / mcs / decl.cs
blobd49d0641e855b6cb179a3ac2122e9a3166e701eb
1 //
2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
6 //
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004-2008 Novell, Inc
14 using System;
15 using System.Text;
16 using System.Collections;
17 using System.Globalization;
18 using System.Reflection.Emit;
19 using System.Reflection;
21 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
22 using XmlElement = System.Object;
23 #else
24 using System.Xml;
25 #endif
27 namespace Mono.CSharp {
30 // Better name would be DottenName
32 public class MemberName {
33 public readonly string Name;
34 public readonly TypeArguments TypeArguments;
36 public readonly MemberName Left;
37 public readonly Location Location;
39 public static readonly MemberName Null = new MemberName ("");
41 bool is_double_colon;
43 private MemberName (MemberName left, string name, bool is_double_colon,
44 Location loc)
46 this.Name = name;
47 this.Location = loc;
48 this.is_double_colon = is_double_colon;
49 this.Left = left;
52 private MemberName (MemberName left, string name, bool is_double_colon,
53 TypeArguments args, Location loc)
54 : this (left, name, is_double_colon, loc)
56 if (args != null && args.Count > 0)
57 this.TypeArguments = args;
60 public MemberName (string name)
61 : this (name, Location.Null)
62 { }
64 public MemberName (string name, Location loc)
65 : this (null, name, false, loc)
66 { }
68 public MemberName (string name, TypeArguments args, Location loc)
69 : this (null, name, false, args, loc)
70 { }
72 public MemberName (MemberName left, string name)
73 : this (left, name, left != null ? left.Location : Location.Null)
74 { }
76 public MemberName (MemberName left, string name, Location loc)
77 : this (left, name, false, loc)
78 { }
80 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
81 : this (left, name, false, args, loc)
82 { }
84 public MemberName (string alias, string name, TypeArguments args, Location loc)
85 : this (new MemberName (alias, loc), name, true, args, loc)
86 { }
88 public MemberName (MemberName left, MemberName right)
89 : this (left, right, right.Location)
90 { }
92 public MemberName (MemberName left, MemberName right, Location loc)
93 : this (null, right.Name, false, right.TypeArguments, loc)
95 if (right.is_double_colon)
96 throw new InternalErrorException ("Cannot append double_colon member name");
97 this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
100 // TODO: Remove
101 public string GetName ()
103 return GetName (false);
106 public bool IsGeneric {
107 get {
108 if (TypeArguments != null)
109 return true;
110 else if (Left != null)
111 return Left.IsGeneric;
112 else
113 return false;
117 public string GetName (bool is_generic)
119 string name = is_generic ? Basename : Name;
120 if (Left != null)
121 return Left.GetName (is_generic) + (is_double_colon ? "::" : ".") + name;
123 return name;
126 public ATypeNameExpression GetTypeExpression ()
128 if (Left == null) {
129 if (TypeArguments != null)
130 return new SimpleName (Basename, TypeArguments, Location);
132 return new SimpleName (Name, Location);
135 if (is_double_colon) {
136 if (Left.Left != null)
137 throw new InternalErrorException ("The left side of a :: should be an identifier");
138 return new QualifiedAliasMember (Left.Name, Name, TypeArguments, Location);
141 Expression lexpr = Left.GetTypeExpression ();
142 return new MemberAccess (lexpr, Name, TypeArguments, Location);
145 public MemberName Clone ()
147 MemberName left_clone = Left == null ? null : Left.Clone ();
148 return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
151 public string Basename {
152 get {
153 if (TypeArguments != null)
154 return MakeName (Name, TypeArguments);
155 return Name;
159 public string GetSignatureForError ()
161 string append = TypeArguments == null ? "" : "<" + TypeArguments.GetSignatureForError () + ">";
162 if (Left == null)
163 return Name + append;
164 string connect = is_double_colon ? "::" : ".";
165 return Left.GetSignatureForError () + connect + Name + append;
168 public override bool Equals (object other)
170 return Equals (other as MemberName);
173 public bool Equals (MemberName other)
175 if (this == other)
176 return true;
177 if (other == null || Name != other.Name)
178 return false;
179 if (is_double_colon != other.is_double_colon)
180 return false;
182 if ((TypeArguments != null) &&
183 (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
184 return false;
186 if ((TypeArguments == null) && (other.TypeArguments != null))
187 return false;
189 if (Left == null)
190 return other.Left == null;
192 return Left.Equals (other.Left);
195 public override int GetHashCode ()
197 int hash = Name.GetHashCode ();
198 for (MemberName n = Left; n != null; n = n.Left)
199 hash ^= n.Name.GetHashCode ();
200 if (is_double_colon)
201 hash ^= 0xbadc01d;
203 if (TypeArguments != null)
204 hash ^= TypeArguments.Count << 5;
206 return hash & 0x7FFFFFFF;
209 public int CountTypeArguments {
210 get {
211 if (TypeArguments != null)
212 return TypeArguments.Count;
213 else if (Left != null)
214 return Left.CountTypeArguments;
215 else
216 return 0;
220 public static string MakeName (string name, TypeArguments args)
222 if (args == null)
223 return name;
225 return name + "`" + args.Count;
228 public static string MakeName (string name, int count)
230 return name + "`" + count;
234 /// <summary>
235 /// Base representation for members. This is used to keep track
236 /// of Name, Location and Modifier flags, and handling Attributes.
237 /// </summary>
238 public abstract class MemberCore : Attributable, IResolveContext {
239 /// <summary>
240 /// Public name
241 /// </summary>
243 protected string cached_name;
244 // TODO: Remove in favor of MemberName
245 public string Name {
246 get {
247 if (cached_name == null)
248 cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
249 return cached_name;
253 // Is not readonly because of IndexerName attribute
254 private MemberName member_name;
255 public MemberName MemberName {
256 get { return member_name; }
259 /// <summary>
260 /// Modifier flags that the user specified in the source code
261 /// </summary>
262 private int mod_flags;
263 public int ModFlags {
264 set {
265 mod_flags = value;
266 if ((value & Modifiers.COMPILER_GENERATED) != 0)
267 caching_flags = Flags.IsUsed | Flags.IsAssigned;
269 get {
270 return mod_flags;
274 public /*readonly*/ DeclSpace Parent;
276 /// <summary>
277 /// Location where this declaration happens
278 /// </summary>
279 public Location Location {
280 get { return member_name.Location; }
283 /// <summary>
284 /// XML documentation comment
285 /// </summary>
286 protected string comment;
288 /// <summary>
289 /// Represents header string for documentation comment
290 /// for each member types.
291 /// </summary>
292 public abstract string DocCommentHeader { get; }
294 [Flags]
295 public enum Flags {
296 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
297 Obsolete = 1 << 1, // Type has obsolete attribute
298 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
299 ClsCompliant = 1 << 3, // Type is CLS Compliant
300 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
301 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
302 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
303 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
304 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
305 Excluded = 1 << 9, // Method is conditional
306 MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
307 IsUsed = 1 << 11,
308 IsAssigned = 1 << 12, // Field is assigned
309 HasExplicitLayout = 1 << 13,
310 PartialDefinitionExists = 1 << 14, // Set when corresponding partial method definition exists
311 HasStructLayout = 1 << 15 // Has StructLayoutAttribute
314 /// <summary>
315 /// MemberCore flags at first detected then cached
316 /// </summary>
317 internal Flags caching_flags;
319 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
320 : base (attrs)
322 this.Parent = parent;
323 member_name = name;
324 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
327 protected virtual void SetMemberName (MemberName new_name)
329 member_name = new_name;
330 cached_name = null;
333 protected bool CheckAbstractAndExtern (bool has_block)
335 if (Parent.PartialContainer.Kind == Kind.Interface)
336 return true;
338 if (has_block) {
339 if ((ModFlags & Modifiers.EXTERN) != 0) {
340 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
341 GetSignatureForError ());
342 return false;
345 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
346 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
347 GetSignatureForError ());
348 return false;
350 } else {
351 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0) {
352 if (RootContext.Version >= LanguageVersion.LINQ) {
353 Property.PropertyMethod pm = this as Property.PropertyMethod;
354 if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
355 pm = null;
357 if (pm != null && (pm.Property.Get.IsDummy || pm.Property.Set.IsDummy)) {
358 Report.Error (840, Location,
359 "`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
360 GetSignatureForError ());
361 return false;
365 Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
366 GetSignatureForError ());
367 return false;
371 return true;
374 public void CheckProtectedModifier ()
376 if ((ModFlags & Modifiers.PROTECTED) == 0)
377 return;
379 if (Parent.PartialContainer.Kind == Kind.Struct) {
380 Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
381 GetSignatureForError ());
382 return;
385 if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
386 Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
387 GetSignatureForError ());
388 return;
391 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
392 !(this is Destructor)) {
393 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
394 GetSignatureForError ());
395 return;
399 public abstract bool Define ();
401 public virtual string DocComment {
402 get {
403 return comment;
405 set {
406 comment = value;
411 // Returns full member name for error message
413 public virtual string GetSignatureForError ()
415 if (Parent == null || Parent.Parent == null)
416 return member_name.GetSignatureForError ();
418 return Parent.GetSignatureForError () + "." + member_name.GetSignatureForError ();
421 /// <summary>
422 /// Base Emit method. This is also entry point for CLS-Compliant verification.
423 /// </summary>
424 public virtual void Emit ()
426 if (!RootContext.VerifyClsCompliance)
427 return;
429 if (Report.WarningLevel > 0)
430 VerifyClsCompliance ();
433 public bool IsCompilerGenerated {
434 get {
435 if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
436 return true;
438 return Parent == null ? false : Parent.IsCompilerGenerated;
442 public virtual bool IsUsed {
443 get { return (caching_flags & Flags.IsUsed) != 0; }
446 public void SetMemberIsUsed ()
448 caching_flags |= Flags.IsUsed;
451 /// <summary>
452 /// Returns instance of ObsoleteAttribute for this MemberCore
453 /// </summary>
454 public virtual ObsoleteAttribute GetObsoleteAttribute ()
456 if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
457 return null;
459 caching_flags &= ~Flags.Obsolete_Undetected;
461 if (OptAttributes == null)
462 return null;
464 Attribute obsolete_attr = OptAttributes.Search (PredefinedAttributes.Get.Obsolete);
465 if (obsolete_attr == null)
466 return null;
468 caching_flags |= Flags.Obsolete;
470 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
471 if (obsolete == null)
472 return null;
474 return obsolete;
477 /// <summary>
478 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
479 /// </summary>
480 public virtual void CheckObsoleteness (Location loc)
482 ObsoleteAttribute oa = GetObsoleteAttribute ();
483 if (oa != null)
484 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
487 // Access level of a type.
488 const int X = 1;
489 enum AccessLevel
490 { // Each column represents `is this scope larger or equal to Blah scope'
491 // Public Assembly Protected
492 Protected = (0 << 0) | (0 << 1) | (X << 2),
493 Public = (X << 0) | (X << 1) | (X << 2),
494 Private = (0 << 0) | (0 << 1) | (0 << 2),
495 Internal = (0 << 0) | (X << 1) | (0 << 2),
496 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
499 static AccessLevel GetAccessLevelFromModifiers (int flags)
501 if ((flags & Modifiers.INTERNAL) != 0) {
503 if ((flags & Modifiers.PROTECTED) != 0)
504 return AccessLevel.ProtectedOrInternal;
505 else
506 return AccessLevel.Internal;
508 } else if ((flags & Modifiers.PROTECTED) != 0)
509 return AccessLevel.Protected;
510 else if ((flags & Modifiers.PRIVATE) != 0)
511 return AccessLevel.Private;
512 else
513 return AccessLevel.Public;
517 // Returns the access level for type `t'
519 static AccessLevel GetAccessLevelFromType (Type t)
521 if (t.IsPublic)
522 return AccessLevel.Public;
523 if (t.IsNestedPrivate)
524 return AccessLevel.Private;
525 if (t.IsNotPublic)
526 return AccessLevel.Internal;
528 if (t.IsNestedPublic)
529 return AccessLevel.Public;
530 if (t.IsNestedAssembly)
531 return AccessLevel.Internal;
532 if (t.IsNestedFamily)
533 return AccessLevel.Protected;
534 if (t.IsNestedFamORAssem)
535 return AccessLevel.ProtectedOrInternal;
536 if (t.IsNestedFamANDAssem)
537 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
539 // nested private is taken care of
541 throw new Exception ("I give up, what are you?");
545 // Checks whether the type P is as accessible as this member
547 public bool IsAccessibleAs (Type p)
550 // if M is private, its accessibility is the same as this declspace.
551 // we already know that P is accessible to T before this method, so we
552 // may return true.
554 if ((mod_flags & Modifiers.PRIVATE) != 0)
555 return true;
557 while (TypeManager.HasElementType (p))
558 p = TypeManager.GetElementType (p);
560 if (TypeManager.IsGenericParameter (p))
561 return true;
563 if (TypeManager.IsGenericType (p)) {
564 foreach (Type t in TypeManager.GetTypeArguments (p)) {
565 if (!IsAccessibleAs (t))
566 return false;
570 for (Type p_parent = null; p != null; p = p_parent) {
571 p_parent = p.DeclaringType;
572 AccessLevel pAccess = GetAccessLevelFromType (p);
573 if (pAccess == AccessLevel.Public)
574 continue;
576 bool same_access_restrictions = false;
577 for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
578 AccessLevel al = GetAccessLevelFromModifiers (mc.ModFlags);
579 switch (pAccess) {
580 case AccessLevel.Internal:
581 if (al == AccessLevel.Private || al == AccessLevel.Internal)
582 same_access_restrictions = TypeManager.IsThisOrFriendAssembly (p.Assembly);
584 break;
586 case AccessLevel.Protected:
587 if (al == AccessLevel.Protected) {
588 same_access_restrictions = mc.Parent.IsBaseType (p_parent);
589 break;
592 if (al == AccessLevel.Private) {
594 // When type is private and any of its parents derives from
595 // protected type then the type is accessible
597 while (mc.Parent != null) {
598 if (mc.Parent.IsBaseType (p_parent))
599 same_access_restrictions = true;
600 mc = mc.Parent;
604 break;
606 case AccessLevel.ProtectedOrInternal:
607 if (al == AccessLevel.Protected)
608 same_access_restrictions = mc.Parent.IsBaseType (p_parent);
609 else if (al == AccessLevel.Internal)
610 same_access_restrictions = TypeManager.IsThisOrFriendAssembly (p.Assembly);
611 else if (al == AccessLevel.ProtectedOrInternal)
612 same_access_restrictions = mc.Parent.IsBaseType (p_parent) &&
613 TypeManager.IsThisOrFriendAssembly (p.Assembly);
615 break;
617 case AccessLevel.Private:
619 // Both are private and share same parent
621 if (al == AccessLevel.Private)
622 same_access_restrictions = TypeManager.IsEqual (mc.Parent.TypeBuilder, p_parent);
624 break;
626 default:
627 throw new InternalErrorException (al.ToString ());
631 if (!same_access_restrictions)
632 return false;
635 return true;
638 /// <summary>
639 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
640 /// </summary>
641 public override bool IsClsComplianceRequired ()
643 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
644 return (caching_flags & Flags.ClsCompliant) != 0;
646 if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
647 caching_flags &= ~Flags.ClsCompliance_Undetected;
648 caching_flags |= Flags.ClsCompliant;
649 return true;
652 caching_flags &= ~Flags.ClsCompliance_Undetected;
653 return false;
656 /// <summary>
657 /// Returns true when MemberCore is exposed from assembly.
658 /// </summary>
659 public bool IsExposedFromAssembly ()
661 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
662 return false;
664 DeclSpace parentContainer = Parent;
665 while (parentContainer != null && parentContainer.ModFlags != 0) {
666 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
667 return false;
668 parentContainer = parentContainer.Parent;
670 return true;
673 /// <summary>
674 /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
675 /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
676 /// </summary>
677 public virtual bool GetClsCompliantAttributeValue ()
679 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
680 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
682 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
684 if (OptAttributes != null) {
685 Attribute cls_attribute = OptAttributes.Search (
686 PredefinedAttributes.Get.CLSCompliant);
687 if (cls_attribute != null) {
688 caching_flags |= Flags.HasClsCompliantAttribute;
689 bool value = cls_attribute.GetClsCompliantAttributeValue ();
690 if (value)
691 caching_flags |= Flags.ClsCompliantAttributeTrue;
692 return value;
696 // It's null for TypeParameter
697 if (Parent == null)
698 return false;
700 if (Parent.GetClsCompliantAttributeValue ()) {
701 caching_flags |= Flags.ClsCompliantAttributeTrue;
702 return true;
704 return false;
707 /// <summary>
708 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
709 /// </summary>
710 protected bool HasClsCompliantAttribute {
711 get {
712 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) != 0)
713 GetClsCompliantAttributeValue ();
715 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
719 /// <summary>
720 /// Returns true when a member supports multiple overloads (methods, indexers, etc)
721 /// </summary>
722 public virtual bool EnableOverloadChecks (MemberCore overload)
724 return false;
727 /// <summary>
728 /// The main virtual method for CLS-Compliant verifications.
729 /// The method returns true if member is CLS-Compliant and false if member is not
730 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
731 /// and add their extra verifications.
732 /// </summary>
733 protected virtual bool VerifyClsCompliance ()
735 if (!IsClsComplianceRequired ()) {
736 if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
737 if (!IsExposedFromAssembly ()) {
738 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
739 Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
742 if (!CodeGen.Assembly.IsClsCompliant) {
743 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
744 Report.Warning (3021, 2, a.Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
747 return false;
750 if (HasClsCompliantAttribute) {
751 if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
752 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
753 Report.Warning (3014, 1, a.Location,
754 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
755 GetSignatureForError ());
756 return false;
759 if (!Parent.IsClsComplianceRequired ()) {
760 Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
761 Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
762 GetSignatureForError (), Parent.GetSignatureForError ());
763 return false;
767 if (member_name.Name [0] == '_') {
768 Report.Warning (3008, 1, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
770 return true;
774 // Raised (and passed an XmlElement that contains the comment)
775 // when GenerateDocComment is writing documentation expectedly.
777 internal virtual void OnGenerateDocComment (XmlElement intermediateNode)
782 // Returns a string that represents the signature for this
783 // member which should be used in XML documentation.
785 public virtual string GetDocCommentName (DeclSpace ds)
787 if (ds == null || this is DeclSpace)
788 return DocCommentHeader + Name;
789 else
790 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
794 // Generates xml doc comments (if any), and if required,
795 // handle warning report.
797 internal virtual void GenerateDocComment (DeclSpace ds)
799 try {
800 DocUtil.GenerateDocComment (this, ds);
801 } catch (Exception e) {
802 throw new InternalErrorException (this, e);
806 public override IResolveContext ResolveContext {
807 get { return this; }
810 #region IResolveContext Members
812 public DeclSpace DeclContainer {
813 get { return Parent; }
816 public virtual DeclSpace GenericDeclContainer {
817 get { return DeclContainer; }
820 public bool IsInObsoleteScope {
821 get {
822 if (GetObsoleteAttribute () != null)
823 return true;
825 return Parent == null ? false : Parent.IsInObsoleteScope;
829 public bool IsInUnsafeScope {
830 get {
831 if ((ModFlags & Modifiers.UNSAFE) != 0)
832 return true;
834 return Parent == null ? false : Parent.IsInUnsafeScope;
838 #endregion
841 /// <summary>
842 /// Base class for structs, classes, enumerations and interfaces.
843 /// </summary>
844 /// <remarks>
845 /// They all create new declaration spaces. This
846 /// provides the common foundation for managing those name
847 /// spaces.
848 /// </remarks>
849 public abstract class DeclSpace : MemberCore {
850 /// <summary>
851 /// This points to the actual definition that is being
852 /// created with System.Reflection.Emit
853 /// </summary>
854 public TypeBuilder TypeBuilder;
856 /// <summary>
857 /// If we are a generic type, this is the type we are
858 /// currently defining. We need to lookup members on this
859 /// instead of the TypeBuilder.
860 /// </summary>
861 public Type CurrentType;
864 // This is the namespace in which this typecontainer
865 // was declared. We use this to resolve names.
867 public NamespaceEntry NamespaceEntry;
869 private Hashtable Cache = new Hashtable ();
871 public readonly string Basename;
873 protected Hashtable defined_names;
875 public TypeContainer PartialContainer;
877 protected readonly bool is_generic;
878 readonly int count_type_params;
879 protected TypeParameter[] type_params;
880 TypeParameter[] type_param_list;
883 // Whether we are Generic
885 public bool IsGeneric {
886 get {
887 if (is_generic)
888 return true;
889 else if (Parent != null)
890 return Parent.IsGeneric;
891 else
892 return false;
896 static string[] attribute_targets = new string [] { "type" };
898 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
899 Attributes attrs)
900 : base (parent, name, attrs)
902 NamespaceEntry = ns;
903 Basename = name.Basename;
904 defined_names = new Hashtable ();
905 PartialContainer = null;
906 if (name.TypeArguments != null) {
907 is_generic = true;
908 count_type_params = name.TypeArguments.Count;
910 if (parent != null)
911 count_type_params += parent.count_type_params;
914 public override DeclSpace GenericDeclContainer {
915 get { return this; }
918 /// <summary>
919 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
920 /// </summary>
921 protected virtual bool AddToContainer (MemberCore symbol, string name)
923 MemberCore mc = (MemberCore) defined_names [name];
925 if (mc == null) {
926 defined_names.Add (name, symbol);
927 return true;
930 if (((mc.ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
931 return true;
933 if (symbol.EnableOverloadChecks (mc))
934 return true;
936 Report.SymbolRelatedToPreviousError (mc);
937 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
938 Error_MissingPartialModifier (symbol);
939 return false;
942 if (this is ModuleContainer) {
943 Report.Error (101, symbol.Location,
944 "The namespace `{0}' already contains a definition for `{1}'",
945 ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
946 } else if (symbol is TypeParameter) {
947 Report.Error (692, symbol.Location,
948 "Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
949 } else {
950 Report.Error (102, symbol.Location,
951 "The type `{0}' already contains a definition for `{1}'",
952 GetSignatureForError (), symbol.MemberName.Name);
955 return false;
958 protected void RemoveFromContainer (string name)
960 defined_names.Remove (name);
963 /// <summary>
964 /// Returns the MemberCore associated with a given name in the declaration
965 /// space. It doesn't return method based symbols !!
966 /// </summary>
967 ///
968 public MemberCore GetDefinition (string name)
970 return (MemberCore)defined_names [name];
973 public bool IsStaticClass {
974 get { return (ModFlags & Modifiers.STATIC) != 0; }
978 // root_types contains all the types. All TopLevel types
979 // hence have a parent that points to `root_types', that is
980 // why there is a non-obvious test down here.
982 public bool IsTopLevel {
983 get { return (Parent != null && Parent.Parent == null); }
986 public virtual bool IsUnmanagedType ()
988 return false;
991 public virtual void CloseType ()
993 if ((caching_flags & Flags.CloseTypeCreated) == 0){
994 try {
995 TypeBuilder.CreateType ();
996 } catch {
998 // The try/catch is needed because
999 // nested enumerations fail to load when they
1000 // are defined.
1002 // Even if this is the right order (enumerations
1003 // declared after types).
1005 // Note that this still creates the type and
1006 // it is possible to save it
1008 caching_flags |= Flags.CloseTypeCreated;
1012 protected virtual TypeAttributes TypeAttr {
1013 get { return Module.DefaultCharSetType; }
1016 /// <remarks>
1017 /// Should be overriten by the appropriate declaration space
1018 /// </remarks>
1019 public abstract TypeBuilder DefineType ();
1021 protected void Error_MissingPartialModifier (MemberCore type)
1023 Report.Error (260, type.Location,
1024 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
1025 type.GetSignatureForError ());
1028 public override void Emit ()
1030 if (type_params != null) {
1031 int offset = count_type_params - type_params.Length;
1032 for (int i = offset; i < type_params.Length; i++)
1033 CurrentTypeParameters [i - offset].Emit ();
1036 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1037 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1039 base.Emit ();
1042 public override string GetSignatureForError ()
1044 return MemberName.GetSignatureForError ();
1047 public bool CheckAccessLevel (Type check_type)
1049 Type tb = TypeBuilder;
1051 if (this is GenericMethod) {
1052 tb = Parent.TypeBuilder;
1054 // FIXME: Generic container does not work with nested generic
1055 // anonymous method stories
1056 if (TypeBuilder == null)
1057 return true;
1060 check_type = TypeManager.DropGenericTypeArguments (check_type);
1061 if (check_type == tb)
1062 return true;
1064 // TODO: When called from LocalUsingAliasEntry tb is null
1065 // because we are in RootDeclSpace
1066 if (tb == null)
1067 tb = typeof (RootDeclSpace);
1070 // Broken Microsoft runtime, return public for arrays, no matter what
1071 // the accessibility is for their underlying class, and they return
1072 // NonPublic visibility for pointers
1074 if (TypeManager.HasElementType (check_type))
1075 return CheckAccessLevel (TypeManager.GetElementType (check_type));
1077 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
1079 switch (check_attr){
1080 case TypeAttributes.Public:
1081 return true;
1083 case TypeAttributes.NotPublic:
1084 return TypeManager.IsThisOrFriendAssembly (check_type.Assembly);
1086 case TypeAttributes.NestedPublic:
1087 return CheckAccessLevel (check_type.DeclaringType);
1089 case TypeAttributes.NestedPrivate:
1090 Type declaring = check_type.DeclaringType;
1091 return tb == declaring || TypeManager.IsNestedChildOf (tb, declaring);
1093 case TypeAttributes.NestedFamily:
1095 // Only accessible to methods in current type or any subtypes
1097 return FamilyAccessible (tb, check_type);
1099 case TypeAttributes.NestedFamANDAssem:
1100 return TypeManager.IsThisOrFriendAssembly (check_type.Assembly) &&
1101 FamilyAccessible (tb, check_type);
1103 case TypeAttributes.NestedFamORAssem:
1104 return FamilyAccessible (tb, check_type) ||
1105 TypeManager.IsThisOrFriendAssembly (check_type.Assembly);
1107 case TypeAttributes.NestedAssembly:
1108 return TypeManager.IsThisOrFriendAssembly (check_type.Assembly);
1111 throw new NotImplementedException (check_attr.ToString ());
1114 static bool FamilyAccessible (Type tb, Type check_type)
1116 Type declaring = check_type.DeclaringType;
1117 return TypeManager.IsNestedFamilyAccessible (tb, declaring);
1120 public bool IsBaseType (Type baseType)
1122 if (TypeManager.IsInterfaceType (baseType))
1123 throw new NotImplementedException ();
1125 Type type = TypeBuilder;
1126 while (type != null) {
1127 if (TypeManager.IsEqual (type, baseType))
1128 return true;
1130 type = type.BaseType;
1133 return false;
1136 private Type LookupNestedTypeInHierarchy (string name)
1138 Type t = null;
1139 // if the member cache has been created, lets use it.
1140 // the member cache is MUCH faster.
1141 if (MemberCache != null) {
1142 t = MemberCache.FindNestedType (name);
1143 if (t == null)
1144 return null;
1147 // FIXME: This hack is needed because member cache does not work
1148 // with nested base generic types, it does only type name copy and
1149 // not type construction
1151 #if !GMCS_SOURCE
1152 return t;
1153 #endif
1156 // no member cache. Do it the hard way -- reflection
1157 for (Type current_type = TypeBuilder;
1158 current_type != null && current_type != TypeManager.object_type;
1159 current_type = current_type.BaseType) {
1161 Type ct = TypeManager.DropGenericTypeArguments (current_type);
1162 if (ct is TypeBuilder) {
1163 TypeContainer tc = ct == TypeBuilder
1164 ? PartialContainer : TypeManager.LookupTypeContainer (ct);
1165 if (tc != null)
1166 t = tc.FindNestedType (name);
1167 } else {
1168 t = TypeManager.GetNestedType (ct, name);
1171 if ((t == null) || !CheckAccessLevel (t))
1172 continue;
1174 if (!TypeManager.IsGenericType (current_type))
1175 return t;
1177 Type[] args = TypeManager.GetTypeArguments (current_type);
1178 Type[] targs = TypeManager.GetTypeArguments (t);
1179 for (int i = 0; i < args.Length; i++)
1180 targs [i] = args [i];
1182 #if GMCS_SOURCE
1183 t = t.MakeGenericType (targs);
1184 #endif
1186 return t;
1189 return null;
1192 public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
1194 return null;
1198 // Public function used to locate types.
1200 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1202 // Returns: Type or null if they type can not be found.
1204 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1206 if (Cache.Contains (name))
1207 return (FullNamedExpression) Cache [name];
1209 FullNamedExpression e;
1210 int errors = Report.Errors;
1211 Type t = LookupNestedTypeInHierarchy (name);
1212 if (t != null)
1213 e = new TypeExpression (t, Location.Null);
1214 else if (Parent != null)
1215 e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
1216 else
1217 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1219 if (errors == Report.Errors)
1220 Cache [name] = e;
1222 return e;
1225 /// <remarks>
1226 /// This function is broken and not what you're looking for. It should only
1227 /// be used while the type is still being created since it doesn't use the cache
1228 /// and relies on the filter doing the member name check.
1229 /// </remarks>
1231 // [Obsolete ("Only MemberCache approach should be used")]
1232 public virtual MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1233 MemberFilter filter, object criteria)
1235 throw new NotSupportedException ();
1238 /// <remarks>
1239 /// If we have a MemberCache, return it. This property may return null if the
1240 /// class doesn't have a member cache or while it's still being created.
1241 /// </remarks>
1242 public abstract MemberCache MemberCache {
1243 get;
1246 public virtual ModuleContainer Module {
1247 get { return Parent.Module; }
1250 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
1252 if (a.Type == pa.Required) {
1253 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1254 return;
1256 TypeBuilder.SetCustomAttribute (cb);
1259 TypeParameter[] initialize_type_params ()
1261 if (type_param_list != null)
1262 return type_param_list;
1264 DeclSpace the_parent = Parent;
1265 if (this is GenericMethod)
1266 the_parent = null;
1268 ArrayList list = new ArrayList ();
1269 if (the_parent != null && the_parent.IsGeneric) {
1270 // FIXME: move generics info out of DeclSpace
1271 TypeParameter[] parent_params = the_parent.PartialContainer.TypeParameters;
1272 list.AddRange (parent_params);
1275 int count = type_params != null ? type_params.Length : 0;
1276 for (int i = 0; i < count; i++) {
1277 TypeParameter param = type_params [i];
1278 list.Add (param);
1279 if (Parent.IsGeneric) {
1280 foreach (TypeParameter tp in Parent.PartialContainer.CurrentTypeParameters) {
1281 if (tp.Name != param.Name)
1282 continue;
1284 Report.SymbolRelatedToPreviousError (tp.Location, null);
1285 Report.Warning (693, 3, param.Location,
1286 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
1287 param.Name, Parent.GetSignatureForError ());
1292 type_param_list = new TypeParameter [list.Count];
1293 list.CopyTo (type_param_list, 0);
1294 return type_param_list;
1297 public virtual void SetParameterInfo (ArrayList constraints_list)
1299 if (!is_generic) {
1300 if (constraints_list != null) {
1301 Report.Error (
1302 80, Location, "Constraints are not allowed " +
1303 "on non-generic declarations");
1306 return;
1309 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1310 type_params = new TypeParameter [names.Length];
1313 // Register all the names
1315 for (int i = 0; i < type_params.Length; i++) {
1316 TypeParameterName name = names [i];
1318 Constraints constraints = null;
1319 if (constraints_list != null) {
1320 int total = constraints_list.Count;
1321 for (int ii = 0; ii < total; ++ii) {
1322 Constraints constraints_at = (Constraints)constraints_list[ii];
1323 // TODO: it is used by iterators only
1324 if (constraints_at == null) {
1325 constraints_list.RemoveAt (ii);
1326 --total;
1327 continue;
1329 if (constraints_at.TypeParameter == name.Name) {
1330 constraints = constraints_at;
1331 constraints_list.RemoveAt(ii);
1332 break;
1337 type_params [i] = new TypeParameter (
1338 Parent, this, name.Name, constraints, name.OptAttributes, name.Variance,
1339 Location);
1341 AddToContainer (type_params [i], name.Name);
1344 if (constraints_list != null && constraints_list.Count > 0) {
1345 foreach (Constraints constraint in constraints_list) {
1346 Report.Error(699, constraint.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
1347 GetSignatureForError (), constraint.TypeParameter);
1352 public TypeParameter[] TypeParameters {
1353 get {
1354 if (!IsGeneric)
1355 throw new InvalidOperationException ();
1356 if ((PartialContainer != null) && (PartialContainer != this))
1357 return PartialContainer.TypeParameters;
1358 if (type_param_list == null)
1359 initialize_type_params ();
1361 return type_param_list;
1365 public TypeParameter[] CurrentTypeParameters {
1366 get {
1367 if (!IsGeneric)
1368 throw new InvalidOperationException ();
1370 // TODO: Something is seriously broken here
1371 if (type_params == null)
1372 return new TypeParameter [0];
1374 return type_params;
1378 public int CountTypeParameters {
1379 get {
1380 return count_type_params;
1384 public TypeParameterExpr LookupGeneric (string name, Location loc)
1386 if (!IsGeneric)
1387 return null;
1389 TypeParameter [] current_params;
1390 if (this is TypeContainer)
1391 current_params = PartialContainer.CurrentTypeParameters;
1392 else
1393 current_params = CurrentTypeParameters;
1395 foreach (TypeParameter type_param in current_params) {
1396 if (type_param.Name == name)
1397 return new TypeParameterExpr (type_param, loc);
1400 if (Parent != null)
1401 return Parent.LookupGeneric (name, loc);
1403 return null;
1406 // Used for error reporting only
1407 public virtual Type LookupAnyGeneric (string typeName)
1409 return NamespaceEntry.NS.LookForAnyGenericType (typeName);
1412 public override string[] ValidAttributeTargets {
1413 get { return attribute_targets; }
1416 protected override bool VerifyClsCompliance ()
1418 if (!base.VerifyClsCompliance ()) {
1419 return false;
1422 if (type_params != null) {
1423 foreach (TypeParameter tp in type_params) {
1424 if (tp.Constraints == null)
1425 continue;
1427 tp.Constraints.VerifyClsCompliance ();
1431 IDictionary cache = TypeManager.AllClsTopLevelTypes;
1432 if (cache == null)
1433 return true;
1435 string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1436 if (!cache.Contains (lcase)) {
1437 cache.Add (lcase, this);
1438 return true;
1441 object val = cache [lcase];
1442 if (val == null) {
1443 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1444 if (t == null)
1445 return true;
1446 Report.SymbolRelatedToPreviousError (t);
1448 else {
1449 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1452 Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1453 return true;
1457 /// <summary>
1458 /// This is a readonly list of MemberInfo's.
1459 /// </summary>
1460 public class MemberList : IList {
1461 public readonly IList List;
1462 int count;
1464 /// <summary>
1465 /// Create a new MemberList from the given IList.
1466 /// </summary>
1467 public MemberList (IList list)
1469 if (list != null)
1470 this.List = list;
1471 else
1472 this.List = new ArrayList ();
1473 count = List.Count;
1476 /// <summary>
1477 /// Concatenate the ILists `first' and `second' to a new MemberList.
1478 /// </summary>
1479 public MemberList (IList first, IList second)
1481 ArrayList list = new ArrayList ();
1482 list.AddRange (first);
1483 list.AddRange (second);
1484 count = list.Count;
1485 List = list;
1488 public static readonly MemberList Empty = new MemberList (new ArrayList (0));
1490 /// <summary>
1491 /// Cast the MemberList into a MemberInfo[] array.
1492 /// </summary>
1493 /// <remarks>
1494 /// This is an expensive operation, only use it if it's really necessary.
1495 /// </remarks>
1496 public static explicit operator MemberInfo [] (MemberList list)
1498 Timer.StartTimer (TimerType.MiscTimer);
1499 MemberInfo [] result = new MemberInfo [list.Count];
1500 list.CopyTo (result, 0);
1501 Timer.StopTimer (TimerType.MiscTimer);
1502 return result;
1505 // ICollection
1507 public int Count {
1508 get {
1509 return count;
1513 public bool IsSynchronized {
1514 get {
1515 return List.IsSynchronized;
1519 public object SyncRoot {
1520 get {
1521 return List.SyncRoot;
1525 public void CopyTo (Array array, int index)
1527 List.CopyTo (array, index);
1530 // IEnumerable
1532 public IEnumerator GetEnumerator ()
1534 return List.GetEnumerator ();
1537 // IList
1539 public bool IsFixedSize {
1540 get {
1541 return true;
1545 public bool IsReadOnly {
1546 get {
1547 return true;
1551 object IList.this [int index] {
1552 get {
1553 return List [index];
1556 set {
1557 throw new NotSupportedException ();
1561 // FIXME: try to find out whether we can avoid the cast in this indexer.
1562 public MemberInfo this [int index] {
1563 get {
1564 return (MemberInfo) List [index];
1568 public int Add (object value)
1570 throw new NotSupportedException ();
1573 public void Clear ()
1575 throw new NotSupportedException ();
1578 public bool Contains (object value)
1580 return List.Contains (value);
1583 public int IndexOf (object value)
1585 return List.IndexOf (value);
1588 public void Insert (int index, object value)
1590 throw new NotSupportedException ();
1593 public void Remove (object value)
1595 throw new NotSupportedException ();
1598 public void RemoveAt (int index)
1600 throw new NotSupportedException ();
1604 /// <summary>
1605 /// This interface is used to get all members of a class when creating the
1606 /// member cache. It must be implemented by all DeclSpace derivatives which
1607 /// want to support the member cache and by TypeHandle to get caching of
1608 /// non-dynamic types.
1609 /// </summary>
1610 public interface IMemberContainer {
1611 /// <summary>
1612 /// The name of the IMemberContainer. This is only used for
1613 /// debugging purposes.
1614 /// </summary>
1615 string Name {
1616 get;
1619 /// <summary>
1620 /// The type of this IMemberContainer.
1621 /// </summary>
1622 Type Type {
1623 get;
1626 /// <summary>
1627 /// Returns the IMemberContainer of the base class or null if this
1628 /// is an interface or TypeManger.object_type.
1629 /// This is used when creating the member cache for a class to get all
1630 /// members from the base class.
1631 /// </summary>
1632 MemberCache BaseCache {
1633 get;
1636 /// <summary>
1637 /// Whether this is an interface.
1638 /// </summary>
1639 bool IsInterface {
1640 get;
1643 /// <summary>
1644 /// Returns all members of this class with the corresponding MemberTypes
1645 /// and BindingFlags.
1646 /// </summary>
1647 /// <remarks>
1648 /// When implementing this method, make sure not to return any inherited
1649 /// members and check the MemberTypes and BindingFlags properly.
1650 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1651 /// get the BindingFlags (static/non-static,public/non-public) in the
1652 /// MemberInfo class, but the cache needs this information. That's why
1653 /// this method is called multiple times with different BindingFlags.
1654 /// </remarks>
1655 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1658 /// <summary>
1659 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1660 /// member lookups. It has a member name based hash table; it maps each member
1661 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1662 /// and the BindingFlags that were initially used to get it. The cache contains
1663 /// all members of the current class and all inherited members. If this cache is
1664 /// for an interface types, it also contains all inherited members.
1666 /// There are two ways to get a MemberCache:
1667 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1668 /// use the DeclSpace.MemberCache property.
1669 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1670 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1671 /// </summary>
1672 public class MemberCache {
1673 public readonly IMemberContainer Container;
1674 protected Hashtable member_hash;
1675 protected Hashtable method_hash;
1677 /// <summary>
1678 /// Create a new MemberCache for the given IMemberContainer `container'.
1679 /// </summary>
1680 public MemberCache (IMemberContainer container)
1682 this.Container = container;
1684 Timer.IncrementCounter (CounterType.MemberCache);
1685 Timer.StartTimer (TimerType.CacheInit);
1687 // If we have a base class (we have a base class unless we're
1688 // TypeManager.object_type), we deep-copy its MemberCache here.
1689 if (Container.BaseCache != null)
1690 member_hash = SetupCache (Container.BaseCache);
1691 else
1692 member_hash = new Hashtable ();
1694 // If this is neither a dynamic type nor an interface, create a special
1695 // method cache with all declared and inherited methods.
1696 Type type = container.Type;
1697 if (!(type is TypeBuilder) && !type.IsInterface &&
1698 // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1699 !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
1700 (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1701 method_hash = new Hashtable ();
1702 AddMethods (type);
1705 // Add all members from the current class.
1706 AddMembers (Container);
1708 Timer.StopTimer (TimerType.CacheInit);
1711 public MemberCache (Type baseType, IMemberContainer container)
1713 this.Container = container;
1714 if (baseType == null)
1715 this.member_hash = new Hashtable ();
1716 else
1717 this.member_hash = SetupCache (TypeManager.LookupMemberCache (baseType));
1720 public MemberCache (Type[] ifaces)
1723 // The members of this cache all belong to other caches.
1724 // So, 'Container' will not be used.
1726 this.Container = null;
1728 member_hash = new Hashtable ();
1729 if (ifaces == null)
1730 return;
1732 foreach (Type itype in ifaces)
1733 AddCacheContents (TypeManager.LookupMemberCache (itype));
1736 public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
1738 this.Container = container;
1740 // If we have a base class (we have a base class unless we're
1741 // TypeManager.object_type), we deep-copy its MemberCache here.
1742 if (Container.BaseCache != null)
1743 member_hash = SetupCache (Container.BaseCache);
1744 else
1745 member_hash = new Hashtable ();
1747 if (base_class != null)
1748 AddCacheContents (TypeManager.LookupMemberCache (base_class));
1749 if (ifaces != null) {
1750 foreach (Type itype in ifaces) {
1751 MemberCache cache = TypeManager.LookupMemberCache (itype);
1752 if (cache != null)
1753 AddCacheContents (cache);
1758 /// <summary>
1759 /// Bootstrap this member cache by doing a deep-copy of our base.
1760 /// </summary>
1761 static Hashtable SetupCache (MemberCache base_class)
1763 if (base_class == null)
1764 return new Hashtable ();
1766 Hashtable hash = new Hashtable (base_class.member_hash.Count);
1767 IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1768 while (it.MoveNext ()) {
1769 hash.Add (it.Key, ((ArrayList) it.Value).Clone ());
1772 return hash;
1776 // Converts ModFlags to BindingFlags
1778 static BindingFlags GetBindingFlags (int modifiers)
1780 BindingFlags bf;
1781 if ((modifiers & Modifiers.STATIC) != 0)
1782 bf = BindingFlags.Static;
1783 else
1784 bf = BindingFlags.Instance;
1786 if ((modifiers & Modifiers.PRIVATE) != 0)
1787 bf |= BindingFlags.NonPublic;
1788 else
1789 bf |= BindingFlags.Public;
1791 return bf;
1794 /// <summary>
1795 /// Add the contents of `cache' to the member_hash.
1796 /// </summary>
1797 void AddCacheContents (MemberCache cache)
1799 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1800 while (it.MoveNext ()) {
1801 ArrayList list = (ArrayList) member_hash [it.Key];
1802 if (list == null)
1803 member_hash [it.Key] = list = new ArrayList ();
1805 ArrayList entries = (ArrayList) it.Value;
1806 for (int i = entries.Count-1; i >= 0; i--) {
1807 CacheEntry entry = (CacheEntry) entries [i];
1809 if (entry.Container != cache.Container)
1810 break;
1811 list.Add (entry);
1816 /// <summary>
1817 /// Add all members from class `container' to the cache.
1818 /// </summary>
1819 void AddMembers (IMemberContainer container)
1821 // We need to call AddMembers() with a single member type at a time
1822 // to get the member type part of CacheEntry.EntryType right.
1823 if (!container.IsInterface) {
1824 AddMembers (MemberTypes.Constructor, container);
1825 AddMembers (MemberTypes.Field, container);
1827 AddMembers (MemberTypes.Method, container);
1828 AddMembers (MemberTypes.Property, container);
1829 AddMembers (MemberTypes.Event, container);
1830 // Nested types are returned by both Static and Instance searches.
1831 AddMembers (MemberTypes.NestedType,
1832 BindingFlags.Static | BindingFlags.Public, container);
1833 AddMembers (MemberTypes.NestedType,
1834 BindingFlags.Static | BindingFlags.NonPublic, container);
1837 void AddMembers (MemberTypes mt, IMemberContainer container)
1839 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1840 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1841 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1842 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1845 public void AddMember (MemberInfo mi, MemberCore mc)
1847 AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container, mi.Name, mi);
1850 public void AddGenericMember (MemberInfo mi, InterfaceMemberBase mc)
1852 AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container,
1853 MemberName.MakeName (mc.GetFullName (mc.MemberName), mc.MemberName.TypeArguments), mi);
1856 public void AddNestedType (DeclSpace type)
1858 AddMember (MemberTypes.NestedType, GetBindingFlags (type.ModFlags), (IMemberContainer) type.Parent,
1859 type.TypeBuilder.Name, type.TypeBuilder);
1862 public void AddInterface (MemberCache baseCache)
1864 if (baseCache.member_hash.Count > 0)
1865 AddCacheContents (baseCache);
1868 void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
1869 string name, MemberInfo member)
1871 // We use a name-based hash table of ArrayList's.
1872 ArrayList list = (ArrayList) member_hash [name];
1873 if (list == null) {
1874 list = new ArrayList (1);
1875 member_hash.Add (name, list);
1878 // When this method is called for the current class, the list will
1879 // already contain all inherited members from our base classes.
1880 // We cannot add new members in front of the list since this'd be an
1881 // expensive operation, that's why the list is sorted in reverse order
1882 // (ie. members from the current class are coming last).
1883 list.Add (new CacheEntry (container, member, mt, bf));
1886 /// <summary>
1887 /// Add all members from class `container' with the requested MemberTypes and
1888 /// BindingFlags to the cache. This method is called multiple times with different
1889 /// MemberTypes and BindingFlags.
1890 /// </summary>
1891 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1893 MemberList members = container.GetMembers (mt, bf);
1895 foreach (MemberInfo member in members) {
1896 string name = member.Name;
1898 AddMember (mt, bf, container, name, member);
1900 if (member is MethodInfo) {
1901 string gname = TypeManager.GetMethodName ((MethodInfo) member);
1902 if (gname != name)
1903 AddMember (mt, bf, container, gname, member);
1908 /// <summary>
1909 /// Add all declared and inherited methods from class `type' to the method cache.
1910 /// </summary>
1911 void AddMethods (Type type)
1913 AddMethods (BindingFlags.Static | BindingFlags.Public |
1914 BindingFlags.FlattenHierarchy, type);
1915 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1916 BindingFlags.FlattenHierarchy, type);
1917 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1918 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1921 static ArrayList overrides = new ArrayList ();
1923 void AddMethods (BindingFlags bf, Type type)
1925 MethodBase [] members = type.GetMethods (bf);
1927 Array.Reverse (members);
1929 foreach (MethodBase member in members) {
1930 string name = member.Name;
1932 // We use a name-based hash table of ArrayList's.
1933 ArrayList list = (ArrayList) method_hash [name];
1934 if (list == null) {
1935 list = new ArrayList (1);
1936 method_hash.Add (name, list);
1939 MethodInfo curr = (MethodInfo) member;
1940 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1941 MethodInfo base_method = curr.GetBaseDefinition ();
1943 if (base_method == curr)
1944 // Not every virtual function needs to have a NewSlot flag.
1945 break;
1947 overrides.Add (curr);
1948 list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1949 curr = base_method;
1952 if (overrides.Count > 0) {
1953 for (int i = 0; i < overrides.Count; ++i)
1954 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1955 overrides.Clear ();
1958 // Unfortunately, the elements returned by Type.GetMethods() aren't
1959 // sorted so we need to do this check for every member.
1960 BindingFlags new_bf = bf;
1961 if (member.DeclaringType == type)
1962 new_bf |= BindingFlags.DeclaredOnly;
1964 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1968 /// <summary>
1969 /// Compute and return a appropriate `EntryType' magic number for the given
1970 /// MemberTypes and BindingFlags.
1971 /// </summary>
1972 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1974 EntryType type = EntryType.None;
1976 if ((mt & MemberTypes.Constructor) != 0)
1977 type |= EntryType.Constructor;
1978 if ((mt & MemberTypes.Event) != 0)
1979 type |= EntryType.Event;
1980 if ((mt & MemberTypes.Field) != 0)
1981 type |= EntryType.Field;
1982 if ((mt & MemberTypes.Method) != 0)
1983 type |= EntryType.Method;
1984 if ((mt & MemberTypes.Property) != 0)
1985 type |= EntryType.Property;
1986 // Nested types are returned by static and instance searches.
1987 if ((mt & MemberTypes.NestedType) != 0)
1988 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1990 if ((bf & BindingFlags.Instance) != 0)
1991 type |= EntryType.Instance;
1992 if ((bf & BindingFlags.Static) != 0)
1993 type |= EntryType.Static;
1994 if ((bf & BindingFlags.Public) != 0)
1995 type |= EntryType.Public;
1996 if ((bf & BindingFlags.NonPublic) != 0)
1997 type |= EntryType.NonPublic;
1998 if ((bf & BindingFlags.DeclaredOnly) != 0)
1999 type |= EntryType.Declared;
2001 return type;
2004 /// <summary>
2005 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
2006 /// denote multiple member types. Returns true if the given flags value denotes a
2007 /// single member types.
2008 /// </summary>
2009 public static bool IsSingleMemberType (MemberTypes mt)
2011 switch (mt) {
2012 case MemberTypes.Constructor:
2013 case MemberTypes.Event:
2014 case MemberTypes.Field:
2015 case MemberTypes.Method:
2016 case MemberTypes.Property:
2017 case MemberTypes.NestedType:
2018 return true;
2020 default:
2021 return false;
2025 /// <summary>
2026 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
2027 /// number to speed up the searching process.
2028 /// </summary>
2029 [Flags]
2030 protected enum EntryType {
2031 None = 0x000,
2033 Instance = 0x001,
2034 Static = 0x002,
2035 MaskStatic = Instance|Static,
2037 Public = 0x004,
2038 NonPublic = 0x008,
2039 MaskProtection = Public|NonPublic,
2041 Declared = 0x010,
2043 Constructor = 0x020,
2044 Event = 0x040,
2045 Field = 0x080,
2046 Method = 0x100,
2047 Property = 0x200,
2048 NestedType = 0x400,
2050 NotExtensionMethod = 0x800,
2052 MaskType = Constructor|Event|Field|Method|Property|NestedType
2055 protected class CacheEntry {
2056 public readonly IMemberContainer Container;
2057 public EntryType EntryType;
2058 public readonly MemberInfo Member;
2060 public CacheEntry (IMemberContainer container, MemberInfo member,
2061 MemberTypes mt, BindingFlags bf)
2063 this.Container = container;
2064 this.Member = member;
2065 this.EntryType = GetEntryType (mt, bf);
2068 public override string ToString ()
2070 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
2071 EntryType, Member);
2075 /// <summary>
2076 /// This is called each time we're walking up one level in the class hierarchy
2077 /// and checks whether we can abort the search since we've already found what
2078 /// we were looking for.
2079 /// </summary>
2080 protected bool DoneSearching (ArrayList list)
2083 // We've found exactly one member in the current class and it's not
2084 // a method or constructor.
2086 if (list.Count == 1 && !(list [0] is MethodBase))
2087 return true;
2090 // Multiple properties: we query those just to find out the indexer
2091 // name
2093 if ((list.Count > 0) && (list [0] is PropertyInfo))
2094 return true;
2096 return false;
2099 /// <summary>
2100 /// Looks up members with name `name'. If you provide an optional
2101 /// filter function, it'll only be called with members matching the
2102 /// requested member name.
2104 /// This method will try to use the cache to do the lookup if possible.
2106 /// Unlike other FindMembers implementations, this method will always
2107 /// check all inherited members - even when called on an interface type.
2109 /// If you know that you're only looking for methods, you should use
2110 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2111 /// When doing a method-only search, it'll try to use a special method
2112 /// cache (unless it's a dynamic type or an interface) and the returned
2113 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2114 /// The lookup process will automatically restart itself in method-only
2115 /// search mode if it discovers that it's about to return methods.
2116 /// </summary>
2117 ArrayList global = new ArrayList ();
2118 bool using_global = false;
2120 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2122 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2123 MemberFilter filter, object criteria)
2125 if (using_global)
2126 throw new Exception ();
2128 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2129 bool method_search = mt == MemberTypes.Method;
2130 // If we have a method cache and we aren't already doing a method-only search,
2131 // then we restart a method search if the first match is a method.
2132 bool do_method_search = !method_search && (method_hash != null);
2134 ArrayList applicable;
2136 // If this is a method-only search, we try to use the method cache if
2137 // possible; a lookup in the method cache will return a MemberInfo with
2138 // the correct ReflectedType for inherited methods.
2140 if (method_search && (method_hash != null))
2141 applicable = (ArrayList) method_hash [name];
2142 else
2143 applicable = (ArrayList) member_hash [name];
2145 if (applicable == null)
2146 return emptyMemberInfo;
2149 // 32 slots gives 53 rss/54 size
2150 // 2/4 slots gives 55 rss
2152 // Strange: from 25,000 calls, only 1,800
2153 // are above 2. Why does this impact it?
2155 global.Clear ();
2156 using_global = true;
2158 Timer.StartTimer (TimerType.CachedLookup);
2160 EntryType type = GetEntryType (mt, bf);
2162 IMemberContainer current = Container;
2164 bool do_interface_search = current.IsInterface;
2166 // `applicable' is a list of all members with the given member name `name'
2167 // in the current class and all its base classes. The list is sorted in
2168 // reverse order due to the way how the cache is initialy created (to speed
2169 // things up, we're doing a deep-copy of our base).
2171 for (int i = applicable.Count-1; i >= 0; i--) {
2172 CacheEntry entry = (CacheEntry) applicable [i];
2174 // This happens each time we're walking one level up in the class
2175 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2176 // the first time this happens (this may already happen in the first
2177 // iteration of this loop if there are no members with the name we're
2178 // looking for in the current class).
2179 if (entry.Container != current) {
2180 if (declared_only)
2181 break;
2183 if (!do_interface_search && DoneSearching (global))
2184 break;
2186 current = entry.Container;
2189 // Is the member of the correct type ?
2190 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2191 continue;
2193 // Is the member static/non-static ?
2194 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2195 continue;
2197 // Apply the filter to it.
2198 if (filter (entry.Member, criteria)) {
2199 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
2200 do_method_search = false;
2203 // Because interfaces support multiple inheritance we have to be sure that
2204 // base member is from same interface, so only top level member will be returned
2205 if (do_interface_search && global.Count > 0) {
2206 bool member_already_exists = false;
2208 foreach (MemberInfo mi in global) {
2209 if (mi is MethodBase)
2210 continue;
2212 if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
2213 member_already_exists = true;
2214 break;
2217 if (member_already_exists)
2218 continue;
2221 global.Add (entry.Member);
2225 Timer.StopTimer (TimerType.CachedLookup);
2227 // If we have a method cache and we aren't already doing a method-only
2228 // search, we restart in method-only search mode if the first match is
2229 // a method. This ensures that we return a MemberInfo with the correct
2230 // ReflectedType for inherited methods.
2231 if (do_method_search && (global.Count > 0)){
2232 using_global = false;
2234 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2237 using_global = false;
2238 MemberInfo [] copy = new MemberInfo [global.Count];
2239 global.CopyTo (copy);
2240 return copy;
2243 /// <summary>
2244 /// Returns true if iterface exists in any base interfaces (ifaces)
2245 /// </summary>
2246 static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
2248 foreach (Type iface in ifaces) {
2249 if (iface == ifaceToFind)
2250 return true;
2252 Type[] base_ifaces = TypeManager.GetInterfaces (iface);
2253 if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
2254 return true;
2256 return false;
2259 // find the nested type @name in @this.
2260 public Type FindNestedType (string name)
2262 ArrayList applicable = (ArrayList) member_hash [name];
2263 if (applicable == null)
2264 return null;
2266 for (int i = applicable.Count-1; i >= 0; i--) {
2267 CacheEntry entry = (CacheEntry) applicable [i];
2268 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2269 return (Type) entry.Member;
2272 return null;
2275 public MemberInfo FindBaseEvent (Type invocation_type, string name)
2277 ArrayList applicable = (ArrayList) member_hash [name];
2278 if (applicable == null)
2279 return null;
2282 // Walk the chain of events, starting from the top.
2284 for (int i = applicable.Count - 1; i >= 0; i--)
2286 CacheEntry entry = (CacheEntry) applicable [i];
2287 if ((entry.EntryType & EntryType.Event) == 0)
2288 continue;
2290 EventInfo ei = (EventInfo)entry.Member;
2291 return ei.GetAddMethod (true);
2294 return null;
2298 // Looks for extension methods with defined name and extension type
2300 public ArrayList FindExtensionMethods (Type extensionType, string name, bool publicOnly)
2302 ArrayList entries;
2303 if (method_hash != null)
2304 entries = (ArrayList)method_hash [name];
2305 else
2306 entries = (ArrayList)member_hash [name];
2308 if (entries == null)
2309 return null;
2311 EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
2312 EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
2314 ArrayList candidates = null;
2315 foreach (CacheEntry entry in entries) {
2316 if ((entry.EntryType & entry_type) == found_entry_type) {
2317 MethodBase mb = (MethodBase)entry.Member;
2319 // Simple accessibility check
2320 if ((entry.EntryType & EntryType.Public) == 0 && publicOnly) {
2321 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2322 if (ma != MethodAttributes.Assembly && ma != MethodAttributes.FamORAssem)
2323 continue;
2325 if (!TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly))
2326 continue;
2329 IMethodData md = TypeManager.GetMethod (mb);
2330 AParametersCollection pd = md == null ?
2331 TypeManager.GetParameterData (mb) : md.ParameterInfo;
2333 Type ex_type = pd.ExtensionMethodType;
2334 if (ex_type == null) {
2335 entry.EntryType |= EntryType.NotExtensionMethod;
2336 continue;
2339 //if (implicit conversion between ex_type and extensionType exist) {
2340 if (candidates == null)
2341 candidates = new ArrayList (2);
2342 candidates.Add (mb);
2347 return candidates;
2351 // This finds the method or property for us to override. invocation_type is the type where
2352 // the override is going to be declared, name is the name of the method/property, and
2353 // param_types is the parameters, if any to the method or property
2355 // Because the MemberCache holds members from this class and all the base classes,
2356 // we can avoid tons of reflection stuff.
2358 public MemberInfo FindMemberToOverride (Type invocation_type, string name, AParametersCollection parameters, GenericMethod generic_method, bool is_property)
2360 ArrayList applicable;
2361 if (method_hash != null && !is_property)
2362 applicable = (ArrayList) method_hash [name];
2363 else
2364 applicable = (ArrayList) member_hash [name];
2366 if (applicable == null)
2367 return null;
2369 // Walk the chain of methods, starting from the top.
2371 for (int i = applicable.Count - 1; i >= 0; i--) {
2372 CacheEntry entry = (CacheEntry) applicable [i];
2374 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2375 continue;
2377 PropertyInfo pi = null;
2378 MethodInfo mi = null;
2379 FieldInfo fi = null;
2380 AParametersCollection cmp_attrs;
2382 if (is_property) {
2383 if ((entry.EntryType & EntryType.Field) != 0) {
2384 fi = (FieldInfo)entry.Member;
2385 cmp_attrs = ParametersCompiled.EmptyReadOnlyParameters;
2386 } else {
2387 pi = (PropertyInfo) entry.Member;
2388 cmp_attrs = TypeManager.GetParameterData (pi);
2390 } else {
2391 mi = (MethodInfo) entry.Member;
2392 cmp_attrs = TypeManager.GetParameterData (mi);
2395 if (fi != null) {
2396 // TODO: Almost duplicate !
2397 // Check visibility
2398 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2399 case FieldAttributes.PrivateScope:
2400 continue;
2401 case FieldAttributes.Private:
2403 // A private method is Ok if we are a nested subtype.
2404 // The spec actually is not very clear about this, see bug 52458.
2406 if (!invocation_type.Equals (entry.Container.Type) &&
2407 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2408 continue;
2409 break;
2410 case FieldAttributes.FamANDAssem:
2411 case FieldAttributes.Assembly:
2413 // Check for assembly methods
2415 if (fi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2416 continue;
2417 break;
2419 return entry.Member;
2423 // Check the arguments
2425 if (cmp_attrs.Count != parameters.Count)
2426 continue;
2428 int j;
2429 for (j = 0; j < cmp_attrs.Count; ++j) {
2431 // LAMESPEC: No idea why `params' modifier is ignored
2433 if ((parameters.FixedParameters [j].ModFlags & ~Parameter.Modifier.PARAMS) !=
2434 (cmp_attrs.FixedParameters [j].ModFlags & ~Parameter.Modifier.PARAMS))
2435 break;
2437 if (!TypeManager.IsEqual (parameters.Types [j], cmp_attrs.Types [j]))
2438 break;
2441 if (j < cmp_attrs.Count)
2442 continue;
2445 // check generic arguments for methods
2447 if (mi != null) {
2448 Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
2449 if (generic_method == null && cmpGenArgs != null && cmpGenArgs.Length != 0)
2450 continue;
2451 if (generic_method != null && cmpGenArgs != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
2452 continue;
2456 // get one of the methods because this has the visibility info.
2458 if (is_property) {
2459 mi = pi.GetGetMethod (true);
2460 if (mi == null)
2461 mi = pi.GetSetMethod (true);
2465 // Check visibility
2467 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2468 case MethodAttributes.PrivateScope:
2469 continue;
2470 case MethodAttributes.Private:
2472 // A private method is Ok if we are a nested subtype.
2473 // The spec actually is not very clear about this, see bug 52458.
2475 if (!invocation_type.Equals (entry.Container.Type) &&
2476 !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
2477 continue;
2478 break;
2479 case MethodAttributes.FamANDAssem:
2480 case MethodAttributes.Assembly:
2482 // Check for assembly methods
2484 if (!TypeManager.IsThisOrFriendAssembly (mi.DeclaringType.Assembly))
2485 continue;
2486 break;
2488 return entry.Member;
2491 return null;
2494 /// <summary>
2495 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2496 /// We handle two cases. The first is for types without parameters (events, field, properties).
2497 /// The second are methods, indexers and this is why ignore_complex_types is here.
2498 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2499 /// </summary>
2500 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2502 ArrayList applicable = null;
2504 if (method_hash != null)
2505 applicable = (ArrayList) method_hash [name];
2507 if (applicable != null) {
2508 for (int i = applicable.Count - 1; i >= 0; i--) {
2509 CacheEntry entry = (CacheEntry) applicable [i];
2510 if ((entry.EntryType & EntryType.Public) != 0)
2511 return entry.Member;
2515 if (member_hash == null)
2516 return null;
2517 applicable = (ArrayList) member_hash [name];
2519 if (applicable != null) {
2520 for (int i = applicable.Count - 1; i >= 0; i--) {
2521 CacheEntry entry = (CacheEntry) applicable [i];
2522 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2523 if (ignore_complex_types) {
2524 if ((entry.EntryType & EntryType.Method) != 0)
2525 continue;
2527 // Does exist easier way how to detect indexer ?
2528 if ((entry.EntryType & EntryType.Property) != 0) {
2529 AParametersCollection arg_types = TypeManager.GetParameterData ((PropertyInfo)entry.Member);
2530 if (arg_types.Count > 0)
2531 continue;
2534 return entry.Member;
2538 return null;
2541 Hashtable locase_table;
2543 /// <summary>
2544 /// Builds low-case table for CLS Compliance test
2545 /// </summary>
2546 public Hashtable GetPublicMembers ()
2548 if (locase_table != null)
2549 return locase_table;
2551 locase_table = new Hashtable ();
2552 foreach (DictionaryEntry entry in member_hash) {
2553 ArrayList members = (ArrayList)entry.Value;
2554 for (int ii = 0; ii < members.Count; ++ii) {
2555 CacheEntry member_entry = (CacheEntry) members [ii];
2557 if ((member_entry.EntryType & EntryType.Public) == 0)
2558 continue;
2560 // TODO: Does anyone know easier way how to detect that member is internal ?
2561 switch (member_entry.EntryType & EntryType.MaskType) {
2562 case EntryType.Constructor:
2563 continue;
2565 case EntryType.Field:
2566 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2567 continue;
2568 break;
2570 case EntryType.Method:
2571 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2572 continue;
2573 break;
2575 case EntryType.Property:
2576 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2577 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2578 continue;
2579 break;
2581 case EntryType.Event:
2582 EventInfo ei = (EventInfo)member_entry.Member;
2583 MethodInfo mi = ei.GetAddMethod ();
2584 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2585 continue;
2586 break;
2588 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2589 locase_table [lcase] = member_entry.Member;
2590 break;
2593 return locase_table;
2596 public Hashtable Members {
2597 get {
2598 return member_hash;
2602 /// <summary>
2603 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2604 /// </summary>
2605 ///
2606 // TODO: refactor as method is always 'this'
2607 public static void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2609 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2611 for (int i = 0; i < al.Count; ++i) {
2612 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2614 // skip itself
2615 if (entry.Member == this_builder)
2616 continue;
2618 if ((entry.EntryType & tested_type) != tested_type)
2619 continue;
2621 MethodBase method_to_compare = (MethodBase)entry.Member;
2622 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2623 method.Parameters, TypeManager.GetParameterData (method_to_compare));
2625 if (result == AttributeTester.Result.Ok)
2626 continue;
2628 IMethodData md = TypeManager.GetMethod (method_to_compare);
2630 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2631 // However it is exactly what csc does.
2632 if (md != null && !md.IsClsComplianceRequired ())
2633 continue;
2635 Report.SymbolRelatedToPreviousError (entry.Member);
2636 switch (result) {
2637 case AttributeTester.Result.RefOutArrayError:
2638 Report.Warning (3006, 1, method.Location,
2639 "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant",
2640 method.GetSignatureForError ());
2641 continue;
2642 case AttributeTester.Result.ArrayArrayError:
2643 Report.Warning (3007, 1, method.Location,
2644 "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant",
2645 method.GetSignatureForError ());
2646 continue;
2649 throw new NotImplementedException (result.ToString ());
2653 public bool CheckExistingMembersOverloads (MemberCore member, string name, ParametersCompiled parameters)
2655 ArrayList entries = (ArrayList)member_hash [name];
2656 if (entries == null)
2657 return true;
2659 int method_param_count = parameters.Count;
2660 for (int i = entries.Count - 1; i >= 0; --i) {
2661 CacheEntry ce = (CacheEntry) entries [i];
2663 if (ce.Container != member.Parent.PartialContainer)
2664 return true;
2666 Type [] p_types;
2667 AParametersCollection pd;
2668 if ((ce.EntryType & EntryType.Property) != 0) {
2669 pd = TypeManager.GetParameterData ((PropertyInfo) ce.Member);
2670 p_types = pd.Types;
2671 } else {
2672 MethodBase mb = (MethodBase) ce.Member;
2674 // TODO: This is more like a hack, because we are adding generic methods
2675 // twice with and without arity name
2676 if (TypeManager.IsGenericMethod (mb) && !member.MemberName.IsGeneric)
2677 continue;
2679 pd = TypeManager.GetParameterData (mb);
2680 p_types = pd.Types;
2683 if (p_types.Length != method_param_count)
2684 continue;
2686 if (method_param_count > 0) {
2687 int ii = method_param_count - 1;
2688 Type type_a, type_b;
2689 do {
2690 type_a = parameters.Types [ii];
2691 type_b = p_types [ii];
2693 #if GMCS_SOURCE
2694 if (TypeManager.IsGenericParameter (type_a) && type_a.DeclaringMethod != null)
2695 type_a = typeof (TypeParameter);
2697 if (TypeManager.IsGenericParameter (type_b) && type_b.DeclaringMethod != null)
2698 type_b = typeof (TypeParameter);
2699 #endif
2700 if ((pd.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF) !=
2701 (parameters.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF))
2702 type_a = null;
2704 } while (type_a == type_b && ii-- != 0);
2706 if (ii >= 0)
2707 continue;
2710 // Operators can differ in return type only
2712 if (member is Operator) {
2713 Operator op = TypeManager.GetMethod ((MethodBase) ce.Member) as Operator;
2714 if (op != null && op.ReturnType != ((Operator) member).ReturnType)
2715 continue;
2719 // Report difference in parameter modifiers only
2721 if (pd != null && member is MethodCore) {
2722 ii = method_param_count;
2723 while (ii-- != 0 && parameters.FixedParameters [ii].ModFlags == pd.FixedParameters [ii].ModFlags &&
2724 parameters.ExtensionMethodType == pd.ExtensionMethodType);
2726 if (ii >= 0) {
2727 MethodCore mc = TypeManager.GetMethod ((MethodBase) ce.Member) as MethodCore;
2728 Report.SymbolRelatedToPreviousError (ce.Member);
2729 if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.ModFlags & Modifiers.PARTIAL) != 0) {
2730 if (parameters.HasParams || pd.HasParams) {
2731 Report.Error (758, member.Location,
2732 "A partial method declaration and partial method implementation cannot differ on use of `params' modifier");
2733 } else {
2734 Report.Error (755, member.Location,
2735 "A partial method declaration and partial method implementation must be both an extension method or neither");
2737 } else {
2738 Report.Error (663, member.Location,
2739 "An overloaded method `{0}' cannot differ on use of parameter modifiers only",
2740 member.GetSignatureForError ());
2742 return false;
2747 if ((ce.EntryType & EntryType.Method) != 0) {
2748 Method method_a = member as Method;
2749 Method method_b = TypeManager.GetMethod ((MethodBase) ce.Member) as Method;
2750 if (method_a != null && method_b != null && (method_a.ModFlags & method_b.ModFlags & Modifiers.PARTIAL) != 0) {
2751 const int partial_modifiers = Modifiers.STATIC | Modifiers.UNSAFE;
2752 if (method_a.IsPartialDefinition == method_b.IsPartialImplementation) {
2753 if ((method_a.ModFlags & partial_modifiers) == (method_b.ModFlags & partial_modifiers) ||
2754 method_a.Parent.IsInUnsafeScope && method_b.Parent.IsInUnsafeScope) {
2755 if (method_a.IsPartialImplementation) {
2756 method_a.SetPartialDefinition (method_b);
2757 entries.RemoveAt (i);
2758 } else {
2759 method_b.SetPartialDefinition (method_a);
2761 continue;
2764 if ((method_a.ModFlags & Modifiers.STATIC) != (method_b.ModFlags & Modifiers.STATIC)) {
2765 Report.SymbolRelatedToPreviousError (ce.Member);
2766 Report.Error (763, member.Location,
2767 "A partial method declaration and partial method implementation must be both `static' or neither");
2770 Report.SymbolRelatedToPreviousError (ce.Member);
2771 Report.Error (764, member.Location,
2772 "A partial method declaration and partial method implementation must be both `unsafe' or neither");
2773 return false;
2776 Report.SymbolRelatedToPreviousError (ce.Member);
2777 if (method_a.IsPartialDefinition) {
2778 Report.Error (756, member.Location, "A partial method `{0}' declaration is already defined",
2779 member.GetSignatureForError ());
2782 Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
2783 member.GetSignatureForError ());
2784 return false;
2787 Report.SymbolRelatedToPreviousError (ce.Member);
2788 IMethodData duplicate_member = TypeManager.GetMethod ((MethodBase) ce.Member);
2789 if (member is Operator && duplicate_member is Operator) {
2790 Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
2791 member.Parent.GetSignatureForError ());
2792 return false;
2795 bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
2796 bool is_reserved_b = duplicate_member is AbstractPropertyEventMethod || duplicate_member is Operator;
2798 if (is_reserved_a || is_reserved_b) {
2799 Report.Error (82, member.Location, "A member `{0}' is already reserved",
2800 is_reserved_a ?
2801 TypeManager.GetFullNameSignature (ce.Member) :
2802 member.GetSignatureForError ());
2803 return false;
2805 } else {
2806 Report.SymbolRelatedToPreviousError (ce.Member);
2809 Report.Error (111, member.Location,
2810 "A member `{0}' is already defined. Rename this member or use different parameter types",
2811 member.GetSignatureForError ());
2812 return false;
2815 return true;