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
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.CompilerServices;
20 using System.Runtime.InteropServices;
21 using System.Security;
22 using System.Security.Permissions;
25 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
26 using XmlElement = System.Object;
31 using Mono.CompilerServices.SymbolWriter;
33 namespace Mono.CSharp {
45 /// This is the base class for structs and classes.
47 public abstract class TypeContainer : DeclSpace, IMemberContainer {
49 public class MemberCoreArrayList: ArrayList
52 /// Defines the MemberCore objects that are in this array
54 public virtual void DefineContainerMembers ()
56 foreach (MemberCore mc in this) {
59 } catch (Exception e) {
60 throw new InternalErrorException (mc, e);
65 public virtual void Emit ()
67 foreach (MemberCore mc in this)
72 public class OperatorArrayList: MemberCoreArrayList
74 TypeContainer container;
76 public OperatorArrayList (TypeContainer container)
78 this.container = container;
82 // Checks that some operators come in pairs:
88 // They are matched based on the return type and the argument types
90 void CheckPairedOperators ()
92 bool has_equality_or_inequality = false;
93 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
94 bool [] has_pair = new bool [operators.Length];
96 for (int i = 0; i < Count; ++i) {
97 if (operators [i] == null)
100 Operator o_a = operators [i];
101 Operator.OpType o_type = o_a.OperatorType;
102 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
103 has_equality_or_inequality = true;
105 Operator.OpType matching_type = o_a.GetMatchingOperator ();
106 if (matching_type == Operator.OpType.TOP) {
107 operators [i] = null;
111 for (int ii = 0; ii < Count; ++ii) {
112 Operator o_b = operators [ii];
113 if (o_b == null || o_b.OperatorType != matching_type)
116 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
119 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
122 operators [i] = null;
125 // Used to ignore duplicate user conversions
127 has_pair [ii] = true;
131 for (int i = 0; i < Count; ++i) {
132 if (operators [i] == null || has_pair [i])
135 Operator o = operators [i];
136 Report.Error (216, o.Location,
137 "The operator `{0}' requires a matching operator `{1}' to also be defined",
138 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
141 if (has_equality_or_inequality && Report.WarningLevel > 2) {
142 if (container.Methods == null || !container.HasEquals)
143 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
145 if (container.Methods == null || !container.HasGetHashCode)
146 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
150 public override void DefineContainerMembers ()
152 base.DefineContainerMembers ();
153 CheckPairedOperators ();
158 // Different context is needed when resolving type container base
159 // types. Type names come from the parent scope but type parameter
160 // names from the container scope.
162 struct BaseContext : IResolveContext
166 public BaseContext (TypeContainer tc)
171 #region IResolveContext Members
173 public Type CurrentType {
174 get { return tc.Parent.CurrentType; }
177 public TypeParameter[] CurrentTypeParameters {
178 get { return tc.PartialContainer.CurrentTypeParameters; }
181 public TypeContainer CurrentTypeDefinition {
182 get { return tc.Parent.CurrentTypeDefinition; }
185 public DeclSpace DeclContainer {
186 get { return tc.Parent; }
189 public bool IsInObsoleteScope {
190 get { return tc.IsInObsoleteScope; }
193 public bool IsInUnsafeScope {
194 get { return tc.IsInUnsafeScope; }
197 public bool IsStatic {
198 get { return tc.IsStatic; }
201 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
206 public FullNamedExpression LookupNamespaceAlias (string name)
208 return tc.Parent.LookupNamespaceAlias (name);
211 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
213 TypeParameter[] tp = CurrentTypeParameters;
215 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
217 return new TypeParameterExpr (t, loc);
220 return tc.Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
230 GetHashCode = 1 << 1,
231 HasStaticFieldInitializer = 1 << 2
235 // Whether this is a struct, class or interface
236 public readonly Kind Kind;
238 // Holds a list of classes and structures
239 protected ArrayList types;
241 MemberCoreArrayList ordered_explicit_member_list;
242 MemberCoreArrayList ordered_member_list;
244 // Holds the list of properties
245 MemberCoreArrayList properties;
247 // Holds the list of delegates
248 MemberCoreArrayList delegates;
250 // Holds the list of constructors
251 protected MemberCoreArrayList instance_constructors;
253 // Holds the list of fields
254 protected MemberCoreArrayList fields;
256 // Holds a list of fields that have initializers
257 protected ArrayList initialized_fields;
259 // Holds a list of static fields that have initializers
260 protected ArrayList initialized_static_fields;
262 // Holds the list of constants
263 protected MemberCoreArrayList constants;
265 // Holds the methods.
266 MemberCoreArrayList methods;
269 protected MemberCoreArrayList events;
271 // Holds the indexers
274 // Holds the operators
275 MemberCoreArrayList operators;
277 // Holds the compiler generated classes
278 ArrayList compiler_generated;
281 // Pointers to the default constructor and the default static constructor
283 protected Constructor default_constructor;
284 protected Constructor default_static_constructor;
287 // Points to the first non-static field added to the container.
289 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
290 // and the first one's as good as any.
292 FieldBase first_nonstatic_field = null;
295 // This one is computed after we can distinguish interfaces
296 // from classes from the arraylist `type_bases'
299 TypeExpr[] iface_exprs;
301 GenericTypeParameterBuilder[] nested_gen_params;
303 protected ArrayList type_bases;
305 protected bool members_defined;
306 bool members_defined_ok;
308 // The interfaces we implement.
309 protected Type[] ifaces;
311 // The base member cache and our member cache
312 MemberCache base_cache;
313 protected MemberCache member_cache;
315 public const string DefaultIndexerName = "Item";
317 private bool seen_normal_indexers = false;
318 private string indexer_name = DefaultIndexerName;
319 protected bool requires_delayed_unmanagedtype_check;
321 private CachedMethods cached_method;
323 ArrayList partial_parts;
326 /// The pending methods that need to be implemented
327 // (interfaces or abstract methods)
329 PendingImplementation pending;
331 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
332 Attributes attrs, Kind kind)
333 : base (ns, parent, name, attrs)
335 if (parent != null && parent.NamespaceEntry != ns)
336 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
339 this.PartialContainer = this;
342 public bool AddMember (MemberCore symbol)
344 return AddToContainer (symbol, symbol.MemberName.Basename);
347 protected virtual bool AddMemberType (DeclSpace ds)
349 return AddToContainer (ds, ds.Basename);
352 protected virtual void RemoveMemberType (DeclSpace ds)
354 RemoveFromContainer (ds.Basename);
357 public void AddConstant (Const constant)
359 if (!AddMember (constant))
362 if (constants == null)
363 constants = new MemberCoreArrayList ();
365 constants.Add (constant);
368 public TypeContainer AddTypeContainer (TypeContainer tc)
370 if (!AddMemberType (tc))
374 types = new MemberCoreArrayList ();
380 public virtual TypeContainer AddPartial (TypeContainer next_part)
382 return AddPartial (next_part, next_part.Basename);
385 protected TypeContainer AddPartial (TypeContainer next_part, string name)
387 next_part.ModFlags |= Modifiers.PARTIAL;
388 TypeContainer tc = defined_names [name] as TypeContainer;
391 return AddTypeContainer (next_part);
393 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
394 Report.SymbolRelatedToPreviousError (next_part);
395 Error_MissingPartialModifier (tc);
398 if (tc.Kind != next_part.Kind) {
399 Report.SymbolRelatedToPreviousError (tc);
400 Report.Error (261, next_part.Location,
401 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
402 next_part.GetSignatureForError ());
405 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
406 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
407 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
408 Report.SymbolRelatedToPreviousError (tc);
409 Report.Error (262, next_part.Location,
410 "Partial declarations of `{0}' have conflicting accessibility modifiers",
411 next_part.GetSignatureForError ());
414 if (tc.partial_parts == null)
415 tc.partial_parts = new ArrayList (1);
417 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
418 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
419 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
420 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
421 tc.ModFlags |= next_part.ModFlags;
423 tc.ModFlags |= next_part.ModFlags;
426 if (next_part.attributes != null) {
427 if (tc.attributes == null)
428 tc.attributes = next_part.attributes;
430 tc.attributes.AddAttributes (next_part.attributes.Attrs);
433 next_part.PartialContainer = tc;
434 tc.partial_parts.Add (next_part);
438 public virtual void RemoveTypeContainer (TypeContainer next_part)
441 types.Remove (next_part);
442 RemoveMemberType (next_part);
445 public void AddDelegate (Delegate d)
447 if (!AddMemberType (d))
450 if (delegates == null)
451 delegates = new MemberCoreArrayList ();
456 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
458 if (ordered_explicit_member_list == null) {
459 ordered_explicit_member_list = new MemberCoreArrayList ();
460 ordered_member_list = new MemberCoreArrayList ();
464 if (Kind == Kind.Interface) {
465 Report.Error (541, mc.Location,
466 "`{0}': explicit interface declaration can only be declared in a class or struct",
467 mc.GetSignatureForError ());
470 ordered_explicit_member_list.Add (mc);
471 alist.Insert (0, mc);
473 ordered_member_list.Add (mc);
479 public void AddMethod (MethodOrOperator method)
481 if (!AddToContainer (method, method.MemberName.Basename))
485 methods = new MemberCoreArrayList ();
487 if (method.MemberName.Left != null)
488 AddMemberToList (method, methods, true);
490 AddMemberToList (method, methods, false);
493 public void AddConstructor (Constructor c)
495 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
496 if (!AddToContainer (c, is_static ?
497 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
500 if (is_static && c.Parameters.IsEmpty){
501 if (default_static_constructor != null) {
502 Report.SymbolRelatedToPreviousError (default_static_constructor);
503 Report.Error (111, c.Location,
504 "A member `{0}' is already defined. Rename this member or use different parameter types",
505 c.GetSignatureForError ());
509 default_static_constructor = c;
511 if (c.Parameters.IsEmpty)
512 default_constructor = c;
514 if (instance_constructors == null)
515 instance_constructors = new MemberCoreArrayList ();
517 instance_constructors.Add (c);
521 public bool AddField (FieldBase field)
523 if (!AddMember (field))
527 fields = new MemberCoreArrayList ();
531 if ((field.ModFlags & Modifiers.STATIC) != 0)
534 if (first_nonstatic_field == null) {
535 first_nonstatic_field = field;
539 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
540 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
541 Report.Warning (282, 3, field.Location,
542 "struct instance field `{0}' found in different declaration from instance field `{1}'",
543 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
548 public void AddProperty (Property prop)
550 if (!AddMember (prop) ||
551 !AddMember (prop.Get) || !AddMember (prop.Set))
554 if (properties == null)
555 properties = new MemberCoreArrayList ();
557 if (prop.MemberName.Left != null)
558 AddMemberToList (prop, properties, true);
560 AddMemberToList (prop, properties, false);
563 public void AddEvent (Event e)
568 if (e is EventProperty) {
569 if (!AddMember (e.Add))
572 if (!AddMember (e.Remove))
577 events = new MemberCoreArrayList ();
583 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
585 public void AddIndexer (Indexer i)
587 if (indexers == null)
588 indexers = new ArrayList ();
590 if (i.IsExplicitImpl)
591 AddMemberToList (i, indexers, true);
593 AddMemberToList (i, indexers, false);
596 public void AddOperator (Operator op)
601 if (operators == null)
602 operators = new OperatorArrayList (this);
607 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
609 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
611 if (compiler_generated == null)
612 compiler_generated = new ArrayList ();
614 compiler_generated.Add (c);
617 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
619 if (a.Type == pa.DefaultMember) {
620 if (Indexers != null) {
621 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
626 base.ApplyAttributeBuilder (a, cb, pa);
629 public override AttributeTargets AttributeTargets {
631 throw new NotSupportedException ();
635 public ArrayList Types {
641 public MemberCoreArrayList Methods {
647 public ArrayList Constants {
653 protected Type BaseType {
655 return TypeBuilder.BaseType;
659 public ArrayList Fields {
665 public ArrayList InstanceConstructors {
667 return instance_constructors;
671 public ArrayList Properties {
677 public ArrayList Events {
683 public ArrayList Indexers {
689 public ArrayList Operators {
695 public ArrayList Delegates {
701 protected override TypeAttributes TypeAttr {
703 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
707 public string IndexerName {
709 return indexers == null ? DefaultIndexerName : indexer_name;
713 public bool IsComImport {
715 if (OptAttributes == null)
718 return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
722 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
724 if ((field.ModFlags & Modifiers.STATIC) != 0){
725 if (initialized_static_fields == null) {
726 PartialContainer.HasStaticFieldInitializer = true;
727 initialized_static_fields = new ArrayList (4);
730 initialized_static_fields.Add (expression);
732 if (initialized_fields == null)
733 initialized_fields = new ArrayList (4);
735 initialized_fields.Add (expression);
739 public void ResolveFieldInitializers (BlockContext ec)
741 if (partial_parts != null) {
742 foreach (TypeContainer part in partial_parts) {
743 part.DoResolveFieldInitializers (ec);
746 DoResolveFieldInitializers (ec);
749 void DoResolveFieldInitializers (BlockContext ec)
752 if (initialized_static_fields == null)
755 bool has_complex_initializer = !RootContext.Optimize;
757 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
758 for (i = 0; i < initialized_static_fields.Count; ++i) {
759 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
760 ExpressionStatement s = fi.ResolveStatement (ec);
762 s = EmptyExpressionStatement.Instance;
763 } else if (fi.IsComplexInitializer) {
764 has_complex_initializer |= true;
770 for (i = 0; i < initialized_static_fields.Count; ++i) {
771 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
773 // Need special check to not optimize code like this
774 // static int a = b = 5;
777 if (!has_complex_initializer && fi.IsDefaultInitializer)
780 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
786 if (initialized_fields == null)
789 for (int i = 0; i < initialized_fields.Count; ++i) {
790 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
791 ExpressionStatement s = fi.ResolveStatement (ec);
796 // Field is re-initialized to its default value => removed
798 if (fi.IsDefaultInitializer && RootContext.Optimize)
801 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
805 public override string DocComment {
817 public PendingImplementation PendingImplementations {
818 get { return pending; }
821 public override bool GetClsCompliantAttributeValue ()
823 if (PartialContainer != this)
824 return PartialContainer.GetClsCompliantAttributeValue ();
826 return base.GetClsCompliantAttributeValue ();
829 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
831 // FIXME: get rid of partial_parts and store lists of bases of each part here
832 // assumed, not verified: 'part' is in 'partial_parts'
833 ((TypeContainer) part).type_bases = bases;
837 /// This function computes the Base class and also the
838 /// list of interfaces that the class or struct @c implements.
840 /// The return value is an array (might be null) of
841 /// interfaces implemented (as Types).
843 /// The @base_class argument is set to the base object or null
844 /// if this is `System.Object'.
846 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
849 if (type_bases == null)
852 int count = type_bases.Count;
853 TypeExpr [] ifaces = null;
854 IResolveContext base_context = new BaseContext (this);
855 for (int i = 0, j = 0; i < count; i++){
856 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
859 // Standard ResolveAsTypeTerminal cannot be used in this case because
860 // it does ObsoleteAttribute and constraint checks which require
861 // base type to be set
863 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (base_context, false);
864 if (fne_resolved == null)
867 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
868 if (fne_resolved is DynamicTypeExpr)
869 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
870 GetSignatureForError ());
872 base_class = fne_resolved;
877 ifaces = new TypeExpr [count - i];
879 if (fne_resolved.Type.IsInterface) {
880 for (int ii = 0; ii < j; ++ii) {
881 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
882 Report.Error (528, Location, "`{0}' is already listed in interface list",
883 fne_resolved.GetSignatureForError ());
888 if (Kind == Kind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
889 Report.Error (61, fne.Location,
890 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
891 fne_resolved.GetSignatureForError (), GetSignatureForError ());
894 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
895 if (Kind != Kind.Class) {
896 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
897 } else if (base_class != null)
898 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
899 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
901 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
902 GetSignatureForError (), fne_resolved.GetSignatureForError ());
906 ifaces [j++] = fne_resolved;
912 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
914 ArrayList ifaces = new ArrayList (0);
915 if (iface_exprs != null)
916 ifaces.AddRange (iface_exprs);
918 foreach (TypeContainer part in partial_parts) {
919 TypeExpr new_base_class;
920 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
921 if (new_base_class != TypeManager.system_object_expr) {
922 if (base_class == TypeManager.system_object_expr)
923 base_class = new_base_class;
925 if (new_base_class != null && !TypeManager.IsEqual (new_base_class.Type, base_class.Type)) {
926 Report.SymbolRelatedToPreviousError (base_class.Location, "");
927 Report.Error (263, part.Location,
928 "Partial declarations of `{0}' must not specify different base classes",
929 part.GetSignatureForError ());
936 if (new_ifaces == null)
939 foreach (TypeExpr iface in new_ifaces) {
940 if (ifaces.Contains (iface))
947 if (ifaces.Count == 0)
950 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
953 bool CheckGenericInterfaces (Type[] ifaces)
956 ArrayList already_checked = new ArrayList ();
958 for (int i = 0; i < ifaces.Length; i++) {
959 Type iface = ifaces [i];
960 foreach (Type t in already_checked) {
964 Type[] inferred = new Type [CountTypeParameters];
965 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
968 Report.Error (695, Location,
969 "`{0}' cannot implement both `{1}' and `{2}' " +
970 "because they may unify for some type parameter substitutions",
971 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
972 TypeManager.CSharpName (t));
976 already_checked.Add (iface);
985 bool CreateTypeBuilder ()
988 Type default_parent = null;
989 if (Kind == Kind.Struct)
990 default_parent = TypeManager.value_type;
991 else if (Kind == Kind.Enum)
992 default_parent = TypeManager.enum_type;
993 else if (Kind == Kind.Delegate)
994 default_parent = TypeManager.multicast_delegate_type;
997 // Sets .size to 1 for structs with no instance fields
999 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
1002 if (TypeManager.NamespaceClash (Name, Location)) {
1006 ModuleBuilder builder = Module.Builder;
1007 TypeBuilder = builder.DefineType (
1008 Name, TypeAttr, default_parent, type_size);
1010 TypeBuilder builder = Parent.TypeBuilder;
1012 TypeBuilder = builder.DefineNestedType (
1013 Basename, TypeAttr, default_parent, type_size);
1015 } catch (ArgumentException) {
1016 Report.RuntimeMissingSupport (Location, "static classes");
1020 TypeManager.AddUserType (this);
1023 string[] param_names = new string [TypeParameters.Length];
1024 for (int i = 0; i < TypeParameters.Length; i++)
1025 param_names [i] = TypeParameters [i].Name;
1028 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
1030 int offset = CountTypeParameters;
1031 if (CurrentTypeParameters != null)
1032 offset -= CurrentTypeParameters.Length;
1035 nested_gen_params = new GenericTypeParameterBuilder [offset];
1036 Array.Copy (gen_params, nested_gen_params, offset);
1039 for (int i = offset; i < gen_params.Length; i++)
1040 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1042 nested_gen_params = null;
1043 throw new NotSupportedException ();
1050 bool DefineBaseTypes ()
1052 iface_exprs = ResolveBaseTypes (out base_type);
1053 if (partial_parts != null) {
1054 iface_exprs = GetNormalPartialBases (ref base_type);
1058 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1059 // which in turn should have called DefineType()s on base types if necessary.
1061 // None of the code below should trigger DefineType()s on classes that we depend on.
1062 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1064 // Let's do it as soon as possible, since code below can call DefineType() on classes
1065 // that depend on us to be populated before they are.
1067 if (!(this is CompilerGeneratedClass) && !(this is Delegate))
1068 RootContext.RegisterOrder (this);
1070 if (!CheckRecursiveDefinition (this))
1073 if (base_type != null && base_type.Type != null) {
1074 TypeBuilder.SetParent (base_type.Type);
1077 // add interfaces that were not added at type creation
1078 if (iface_exprs != null) {
1079 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1083 foreach (Type itype in ifaces)
1084 TypeBuilder.AddInterfaceImplementation (itype);
1086 if (!CheckGenericInterfaces (ifaces))
1089 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1096 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1098 public TypeBuilder CreateType ()
1100 if (TypeBuilder != null)
1106 if (!CreateTypeBuilder ()) {
1111 if (partial_parts != null) {
1112 foreach (TypeContainer part in partial_parts)
1113 part.TypeBuilder = TypeBuilder;
1116 if (Types != null) {
1117 foreach (TypeContainer tc in Types) {
1118 if (tc.CreateType () == null) {
1130 public override TypeBuilder DefineType ()
1137 type_defined = true;
1139 if (CreateType () == null) {
1144 if (!DefineBaseTypes ()) {
1149 if (!DefineNestedTypes ()) {
1157 public override void SetParameterInfo (ArrayList constraints_list)
1159 base.SetParameterInfo (constraints_list);
1161 if (!is_generic || PartialContainer == this)
1164 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1165 for (int i = 0; i < tc_names.Length; ++i) {
1166 if (tc_names [i].Name != type_params [i].Name) {
1167 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1168 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1169 GetSignatureForError ());
1175 void UpdateTypeParameterConstraints (TypeContainer part)
1177 TypeParameter[] current_params = type_params;
1178 for (int i = 0; i < current_params.Length; i++) {
1179 Constraints c = part.type_params [i].Constraints;
1183 if (current_params [i].UpdateConstraints (part, c))
1186 Report.SymbolRelatedToPreviousError (Location, "");
1187 Report.Error (265, part.Location,
1188 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1189 GetSignatureForError (), current_params [i].GetSignatureForError ());
1193 public bool ResolveType ()
1195 if (!DoResolveType ())
1198 if (compiler_generated != null) {
1199 foreach (CompilerGeneratedClass c in compiler_generated)
1200 if (!c.ResolveType ())
1207 protected virtual bool DoResolveType ()
1212 if (PartialContainer != this)
1213 throw new InternalErrorException ();
1215 TypeExpr current_type = null;
1216 if (CurrentTypeParameters != null) {
1217 foreach (TypeParameter type_param in CurrentTypeParameters) {
1218 if (!type_param.Resolve (this)) {
1224 if (partial_parts != null) {
1225 foreach (TypeContainer part in partial_parts)
1226 UpdateTypeParameterConstraints (part);
1230 for (int i = 0; i < TypeParameters.Length; ++i) {
1232 // FIXME: Same should be done for delegates
1233 // TODO: Quite ugly way how to propagate constraints to
1236 if (nested_gen_params != null && i < nested_gen_params.Length) {
1237 TypeParameters [i].SetConstraints (nested_gen_params [i]);
1239 if (!TypeParameters [i].DefineType (this)) {
1246 // TODO: Very strange, why not simple make generic type from
1247 // current type parameters
1248 current_type = new GenericTypeExpr (this, Location);
1249 current_type = current_type.ResolveAsTypeTerminal (this, false);
1250 if (current_type == null) {
1255 currentType = current_type.Type;
1259 protected virtual bool DefineNestedTypes ()
1261 if (Types != null) {
1262 foreach (TypeContainer tc in Types)
1263 if (tc.DefineType () == null)
1267 if (Delegates != null) {
1268 foreach (Delegate d in Delegates)
1269 if (d.DefineType () == null)
1276 TypeContainer InTransit;
1278 protected bool CheckRecursiveDefinition (TypeContainer tc)
1280 if (InTransit != null) {
1281 Report.SymbolRelatedToPreviousError (this);
1282 if (this is Interface)
1284 529, tc.Location, "Inherited interface `{0}' causes a " +
1285 "cycle in the interface hierarchy of `{1}'",
1286 GetSignatureForError (), tc.GetSignatureForError ());
1289 146, tc.Location, "Circular base class dependency " +
1290 "involving `{0}' and `{1}'",
1291 tc.GetSignatureForError (), GetSignatureForError ());
1297 if (base_type != null && base_type.Type != null) {
1298 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1299 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1300 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1304 if (iface_exprs != null) {
1305 foreach (TypeExpr iface in iface_exprs) {
1306 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1307 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1308 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1313 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1320 public override TypeParameter[] CurrentTypeParameters {
1322 return PartialContainer.type_params;
1327 /// Populates our TypeBuilder with fields and methods
1329 public override bool Define ()
1331 if (members_defined)
1332 return members_defined_ok;
1334 members_defined_ok = DoDefineMembers ();
1335 members_defined = true;
1337 return members_defined_ok;
1340 protected virtual bool DoDefineMembers ()
1342 if (iface_exprs != null) {
1343 foreach (TypeExpr iface in iface_exprs) {
1344 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1345 if ((oa != null) && !IsInObsoleteScope)
1346 AttributeTester.Report_ObsoleteMessage (
1347 oa, iface.GetSignatureForError (), Location);
1349 GenericTypeExpr ct = iface as GenericTypeExpr;
1351 // TODO: passing `this' is wrong, should be base type iface instead
1352 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1354 if (!ct.CheckConstraints (this))
1360 if (base_type != null) {
1361 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1362 if (obsolete_attr != null && !IsInObsoleteScope)
1363 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1365 GenericTypeExpr ct = base_type as GenericTypeExpr;
1366 if ((ct != null) && !ct.CheckConstraints (this))
1369 TypeContainer baseContainer = TypeManager.LookupTypeContainer(base_type.Type);
1370 if (baseContainer != null)
1371 baseContainer.Define();
1373 member_cache = new MemberCache (base_type.Type, this);
1374 } else if (Kind == Kind.Interface) {
1375 member_cache = new MemberCache (null, this);
1376 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1377 for (int i = 0; i < ifaces.Length; ++i)
1378 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1380 member_cache = new MemberCache (null, this);
1384 foreach (TypeContainer tc in types)
1385 member_cache.AddNestedType (tc);
1387 if (delegates != null)
1388 foreach (Delegate d in delegates)
1389 member_cache.AddNestedType (d);
1391 if (partial_parts != null) {
1392 foreach (TypeContainer part in partial_parts)
1393 part.member_cache = member_cache;
1397 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1398 if (conflict_symbol == null) {
1399 if ((ModFlags & Modifiers.NEW) != 0)
1400 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1402 if ((ModFlags & Modifiers.NEW) == 0) {
1403 Report.SymbolRelatedToPreviousError (conflict_symbol);
1404 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1405 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1410 DefineContainerMembers (constants);
1411 DefineContainerMembers (fields);
1413 if (Kind == Kind.Struct || Kind == Kind.Class) {
1414 pending = PendingImplementation.GetPendingImplementations (this);
1416 if (requires_delayed_unmanagedtype_check) {
1417 requires_delayed_unmanagedtype_check = false;
1418 foreach (FieldBase f in fields) {
1419 if (f.MemberType != null && f.MemberType.IsPointer)
1420 TypeManager.VerifyUnManaged (f.MemberType, f.Location);
1426 // Constructors are not in the defined_names array
1428 DefineContainerMembers (instance_constructors);
1430 DefineContainerMembers (events);
1431 DefineContainerMembers (ordered_explicit_member_list);
1432 DefineContainerMembers (ordered_member_list);
1434 DefineContainerMembers (operators);
1435 DefineContainerMembers (delegates);
1437 ComputeIndexerName();
1438 CheckEqualsAndGetHashCode();
1440 if (CurrentType != null) {
1441 GenericType = CurrentType;
1445 // FIXME: This hack is needed because member cache does not work
1446 // with generic types, we rely on runtime to inflate dynamic types.
1447 // TODO: This hack requires member cache refactoring to be removed
1449 if (TypeManager.IsGenericType (TypeBuilder))
1450 member_cache = new MemberCache (this);
1455 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1458 mcal.DefineContainerMembers ();
1461 protected virtual void ComputeIndexerName ()
1463 if (indexers == null)
1466 string class_indexer_name = null;
1469 // If there's both an explicit and an implicit interface implementation, the
1470 // explicit one actually implements the interface while the other one is just
1471 // a normal indexer. See bug #37714.
1474 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1475 foreach (Indexer i in indexers) {
1476 if (i.InterfaceType != null) {
1477 if (seen_normal_indexers)
1478 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1482 seen_normal_indexers = true;
1484 if (class_indexer_name == null) {
1485 class_indexer_name = i.ShortName;
1489 if (i.ShortName != class_indexer_name)
1490 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");
1493 if (class_indexer_name != null)
1494 indexer_name = class_indexer_name;
1497 protected virtual void EmitIndexerName ()
1499 if (!seen_normal_indexers)
1502 PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1503 if (pa.Constructor == null &&
1504 !pa.ResolveConstructor (Location, TypeManager.string_type))
1507 CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { IndexerName });
1508 TypeBuilder.SetCustomAttribute (cb);
1511 protected virtual void CheckEqualsAndGetHashCode ()
1513 if (methods == null)
1516 if (HasEquals && !HasGetHashCode) {
1517 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1521 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1523 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1527 /// This function is based by a delegate to the FindMembers routine
1529 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1535 /// This filter is used by FindMembers, and we just keep
1536 /// a global for the filter to `AlwaysAccept'
1538 static MemberFilter accepting_filter;
1541 static TypeContainer ()
1543 accepting_filter = new MemberFilter (AlwaysAccept);
1546 public MethodInfo[] GetMethods ()
1548 ArrayList members = new ArrayList ();
1552 if (methods != null) {
1553 int len = methods.Count;
1554 for (int i = 0; i < len; i++) {
1555 Method m = (Method) methods [i];
1557 members.Add (m.MethodBuilder);
1561 if (operators != null) {
1562 int len = operators.Count;
1563 for (int i = 0; i < len; i++) {
1564 Operator o = (Operator) operators [i];
1566 members.Add (o.MethodBuilder);
1570 if (properties != null) {
1571 int len = properties.Count;
1572 for (int i = 0; i < len; i++) {
1573 Property p = (Property) properties [i];
1575 if (p.GetBuilder != null)
1576 members.Add (p.GetBuilder);
1577 if (p.SetBuilder != null)
1578 members.Add (p.SetBuilder);
1582 if (indexers != null) {
1583 int len = indexers.Count;
1584 for (int i = 0; i < len; i++) {
1585 Indexer ix = (Indexer) indexers [i];
1587 if (ix.GetBuilder != null)
1588 members.Add (ix.GetBuilder);
1589 if (ix.SetBuilder != null)
1590 members.Add (ix.SetBuilder);
1594 if (events != null) {
1595 int len = events.Count;
1596 for (int i = 0; i < len; i++) {
1597 Event e = (Event) events [i];
1599 if (e.AddBuilder != null)
1600 members.Add (e.AddBuilder);
1601 if (e.RemoveBuilder != null)
1602 members.Add (e.RemoveBuilder);
1606 MethodInfo[] retMethods = new MethodInfo [members.Count];
1607 members.CopyTo (retMethods, 0);
1611 // Indicated whether container has StructLayout attribute set Explicit
1612 public bool HasExplicitLayout {
1613 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1614 set { caching_flags |= Flags.HasExplicitLayout; }
1617 public bool HasStructLayout {
1618 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1619 set { caching_flags |= Flags.HasStructLayout; }
1623 // Return the nested type with name @name. Ensures that the nested type
1624 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1626 public Type FindNestedType (string name)
1628 if (PartialContainer != this)
1629 throw new InternalErrorException ("should not happen");
1631 ArrayList [] lists = { types, delegates };
1633 for (int j = 0; j < lists.Length; ++j) {
1634 ArrayList list = lists [j];
1638 int len = list.Count;
1639 for (int i = 0; i < len; ++i) {
1640 DeclSpace ds = (DeclSpace) list [i];
1641 if (ds.Basename == name) {
1642 return ds.DefineType ();
1650 private void FindMembers_NestedTypes (int modflags,
1651 BindingFlags bf, MemberFilter filter, object criteria,
1652 ref ArrayList members)
1654 ArrayList [] lists = { types, delegates };
1656 for (int j = 0; j < lists.Length; ++j) {
1657 ArrayList list = lists [j];
1661 int len = list.Count;
1662 for (int i = 0; i < len; i++) {
1663 DeclSpace ds = (DeclSpace) list [i];
1665 if ((ds.ModFlags & modflags) == 0)
1668 TypeBuilder tb = ds.TypeBuilder;
1670 if (!(criteria is string) || ds.Basename.Equals (criteria))
1671 tb = ds.DefineType ();
1674 if (tb != null && (filter (tb, criteria) == true)) {
1675 if (members == null)
1676 members = new ArrayList ();
1685 /// This method returns the members of this type just like Type.FindMembers would
1686 /// Only, we need to use this for types which are _being_ defined because MS'
1687 /// implementation can't take care of that.
1690 // FIXME: return an empty static array instead of null, that cleans up
1691 // some code and is consistent with some coding conventions I just found
1695 // Notice that in various cases we check if our field is non-null,
1696 // something that would normally mean that there was a bug elsewhere.
1698 // The problem happens while we are defining p-invoke methods, as those
1699 // will trigger a FindMembers, but this happens before things are defined
1701 // Since the whole process is a no-op, it is fine to check for null here.
1703 // TODO: This approach will be one day completely removed, it's already
1704 // used at few places only
1707 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1708 MemberFilter filter, object criteria)
1710 ArrayList members = null;
1713 if ((bf & BindingFlags.Public) != 0)
1714 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1716 if ((bf & BindingFlags.NonPublic) != 0)
1717 modflags |= Modifiers.PRIVATE;
1719 int static_mask = 0, static_flags = 0;
1720 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1721 case BindingFlags.Static:
1722 static_mask = static_flags = Modifiers.STATIC;
1725 case BindingFlags.Instance:
1726 static_mask = Modifiers.STATIC;
1731 static_mask = static_flags = 0;
1735 Timer.StartTimer (TimerType.TcFindMembers);
1738 filter = accepting_filter;
1740 if ((mt & MemberTypes.Field) != 0) {
1741 if (fields != null) {
1742 int len = fields.Count;
1743 for (int i = 0; i < len; i++) {
1744 FieldBase f = (FieldBase) fields [i];
1746 if ((f.ModFlags & modflags) == 0)
1748 if ((f.ModFlags & static_mask) != static_flags)
1751 FieldBuilder fb = f.FieldBuilder;
1752 if (fb != null && filter (fb, criteria) == true) {
1753 if (members == null)
1754 members = new ArrayList ();
1761 if (constants != null) {
1762 int len = constants.Count;
1763 for (int i = 0; i < len; i++) {
1764 Const con = (Const) constants [i];
1766 if ((con.ModFlags & modflags) == 0)
1768 if ((con.ModFlags & static_mask) != static_flags)
1771 FieldBuilder fb = con.FieldBuilder;
1774 fb = con.FieldBuilder;
1776 if (fb != null && filter (fb, criteria) == true) {
1777 if (members == null)
1778 members = new ArrayList ();
1786 if ((mt & MemberTypes.Method) != 0) {
1787 if (methods != null) {
1788 int len = methods.Count;
1789 for (int i = 0; i < len; i++) {
1790 MethodOrOperator m = (MethodOrOperator) methods [i];
1792 if ((m.ModFlags & modflags) == 0)
1794 if ((m.ModFlags & static_mask) != static_flags)
1797 MethodBuilder mb = m.MethodBuilder;
1799 if (mb != null && filter (mb, criteria) == true) {
1800 if (members == null)
1801 members = new ArrayList ();
1808 if (operators != null) {
1809 int len = operators.Count;
1810 for (int i = 0; i < len; i++) {
1811 Operator o = (Operator) operators [i];
1813 if ((o.ModFlags & modflags) == 0)
1815 if ((o.ModFlags & static_mask) != static_flags)
1818 MethodBuilder ob = o.MethodBuilder;
1819 if (ob != null && filter (ob, criteria) == true) {
1820 if (members == null)
1821 members = new ArrayList ();
1828 if (events != null) {
1829 foreach (Event e in events) {
1830 if ((e.ModFlags & modflags) == 0)
1832 if ((e.ModFlags & static_mask) != static_flags)
1835 MethodBuilder b = e.AddBuilder;
1836 if (b != null && filter (b, criteria)) {
1837 if (members == null)
1838 members = new ArrayList (4);
1843 b = e.RemoveBuilder;
1844 if (b != null && filter (b, criteria)) {
1845 if (members == null)
1846 members = new ArrayList (4);
1853 if (properties != null) {
1854 int len = properties.Count;
1855 for (int i = 0; i < len; i++) {
1856 Property p = (Property) properties [i];
1858 if ((p.ModFlags & modflags) == 0)
1860 if ((p.ModFlags & static_mask) != static_flags)
1866 if (b != null && filter (b, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1874 if (b != null && filter (b, criteria) == true) {
1875 if (members == null)
1876 members = new ArrayList ();
1883 if (indexers != null) {
1884 int len = indexers.Count;
1885 for (int i = 0; i < len; i++) {
1886 Indexer ix = (Indexer) indexers [i];
1888 if ((ix.ModFlags & modflags) == 0)
1890 if ((ix.ModFlags & static_mask) != static_flags)
1896 if (b != null && filter (b, criteria) == true) {
1897 if (members == null)
1898 members = new ArrayList ();
1904 if (b != null && filter (b, criteria) == true) {
1905 if (members == null)
1906 members = new ArrayList ();
1914 if ((mt & MemberTypes.Event) != 0) {
1915 if (events != null) {
1916 int len = events.Count;
1917 for (int i = 0; i < len; i++) {
1918 Event e = (Event) events [i];
1920 if ((e.ModFlags & modflags) == 0)
1922 if ((e.ModFlags & static_mask) != static_flags)
1925 MemberInfo eb = e.EventBuilder;
1926 if (eb != null && filter (eb, criteria) == true) {
1927 if (members == null)
1928 members = new ArrayList ();
1930 members.Add (e.EventBuilder);
1936 if ((mt & MemberTypes.Property) != 0){
1937 if (properties != null) {
1938 int len = properties.Count;
1939 for (int i = 0; i < len; i++) {
1940 Property p = (Property) properties [i];
1942 if ((p.ModFlags & modflags) == 0)
1944 if ((p.ModFlags & static_mask) != static_flags)
1947 MemberInfo pb = p.PropertyBuilder;
1948 if (pb != null && filter (pb, criteria) == true) {
1949 if (members == null)
1950 members = new ArrayList ();
1952 members.Add (p.PropertyBuilder);
1957 if (indexers != null) {
1958 int len = indexers.Count;
1959 for (int i = 0; i < len; i++) {
1960 Indexer ix = (Indexer) indexers [i];
1962 if ((ix.ModFlags & modflags) == 0)
1964 if ((ix.ModFlags & static_mask) != static_flags)
1967 MemberInfo ib = ix.PropertyBuilder;
1968 if (ib != null && filter (ib, criteria) == true) {
1969 if (members == null)
1970 members = new ArrayList ();
1972 members.Add (ix.PropertyBuilder);
1978 if ((mt & MemberTypes.NestedType) != 0)
1979 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1981 if ((mt & MemberTypes.Constructor) != 0){
1982 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1983 int len = instance_constructors.Count;
1984 for (int i = 0; i < len; i++) {
1985 Constructor c = (Constructor) instance_constructors [i];
1987 ConstructorBuilder cb = c.ConstructorBuilder;
1988 if (cb != null && filter (cb, criteria) == true) {
1989 if (members == null)
1990 members = new ArrayList ();
1997 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1998 ConstructorBuilder cb =
1999 default_static_constructor.ConstructorBuilder;
2001 if (cb != null && filter (cb, criteria) == true) {
2002 if (members == null)
2003 members = new ArrayList ();
2011 // Lookup members in base if requested.
2013 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2014 if (TypeBuilder.BaseType != null) {
2015 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2016 if (list.Count > 0) {
2017 if (members == null)
2018 members = new ArrayList ();
2020 members.AddRange (list);
2025 Timer.StopTimer (TimerType.TcFindMembers);
2027 if (members == null)
2028 return MemberList.Empty;
2030 return new MemberList (members);
2033 public override MemberCache MemberCache {
2035 return member_cache;
2039 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2040 MemberFilter filter, object criteria)
2042 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2045 return ds.FindMembers (mt, bf, filter, criteria);
2047 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2051 /// Emits the values for the constants
2053 public void EmitConstants ()
2055 if (constants != null)
2056 foreach (Const con in constants)
2061 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2066 foreach (MemberCore mc in al) {
2067 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2070 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2071 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2076 public virtual void VerifyMembers ()
2079 // Check for internal or private fields that were never assigned
2081 if (Report.WarningLevel >= 3) {
2082 CheckMemberUsage (properties, "property");
2083 CheckMemberUsage (methods, "method");
2084 CheckMemberUsage (constants, "constant");
2086 if (fields != null){
2087 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2088 foreach (FieldBase f in fields) {
2089 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2090 if (is_type_exposed)
2093 f.SetMemberIsUsed ();
2097 if ((f.caching_flags & Flags.IsAssigned) == 0)
2098 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2101 const int error_code = 414;
2103 const int error_code = 169;
2105 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2106 f.GetSignatureForError ());
2112 // Only report 649 on level 4
2114 if (Report.WarningLevel < 4)
2117 if ((f.caching_flags & Flags.IsAssigned) != 0)
2121 // Don't be pendatic over serializable attributes
2123 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2126 Constant c = New.Constantify (f.MemberType);
2127 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2128 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2134 // TODO: move to ClassOrStruct
2135 void EmitConstructors ()
2137 if (instance_constructors == null)
2140 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2141 bool has_compliant_args = false;
2143 foreach (Constructor c in instance_constructors) {
2147 catch (Exception e) {
2148 throw new InternalErrorException (c, e);
2151 if (has_compliant_args)
2154 has_compliant_args = c.HasCompliantArgs;
2156 if (!has_compliant_args)
2157 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2159 foreach (Constructor c in instance_constructors) {
2163 catch (Exception e) {
2164 throw new InternalErrorException (c, e);
2171 /// Emits the code, this step is performed after all
2172 /// the types, enumerations, constructors
2174 public virtual void EmitType ()
2176 if (OptAttributes != null)
2177 OptAttributes.Emit ();
2181 EmitConstructors ();
2183 // Can not continue if constants are broken
2185 if (Report.Errors > 0)
2188 if (default_static_constructor != null)
2189 default_static_constructor.Emit ();
2191 if (operators != null)
2192 foreach (Operator o in operators)
2195 if (properties != null)
2196 foreach (Property p in properties)
2199 if (indexers != null) {
2200 foreach (Indexer indx in indexers)
2205 if (events != null){
2206 foreach (Event e in Events)
2210 if (methods != null) {
2211 for (int i = 0; i < methods.Count; ++i)
2212 ((MethodOrOperator) methods [i]).Emit ();
2216 foreach (FieldBase f in fields)
2219 if (delegates != null) {
2220 foreach (Delegate d in Delegates) {
2225 if (pending != null)
2226 pending.VerifyPendingMethods ();
2228 if (Report.Errors > 0)
2231 if (compiler_generated != null) {
2232 for (int i = 0; i < compiler_generated.Count; ++i)
2233 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2237 public override void CloseType ()
2239 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2243 caching_flags |= Flags.CloseTypeCreated;
2244 TypeBuilder.CreateType ();
2245 } catch (TypeLoadException){
2247 // This is fine, the code still created the type
2249 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2250 // Console.WriteLine (e.Message);
2251 } catch (Exception e) {
2252 throw new InternalErrorException (this, e);
2256 foreach (TypeContainer tc in Types)
2257 if (tc.Kind == Kind.Struct)
2260 foreach (TypeContainer tc in Types)
2261 if (tc.Kind != Kind.Struct)
2265 if (Delegates != null)
2266 foreach (Delegate d in Delegates)
2269 if (compiler_generated != null)
2270 foreach (CompilerGeneratedClass c in compiler_generated)
2273 PartialContainer = null;
2278 initialized_fields = null;
2279 initialized_static_fields = null;
2281 ordered_explicit_member_list = null;
2282 ordered_member_list = null;
2287 compiler_generated = null;
2288 default_constructor = null;
2289 default_static_constructor = null;
2291 OptAttributes = null;
2294 member_cache = null;
2298 // Performs the validation on a Method's modifiers (properties have
2299 // the same properties).
2301 public bool MethodModifiersValid (MemberCore mc)
2303 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2304 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2305 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2307 int flags = mc.ModFlags;
2310 // At most one of static, virtual or override
2312 if ((flags & Modifiers.STATIC) != 0){
2313 if ((flags & vao) != 0){
2314 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2315 mc.GetSignatureForError ());
2320 if (Kind == Kind.Struct){
2321 if ((flags & va) != 0){
2322 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2327 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2328 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2329 mc.GetSignatureForError ());
2334 // If the declaration includes the abstract modifier, then the
2335 // declaration does not include static, virtual or extern
2337 if ((flags & Modifiers.ABSTRACT) != 0){
2338 if ((flags & Modifiers.EXTERN) != 0){
2340 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2344 if ((flags & Modifiers.SEALED) != 0) {
2345 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2349 if ((flags & Modifiers.VIRTUAL) != 0){
2350 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2354 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2355 Report.SymbolRelatedToPreviousError (this);
2356 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2357 mc.GetSignatureForError (), GetSignatureForError ());
2362 if ((flags & Modifiers.PRIVATE) != 0){
2363 if ((flags & vao) != 0){
2364 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2369 if ((flags & Modifiers.SEALED) != 0){
2370 if ((flags & Modifiers.OVERRIDE) == 0){
2371 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2379 public Constructor DefaultStaticConstructor {
2380 get { return default_static_constructor; }
2383 protected override bool VerifyClsCompliance ()
2385 if (!base.VerifyClsCompliance ())
2390 Type base_type = TypeBuilder.BaseType;
2391 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2392 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2399 /// Checks whether container name is CLS Compliant
2401 void VerifyClsName ()
2403 Hashtable base_members = base_cache == null ?
2405 base_cache.GetPublicMembers ();
2406 Hashtable this_members = new Hashtable ();
2408 foreach (DictionaryEntry entry in defined_names) {
2409 MemberCore mc = (MemberCore)entry.Value;
2410 if (!mc.IsClsComplianceRequired ())
2413 string name = (string) entry.Key;
2414 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2416 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2417 object found = base_members [lcase];
2418 if (found == null) {
2419 found = this_members [lcase];
2420 if (found == null) {
2421 this_members.Add (lcase, mc);
2426 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2429 if (found is MemberInfo) {
2430 if (basename == ((MemberInfo) found).Name)
2432 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2434 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2437 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2443 /// Performs checks for an explicit interface implementation. First it
2444 /// checks whether the `interface_type' is a base inteface implementation.
2445 /// Then it checks whether `name' exists in the interface type.
2447 public bool VerifyImplements (InterfaceMemberBase mb)
2449 if (ifaces != null) {
2450 foreach (Type t in ifaces){
2451 if (TypeManager.IsEqual (t, mb.InterfaceType))
2456 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2457 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2458 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2462 public override Type LookupAnyGeneric (string typeName)
2464 if (types != null) {
2465 foreach (TypeContainer tc in types) {
2469 int pos = tc.Basename.LastIndexOf ('`');
2470 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2471 return tc.TypeBuilder;
2475 return base.LookupAnyGeneric (typeName);
2478 public void Mark_HasEquals ()
2480 cached_method |= CachedMethods.Equals;
2483 public void Mark_HasGetHashCode ()
2485 cached_method |= CachedMethods.GetHashCode;
2489 /// Method container contains Equals method
2491 public bool HasEquals {
2493 return (cached_method & CachedMethods.Equals) != 0;
2498 /// Method container contains GetHashCode method
2500 public bool HasGetHashCode {
2502 return (cached_method & CachedMethods.GetHashCode) != 0;
2506 public bool HasStaticFieldInitializer {
2508 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2512 cached_method |= CachedMethods.HasStaticFieldInitializer;
2514 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2522 string IMemberContainer.Name {
2528 Type IMemberContainer.Type {
2534 bool IMemberContainer.IsInterface {
2536 return Kind == Kind.Interface;
2540 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2542 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2544 if (GenericType != null)
2545 return TypeManager.FindMembers (GenericType, mt, new_bf,
2548 return FindMembers (mt, new_bf, null, null);
2552 // Generates xml doc comments (if any), and if required,
2553 // handle warning report.
2555 internal override void GenerateDocComment (DeclSpace ds)
2557 DocUtil.GenerateTypeDocComment (this, ds);
2560 public override string DocCommentHeader {
2561 get { return "T:"; }
2564 public MemberCache BaseCache {
2566 if (base_cache != null)
2568 if (TypeBuilder.BaseType != null)
2569 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2570 if (TypeBuilder.IsInterface)
2571 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2577 public abstract class ClassOrStruct : TypeContainer {
2578 ListDictionary declarative_security;
2580 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2581 MemberName name, Attributes attrs, Kind kind)
2582 : base (ns, parent, name, attrs, kind)
2586 protected override bool AddToContainer (MemberCore symbol, string name)
2588 if (name == MemberName.Name) {
2589 if (symbol is TypeParameter) {
2590 Report.Error (694, symbol.Location,
2591 "Type parameter `{0}' has same name as containing type, or method",
2592 symbol.GetSignatureForError ());
2596 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2597 if (imb == null || !imb.IsExplicitImpl) {
2598 Report.SymbolRelatedToPreviousError (this);
2599 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2600 symbol.GetSignatureForError ());
2605 return base.AddToContainer (symbol, name);
2608 public override void VerifyMembers ()
2610 base.VerifyMembers ();
2612 if ((events != null) && Report.WarningLevel >= 3) {
2613 foreach (Event e in events){
2614 // Note: The event can be assigned from same class only, so we can report
2615 // this warning for all accessibility modes
2616 if ((e.caching_flags & Flags.IsUsed) == 0)
2617 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2622 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
2624 if (a.IsValidSecurityAttribute ()) {
2625 if (declarative_security == null)
2626 declarative_security = new ListDictionary ();
2628 a.ExtractSecurityPermissionSet (declarative_security);
2632 if (a.Type == pa.StructLayout) {
2633 PartialContainer.HasStructLayout = true;
2635 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2636 PartialContainer.HasExplicitLayout = true;
2639 base.ApplyAttributeBuilder (a, cb, pa);
2643 /// Defines the default constructors
2645 protected void DefineDefaultConstructor (bool is_static)
2647 // The default instance constructor is public
2648 // If the class is abstract, the default constructor is protected
2649 // The default static constructor is private
2653 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2655 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2658 Constructor c = new Constructor (this, MemberName.Name, mods,
2659 null, ParametersCompiled.EmptyReadOnlyParameters,
2660 new GeneratedBaseInitializer (Location),
2664 c.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
2667 public override bool Define ()
2669 CheckProtectedModifier ();
2673 if (default_static_constructor != null)
2674 default_static_constructor.Define ();
2679 public override void Emit ()
2681 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2682 DefineDefaultConstructor (true);
2683 default_static_constructor.Define ();
2688 if (declarative_security != null) {
2689 foreach (DictionaryEntry de in declarative_security) {
2690 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2695 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2697 DeclSpace top_level = Parent;
2698 if (top_level != null) {
2699 while (top_level.Parent != null)
2700 top_level = top_level.Parent;
2702 ArrayList candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name);
2703 if (candidates != null)
2704 return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2707 return NamespaceEntry.LookupExtensionMethod (extensionType, name, loc);
2710 protected override TypeAttributes TypeAttr {
2712 if (default_static_constructor == null)
2713 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2715 return base.TypeAttr;
2721 // TODO: should be sealed
2722 public class Class : ClassOrStruct {
2723 const int AllowedModifiers =
2726 Modifiers.PROTECTED |
2727 Modifiers.INTERNAL |
2729 Modifiers.ABSTRACT |
2734 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2736 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2738 : base (ns, parent, name, attrs, Kind.Class)
2740 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2741 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2743 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2744 Report.FeatureIsNotAvailable (Location, "static classes");
2748 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2750 if (part.Name == "System.Object")
2751 Report.Error (537, part.Location,
2752 "The class System.Object cannot have a base class or implement an interface.");
2753 base.AddBasesForPart (part, bases);
2756 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
2758 if (a.Type == pa.AttributeUsage) {
2759 if (!TypeManager.IsAttributeType (BaseType) &&
2760 TypeBuilder.FullName != "System.Attribute") {
2761 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2765 if (a.Type == pa.Conditional && !TypeManager.IsAttributeType (BaseType)) {
2766 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2770 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2771 a.Error_MissingGuidAttribute ();
2775 if (a.Type == pa.Extension) {
2776 a.Error_MisusedExtensionAttribute ();
2780 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2783 base.ApplyAttributeBuilder (a, cb, pa);
2786 public override AttributeTargets AttributeTargets {
2788 return AttributeTargets.Class;
2792 protected override void DefineContainerMembers (MemberCoreArrayList list)
2798 base.DefineContainerMembers (list);
2802 foreach (MemberCore m in list) {
2803 if (m is Operator) {
2804 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2808 if (m is Destructor) {
2809 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2814 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2818 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2821 if (m is Constructor) {
2822 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2826 Method method = m as Method;
2827 if (method != null && method.Parameters.HasExtensionMethodType) {
2828 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2832 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2835 base.DefineContainerMembers (list);
2838 public override bool Define ()
2840 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2841 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2844 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2845 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2848 return base.Define ();
2851 protected override bool DoDefineMembers ()
2853 if (InstanceConstructors == null && !IsStatic)
2854 DefineDefaultConstructor (false);
2856 return base.DoDefineMembers ();
2859 public override void Emit ()
2863 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2864 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2867 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2869 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2871 if (base_class == null) {
2872 if (RootContext.StdLib)
2873 base_class = TypeManager.system_object_expr;
2874 else if (Name != "System.Object")
2875 base_class = TypeManager.system_object_expr;
2877 if (Kind == Kind.Class && TypeManager.IsGenericParameter (base_class.Type)){
2879 689, base_class.Location,
2880 "Cannot derive from `{0}' because it is a type parameter",
2881 base_class.GetSignatureForError ());
2885 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2886 Report.Error (698, base_class.Location,
2887 "A generic type cannot derive from `{0}' because it is an attribute class",
2888 base_class.GetSignatureForError ());
2891 if (base_class.IsSealed){
2892 Report.SymbolRelatedToPreviousError (base_class.Type);
2893 if (base_class.Type.IsAbstract) {
2894 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2895 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2897 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2898 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2903 if (!base_class.CanInheritFrom ()){
2904 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2905 GetSignatureForError (), base_class.GetSignatureForError ());
2909 if (!IsAccessibleAs (base_class.Type)) {
2910 Report.SymbolRelatedToPreviousError (base_class.Type);
2911 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2912 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2916 if (PartialContainer.IsStaticClass) {
2917 if (base_class.Type != TypeManager.object_type) {
2918 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2919 GetSignatureForError (), base_class.GetSignatureForError ());
2923 if (ifaces != null) {
2924 foreach (TypeExpr t in ifaces)
2925 Report.SymbolRelatedToPreviousError (t.Type);
2926 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2933 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2934 /// Valid only for attribute classes.
2935 public bool IsExcluded ()
2937 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2938 return (caching_flags & Flags.Excluded) != 0;
2940 caching_flags &= ~Flags.Excluded_Undetected;
2942 if (OptAttributes == null)
2945 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2949 foreach (Attribute a in attrs) {
2950 string condition = a.GetConditionalAttributeValue ();
2951 if (Location.CompilationUnit.IsConditionalDefined (condition))
2955 caching_flags |= Flags.Excluded;
2960 // FIXME: How do we deal with the user specifying a different
2963 protected override TypeAttributes TypeAttr {
2965 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2967 ta |= StaticClassAttribute;
2973 public sealed class Struct : ClassOrStruct {
2975 bool is_unmanaged, has_unmanaged_check_done;
2978 // Modifiers allowed in a struct declaration
2980 const int AllowedModifiers =
2983 Modifiers.PROTECTED |
2984 Modifiers.INTERNAL |
2988 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2989 int mod, Attributes attrs)
2990 : base (ns, parent, name, attrs, Kind.Struct)
2994 if (parent.Parent == null)
2995 accmods = Modifiers.INTERNAL;
2997 accmods = Modifiers.PRIVATE;
2999 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3001 this.ModFlags |= Modifiers.SEALED;
3004 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
3006 base.ApplyAttributeBuilder (a, cb, pa);
3009 // When struct constains fixed fixed and struct layout has explicitly
3010 // set CharSet, its value has to be propagated to compiler generated
3011 // fixed field types
3013 if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
3014 for (int i = 0; i < Fields.Count; ++i) {
3015 FixedField ff = Fields [i] as FixedField;
3017 ff.SetCharSet (TypeBuilder.Attributes);
3022 public override AttributeTargets AttributeTargets {
3024 return AttributeTargets.Struct;
3028 public override bool IsUnmanagedType ()
3033 if (requires_delayed_unmanagedtype_check)
3036 if (has_unmanaged_check_done)
3037 return is_unmanaged;
3039 has_unmanaged_check_done = true;
3041 foreach (FieldBase f in fields) {
3042 if ((f.ModFlags & Modifiers.STATIC) != 0)
3045 // It can happen when recursive unmanaged types are defined
3046 // struct S { S* s; }
3047 Type mt = f.MemberType;
3049 has_unmanaged_check_done = false;
3050 requires_delayed_unmanagedtype_check = true;
3054 // TODO: Remove when pointer types are under mcs control
3055 while (mt.IsPointer)
3056 mt = TypeManager.GetElementType (mt);
3057 if (TypeManager.IsEqual (mt, TypeBuilder))
3060 if (TypeManager.IsUnmanagedType (mt))
3066 is_unmanaged = true;
3070 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
3072 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
3074 // If we are compiling our runtime,
3075 // and we are defining ValueType, then our
3076 // base is `System.Object'.
3078 if (base_class == null) {
3079 if (!RootContext.StdLib && Name == "System.ValueType")
3080 base_class = TypeManager.system_object_expr;
3082 base_class = TypeManager.system_valuetype_expr;
3089 // FIXME: Allow the user to specify a different set of attributes
3090 // in some cases (Sealed for example is mandatory for a class,
3091 // but what SequentialLayout can be changed
3093 protected override TypeAttributes TypeAttr {
3095 const TypeAttributes DefaultTypeAttributes =
3096 TypeAttributes.SequentialLayout |
3097 TypeAttributes.Sealed;
3099 return base.TypeAttr | DefaultTypeAttributes;
3103 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3105 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3106 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3107 field.GetSignatureForError ());
3110 base.RegisterFieldForInitialization (field, expression);
3118 public sealed class Interface : TypeContainer, IMemberContainer {
3121 /// Modifiers allowed in a class declaration
3123 public const int AllowedModifiers =
3126 Modifiers.PROTECTED |
3127 Modifiers.INTERNAL |
3131 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3133 : base (ns, parent, name, attrs, Kind.Interface)
3137 if (parent.Parent == null)
3138 accmods = Modifiers.INTERNAL;
3140 accmods = Modifiers.PRIVATE;
3142 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3145 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
3147 if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
3148 a.Error_MissingGuidAttribute ();
3152 base.ApplyAttributeBuilder (a, cb, pa);
3156 public override AttributeTargets AttributeTargets {
3158 return AttributeTargets.Interface;
3162 protected override TypeAttributes TypeAttr {
3164 const TypeAttributes DefaultTypeAttributes =
3165 TypeAttributes.AutoLayout |
3166 TypeAttributes.Abstract |
3167 TypeAttributes.Interface;
3169 return base.TypeAttr | DefaultTypeAttributes;
3173 protected override bool VerifyClsCompliance ()
3175 if (!base.VerifyClsCompliance ())
3178 if (ifaces != null) {
3179 foreach (Type t in ifaces) {
3180 if (AttributeTester.IsClsCompliant (t))
3183 Report.SymbolRelatedToPreviousError (t);
3184 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3185 GetSignatureForError (), TypeManager.CSharpName (t));
3193 // It is used as a base class for all property based members
3194 // This includes properties, indexers, and events
3195 public abstract class PropertyBasedMember : InterfaceMemberBase
3197 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3198 FullNamedExpression type, int mod, int allowed_mod,
3199 MemberName name, Attributes attrs)
3200 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3204 protected override bool VerifyClsCompliance ()
3206 if (!base.VerifyClsCompliance ())
3209 if (!AttributeTester.IsClsCompliant (MemberType)) {
3210 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3211 GetSignatureForError ());
3219 public abstract class MethodCore : InterfaceMemberBase
3221 public readonly ParametersCompiled Parameters;
3222 protected ToplevelBlock block;
3224 public MethodCore (DeclSpace parent, GenericMethod generic,
3225 FullNamedExpression type, int mod, int allowed_mod,
3226 MemberName name, Attributes attrs, ParametersCompiled parameters)
3227 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3229 Parameters = parameters;
3233 // Returns the System.Type array for the parameters of this method
3235 public Type [] ParameterTypes {
3237 return Parameters.Types;
3241 public ParametersCompiled ParameterInfo {
3247 public ToplevelBlock Block {
3257 public CallingConventions CallingConventions {
3259 CallingConventions cc = Parameters.CallingConvention;
3261 if ((ModFlags & Modifiers.STATIC) == 0)
3262 cc |= CallingConventions.HasThis;
3264 // FIXME: How is `ExplicitThis' used in C#?
3270 protected override bool CheckBase ()
3272 // Check whether arguments were correct.
3273 if (!DefineParameters (Parameters))
3276 return base.CheckBase ();
3280 // Returns a string that represents the signature for this
3281 // member which should be used in XML documentation.
3283 public override string GetDocCommentName (DeclSpace ds)
3285 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3289 // Raised (and passed an XmlElement that contains the comment)
3290 // when GenerateDocComment is writing documentation expectedly.
3292 // FIXME: with a few effort, it could be done with XmlReader,
3293 // that means removal of DOM use.
3295 internal override void OnGenerateDocComment (XmlElement el)
3297 DocUtil.OnMethodGenerateDocComment (this, el);
3301 // Represents header string for documentation comment.
3303 public override string DocCommentHeader
3305 get { return "M:"; }
3308 public override bool EnableOverloadChecks (MemberCore overload)
3310 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3311 caching_flags |= Flags.MethodOverloadsExist;
3315 return base.EnableOverloadChecks (overload);
3318 protected override bool VerifyClsCompliance ()
3320 if (!base.VerifyClsCompliance ())
3323 if (Parameters.HasArglist) {
3324 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3327 if (!AttributeTester.IsClsCompliant (MemberType)) {
3328 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3329 GetSignatureForError ());
3332 Parameters.VerifyClsCompliance ();
3338 public abstract class InterfaceMemberBase : MemberBase {
3340 // Whether this is an interface member.
3342 public bool IsInterface;
3345 // If true, this is an explicit interface implementation
3347 public bool IsExplicitImpl;
3349 protected bool is_external_implementation;
3352 // The interface type we are explicitly implementing
3354 public Type InterfaceType;
3357 // The method we're overriding if this is an override method.
3359 protected MethodInfo base_method;
3361 readonly int explicit_mod_flags;
3362 public MethodAttributes flags;
3364 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3365 FullNamedExpression type, int mod, int allowed_mod,
3366 MemberName name, Attributes attrs)
3367 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3370 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3371 IsExplicitImpl = (MemberName.Left != null);
3372 explicit_mod_flags = mod;
3375 protected override bool CheckBase ()
3377 if (!base.CheckBase ())
3380 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3381 CheckForDuplications ();
3386 // Is null for System.Object while compiling corlib and base interfaces
3387 if (Parent.PartialContainer.BaseCache == null) {
3388 if ((ModFlags & Modifiers.NEW) != 0) {
3389 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3394 Type base_ret_type = null;
3395 base_method = FindOutBaseMethod (ref base_ret_type);
3397 // method is override
3398 if (base_method != null) {
3399 if (!CheckMethodAgainstBase (base_ret_type))
3402 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3403 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3405 if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
3406 Report.SymbolRelatedToPreviousError (base_method);
3407 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3408 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3411 if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
3412 Report.SymbolRelatedToPreviousError (base_method);
3413 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3414 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3421 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3422 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3423 if (conflict_symbol != null) {
3424 Report.SymbolRelatedToPreviousError (conflict_symbol);
3426 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3427 else if (this is PropertyBase)
3428 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3430 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3432 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3433 GetSignatureForError (), SimpleName.GetMemberType (this));
3438 if (conflict_symbol == null) {
3439 if ((ModFlags & Modifiers.NEW) != 0) {
3440 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3445 if ((ModFlags & Modifiers.NEW) == 0) {
3446 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3449 Report.SymbolRelatedToPreviousError (conflict_symbol);
3450 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3451 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3457 protected virtual bool CheckForDuplications ()
3459 return Parent.MemberCache.CheckExistingMembersOverloads (
3460 this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters);
3464 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3465 // that have been defined.
3467 // `name' is the user visible name for reporting errors (this is used to
3468 // provide the right name regarding method names and properties)
3470 bool CheckMethodAgainstBase (Type base_method_type)
3474 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3475 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3476 Report.SymbolRelatedToPreviousError (base_method);
3477 Report.Error (506, Location,
3478 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3479 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3483 // Now we check that the overriden method is not final
3485 if (base_method.IsFinal) {
3486 Report.SymbolRelatedToPreviousError (base_method);
3487 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3488 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3492 // Check that the permissions are not being changed
3494 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3495 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3497 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3498 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3502 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3503 Report.SymbolRelatedToPreviousError (base_method);
3504 if (this is PropertyBasedMember) {
3505 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3506 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3509 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3510 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3516 if ((ModFlags & Modifiers.NEW) == 0) {
3517 if ((ModFlags & Modifiers.OVERRIDE) == 0) {
3518 ModFlags |= Modifiers.NEW;
3519 Report.SymbolRelatedToPreviousError (base_method);
3520 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3521 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",
3522 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3523 if (base_method.IsAbstract){
3524 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3525 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3529 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3530 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3534 if (base_method.IsAbstract && !IsInterface) {
3535 Report.SymbolRelatedToPreviousError (base_method);
3536 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3537 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3545 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3547 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3549 // when overriding protected internal, the method can be declared
3550 // protected internal only within the same assembly or assembly
3551 // which has InternalsVisibleTo
3553 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3554 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3555 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3557 // if it's not "protected internal", it must be "protected"
3561 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3563 // protected within the same assembly - an error
3566 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3567 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3569 // protected ok, but other attributes differ - report an error
3575 return (thisp == base_classp);
3579 public override bool Define ()
3582 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3583 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3585 flags = MethodAttributes.Public |
3586 MethodAttributes.Abstract |
3587 MethodAttributes.HideBySig |
3588 MethodAttributes.NewSlot |
3589 MethodAttributes.Virtual;
3591 Parent.PartialContainer.MethodModifiersValid (this);
3593 flags = Modifiers.MethodAttr (ModFlags);
3596 if (IsExplicitImpl) {
3597 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3598 if (iface_texpr == null)
3601 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3602 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3603 GetSignatureForError ());
3606 InterfaceType = iface_texpr.Type;
3608 if (!InterfaceType.IsInterface) {
3609 Report.SymbolRelatedToPreviousError (InterfaceType);
3610 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3611 TypeManager.CSharpName (InterfaceType));
3613 Parent.PartialContainer.VerifyImplements (this);
3616 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3619 return base.Define ();
3622 protected bool DefineParameters (ParametersCompiled parameters)
3624 if (!parameters.Resolve (this))
3628 for (int i = 0; i < parameters.Count; ++i) {
3629 Parameter p = parameters [i];
3631 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3632 p.Warning_UselessOptionalParameter ();
3634 if (p.CheckAccessibility (this))
3637 Type t = parameters.Types [i];
3638 Report.SymbolRelatedToPreviousError (t);
3639 if (this is Indexer)
3640 Report.Error (55, Location,
3641 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3642 TypeManager.CSharpName (t), GetSignatureForError ());
3643 else if (this is Operator)
3644 Report.Error (57, Location,
3645 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3646 TypeManager.CSharpName (t), GetSignatureForError ());
3648 Report.Error (51, Location,
3649 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3650 TypeManager.CSharpName (t), GetSignatureForError ());
3656 public override void Emit()
3658 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3659 // We are more strict than csc and report this as an error because SRE does not allow emit that
3660 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3661 if (this is Constructor) {
3662 Report.Error (824, Location,
3663 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3665 Report.Error (626, Location,
3666 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3667 GetSignatureForError ());
3674 public override bool EnableOverloadChecks (MemberCore overload)
3677 // Two members can differ in their explicit interface
3678 // type parameter only
3680 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3681 if (imb != null && imb.IsExplicitImpl) {
3682 if (IsExplicitImpl) {
3683 caching_flags |= Flags.MethodOverloadsExist;
3688 return IsExplicitImpl;
3691 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3693 Report.SymbolRelatedToPreviousError (base_method);
3694 string base_name = TypeManager.GetFullNameSignature (base_method);
3695 string this_name = GetSignatureForError ();
3696 if (suffix != null) {
3697 base_name += suffix;
3698 this_name += suffix;
3701 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3702 this_name, Modifiers.GetDescription (ma), base_name);
3705 protected static string Error722 {
3707 return "`{0}': static types cannot be used as return types";
3712 /// Gets base method and its return type
3714 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3717 // The "short" name of this property / indexer / event. This is the
3718 // name without the explicit interface.
3720 public string ShortName
3722 get { return MemberName.Name; }
3723 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3727 // Returns full metadata method name
3729 public string GetFullName (MemberName name)
3731 if (!IsExplicitImpl)
3735 // When dealing with explicit members a full interface type
3736 // name is added to member name to avoid possible name conflicts
3738 // We use CSharpName which gets us full name with benefit of
3739 // replacing predefined names which saves some space and name
3742 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3745 protected override bool VerifyClsCompliance ()
3747 if (!base.VerifyClsCompliance ()) {
3748 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3749 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3752 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3753 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3758 if (GenericMethod != null)
3759 GenericMethod.VerifyClsCompliance ();
3764 public override bool IsUsed
3766 get { return IsExplicitImpl || base.IsUsed; }
3771 public abstract class MethodOrOperator : MethodCore, IMethodData
3773 public MethodBuilder MethodBuilder;
3774 ReturnParameter return_attributes;
3775 ListDictionary declarative_security;
3776 protected MethodData MethodData;
3778 static string[] attribute_targets = new string [] { "method", "return" };
3780 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3781 int allowed_mod, MemberName name,
3782 Attributes attrs, ParametersCompiled parameters)
3783 : base (parent, generic, type, mod, allowed_mod, name,
3788 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
3790 if (a.Target == AttributeTargets.ReturnValue) {
3791 if (return_attributes == null)
3792 return_attributes = new ReturnParameter (MethodBuilder, Location);
3794 return_attributes.ApplyAttributeBuilder (a, cb, pa);
3798 if (a.IsInternalMethodImplAttribute) {
3799 is_external_implementation = true;
3802 if (a.Type == pa.DllImport) {
3803 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3804 if ((ModFlags & extern_static) != extern_static) {
3805 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3807 is_external_implementation = true;
3810 if (a.IsValidSecurityAttribute ()) {
3811 if (declarative_security == null)
3812 declarative_security = new ListDictionary ();
3813 a.ExtractSecurityPermissionSet (declarative_security);
3817 if (MethodBuilder != null)
3818 MethodBuilder.SetCustomAttribute (cb);
3821 public override AttributeTargets AttributeTargets {
3823 return AttributeTargets.Method;
3827 protected override bool CheckForDuplications ()
3829 string name = GetFullName (MemberName);
3830 if (MemberName.IsGeneric)
3831 name = MemberName.MakeName (name, MemberName.TypeArguments);
3833 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3836 public virtual EmitContext CreateEmitContext (ILGenerator ig)
3838 return new EmitContext (
3839 this, ig, MemberType);
3842 protected override bool ResolveMemberType ()
3845 if (GenericMethod != null) {
3846 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3847 if (!GenericMethod.Define (this))
3852 return base.ResolveMemberType ();
3855 public override bool Define ()
3857 if (!base.Define ())
3863 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3865 // Current method is turned into automatically generated
3866 // wrapper which creates an instance of iterator
3868 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3869 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3872 if (IsPartialDefinition) {
3873 caching_flags &= ~Flags.Excluded_Undetected;
3874 caching_flags |= Flags.Excluded;
3875 // Add to member cache only when a partial method implementation is not there
3876 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3877 MethodBase mb = new PartialMethodDefinitionInfo (this);
3878 Parent.MemberCache.AddMember (mb, this);
3879 TypeManager.AddMethod (mb, this);
3885 MethodData = new MethodData (
3886 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3888 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3891 MethodBuilder = MethodData.MethodBuilder;
3893 if (TypeManager.IsGenericMethod (MethodBuilder))
3894 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3896 Parent.MemberCache.AddMember (MethodBuilder, this);
3901 protected override void DoMemberTypeIndependentChecks ()
3903 base.DoMemberTypeIndependentChecks ();
3905 CheckAbstractAndExtern (block != null);
3907 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3908 for (int i = 0; i < Parameters.Count; ++i) {
3909 IParameterData p = Parameters.FixedParameters [i];
3910 if (p.ModFlags == Parameter.Modifier.OUT) {
3911 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3912 GetSignatureForError ());
3915 if (p.HasDefaultValue && IsPartialImplementation)
3916 ((Parameter) p).Warning_UselessOptionalParameter ();
3921 protected override void DoMemberTypeDependentChecks ()
3923 base.DoMemberTypeDependentChecks ();
3925 if (!TypeManager.IsGenericParameter (MemberType)) {
3926 if (MemberType.IsAbstract && MemberType.IsSealed) {
3927 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3932 public override void Emit ()
3934 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3935 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (MethodBuilder);
3936 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3937 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (MethodBuilder);
3939 if (TypeManager.IsDynamicType (ReturnType)) {
3940 return_attributes = new ReturnParameter (MethodBuilder, Location);
3941 return_attributes.EmitPredefined (PredefinedAttributes.Get.Dynamic, Location);
3944 if (OptAttributes != null)
3945 OptAttributes.Emit ();
3947 if (declarative_security != null) {
3948 foreach (DictionaryEntry de in declarative_security) {
3949 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3953 if (MethodData != null)
3954 MethodData.Emit (Parent);
3962 protected void Error_ConditionalAttributeIsNotValid ()
3964 Report.Error (577, Location,
3965 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3966 GetSignatureForError ());
3969 public bool IsPartialDefinition {
3971 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3975 public bool IsPartialImplementation {
3977 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3981 public override string[] ValidAttributeTargets {
3983 return attribute_targets;
3987 #region IMethodData Members
3989 public Type ReturnType {
3995 public MemberName MethodName {
4002 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4004 public bool IsExcluded () {
4005 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4006 return (caching_flags & Flags.Excluded) != 0;
4008 caching_flags &= ~Flags.Excluded_Undetected;
4010 if (base_method == null) {
4011 if (OptAttributes == null)
4014 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
4019 foreach (Attribute a in attrs) {
4020 string condition = a.GetConditionalAttributeValue ();
4021 if (condition == null)
4024 if (Location.CompilationUnit.IsConditionalDefined (condition))
4028 caching_flags |= Flags.Excluded;
4032 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4034 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
4035 caching_flags |= Flags.Excluded;
4041 if (md.IsExcluded ()) {
4042 caching_flags |= Flags.Excluded;
4048 GenericMethod IMethodData.GenericMethod {
4050 return GenericMethod;
4054 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4061 public class SourceMethod : IMethodDef
4064 SourceMethodBuilder builder;
4066 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4068 this.method = method;
4070 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4073 public string Name {
4074 get { return method.Name; }
4079 if (method is MethodBuilder)
4080 return ((MethodBuilder) method).GetToken ().Token;
4081 else if (method is ConstructorBuilder)
4082 return ((ConstructorBuilder) method).GetToken ().Token;
4084 throw new NotSupportedException ();
4088 public void CloseMethod ()
4090 SymbolWriter.CloseMethod ();
4093 public void SetRealMethodName (string name)
4095 if (builder != null)
4096 builder.SetRealMethodName (name);
4099 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4101 if (!SymbolWriter.HasSymbolWriter)
4106 Location start_loc = block.StartLocation;
4107 if (start_loc.IsNull)
4110 ICompileUnit compile_unit = start_loc.CompilationUnit;
4111 if (compile_unit == null)
4114 return new SourceMethod (parent, method, compile_unit);
4118 public class Method : MethodOrOperator {
4121 /// Modifiers allowed in a class declaration
4123 const int AllowedModifiers =
4126 Modifiers.PROTECTED |
4127 Modifiers.INTERNAL |
4132 Modifiers.OVERRIDE |
4133 Modifiers.ABSTRACT |
4137 const int AllowedInterfaceModifiers =
4138 Modifiers.NEW | Modifiers.UNSAFE;
4140 Method partialMethodImplementation;
4142 public Method (DeclSpace parent, GenericMethod generic,
4143 FullNamedExpression return_type, int mod,
4144 MemberName name, ParametersCompiled parameters, Attributes attrs)
4145 : base (parent, generic, return_type, mod,
4146 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4147 name, attrs, parameters)
4151 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4152 MemberName name, ParametersCompiled parameters, Attributes attrs)
4153 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4157 public override string GetSignatureForError()
4159 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4162 static void Error_DuplicateEntryPoint (Method b)
4164 Report.Error (17, b.Location,
4165 "Program `{0}' has more than one entry point defined: `{1}'",
4166 CodeGen.FileName, b.GetSignatureForError ());
4169 bool IsEntryPoint ()
4171 if (ReturnType != TypeManager.void_type &&
4172 ReturnType != TypeManager.int32_type)
4175 if (Parameters.Count == 0)
4178 if (Parameters.Count > 1)
4181 Type t = Parameters.Types [0];
4182 return t.IsArray && t.GetArrayRank () == 1 &&
4183 TypeManager.GetElementType (t) == TypeManager.string_type &&
4184 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4187 public override FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
4189 TypeParameter[] tp = CurrentTypeParameters;
4191 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
4193 return new TypeParameterExpr (t, loc);
4196 return base.LookupNamespaceOrType (name, loc, ignore_cs0104);
4199 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
4201 if (a.Type == pa.Conditional) {
4202 if (IsExplicitImpl) {
4203 Error_ConditionalAttributeIsNotValid ();
4207 if (ReturnType != TypeManager.void_type) {
4208 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4212 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4213 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4218 Report.Error (582, Location, "Conditional not valid on interface members");
4222 if (MethodData.implementing != null) {
4223 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4224 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4225 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4229 for (int i = 0; i < Parameters.Count; ++i) {
4230 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4231 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4237 if (a.Type == pa.Extension) {
4238 a.Error_MisusedExtensionAttribute ();
4242 base.ApplyAttributeBuilder (a, cb, pa);
4245 protected override bool CheckForDuplications ()
4247 if (!base.CheckForDuplications ())
4250 ArrayList ar = Parent.PartialContainer.Properties;
4252 for (int i = 0; i < ar.Count; ++i) {
4253 PropertyBase pb = (PropertyBase) ar [i];
4254 if (pb.AreAccessorsDuplicateImplementation (this))
4259 ar = Parent.PartialContainer.Indexers;
4261 for (int i = 0; i < ar.Count; ++i) {
4262 PropertyBase pb = (PropertyBase) ar [i];
4263 if (pb.AreAccessorsDuplicateImplementation (this))
4271 protected override bool CheckBase ()
4273 if (!base.CheckBase ())
4276 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
4277 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
4278 TypeManager.CSharpSignature (base_method));
4284 public override TypeParameter[] CurrentTypeParameters {
4286 if (GenericMethod != null)
4287 return GenericMethod.CurrentTypeParameters;
4296 public override bool Define ()
4298 if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
4299 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4302 if (!base.Define ())
4305 if (partialMethodImplementation != null && IsPartialDefinition)
4306 MethodBuilder = partialMethodImplementation.MethodBuilder;
4308 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4309 Error1599 (Location, ReturnType);
4313 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4314 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4315 Parent.PartialContainer.Mark_HasEquals ();
4316 else if (Parameters.IsEmpty && Name == "GetHashCode")
4317 Parent.PartialContainer.Mark_HasGetHashCode ();
4320 if ((ModFlags & Modifiers.STATIC) == 0)
4323 if (Parameters.HasExtensionMethodType) {
4324 if (Parent.PartialContainer.IsStaticClass && !Parent.IsGeneric) {
4325 if (!Parent.IsTopLevel)
4326 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4327 GetSignatureForError ());
4329 PredefinedAttribute pa = PredefinedAttributes.Get.Extension;
4330 if (!pa.IsDefined) {
4331 Report.Error (1110, Location,
4332 "`{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",
4333 GetSignatureForError ());
4336 ModFlags |= Modifiers.METHOD_EXTENSION;
4337 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
4338 CodeGen.Assembly.HasExtensionMethods = true;
4340 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4341 GetSignatureForError ());
4346 // This is used to track the Entry Point,
4348 if (RootContext.NeedsEntryPoint &&
4350 (RootContext.MainClass == null ||
4351 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4352 if (IsEntryPoint ()) {
4354 if (RootContext.EntryPoint == null) {
4355 if (Parent.IsGeneric || MemberName.IsGeneric) {
4356 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4357 GetSignatureForError ());
4360 RootContext.EntryPoint = this;
4363 Error_DuplicateEntryPoint (RootContext.EntryPoint);
4364 Error_DuplicateEntryPoint (this);
4367 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4368 GetSignatureForError ());
4378 public override void Emit ()
4381 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4382 if (IsPartialDefinition) {
4384 // Use partial method implementation builder for partial method declaration attributes
4386 if (partialMethodImplementation != null) {
4387 MethodBuilder = partialMethodImplementation.MethodBuilder;
4390 } else if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
4391 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4392 GetSignatureForError ());
4397 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4398 PredefinedAttributes.Get.Extension.EmitAttribute (MethodBuilder);
4400 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4401 Location, MethodBuilder);
4406 public override bool EnableOverloadChecks (MemberCore overload)
4408 // TODO: It can be deleted when members will be defined in correct order
4409 if (overload is Operator)
4410 return overload.EnableOverloadChecks (this);
4412 if (overload is Indexer)
4415 return base.EnableOverloadChecks (overload);
4418 public static void Error1599 (Location loc, Type t)
4420 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4423 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4425 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4426 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4431 if (mi.IsSpecialName)
4434 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4438 public void SetPartialDefinition (Method methodDefinition)
4440 caching_flags |= Flags.PartialDefinitionExists;
4441 methodDefinition.partialMethodImplementation = this;
4443 for (int i = 0; i < methodDefinition.Parameters.Count; ++i ) {
4444 Parameters [i].DefaultValue = methodDefinition.Parameters [i].DefaultValue;
4447 if (methodDefinition.attributes == null)
4450 if (attributes == null) {
4451 attributes = methodDefinition.attributes;
4453 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4457 protected override bool VerifyClsCompliance ()
4459 if (!base.VerifyClsCompliance ())
4462 if (!Parameters.IsEmpty) {
4463 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4465 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4472 public abstract class ConstructorInitializer : ExpressionStatement
4474 Arguments argument_list;
4475 MethodGroupExpr base_constructor_group;
4477 public ConstructorInitializer (Arguments argument_list, Location loc)
4479 this.argument_list = argument_list;
4483 public Arguments Arguments {
4485 return argument_list;
4489 public override Expression CreateExpressionTree (ResolveContext ec)
4491 throw new NotSupportedException ("ET");
4494 public override Expression DoResolve (ResolveContext ec)
4496 eclass = ExprClass.Value;
4498 // TODO: ec.GetSignatureForError ()
4499 ConstructorBuilder caller_builder = ((Constructor) ec.ResolveContext).ConstructorBuilder;
4501 if (argument_list != null) {
4505 // Spec mandates that constructor initializer will not have `this' access
4507 using (ec.Set (EmitContext.Options.BaseInitializer)) {
4508 argument_list.Resolve (ec, out dynamic);
4512 SimpleName ctor = new SimpleName (ConstructorBuilder.ConstructorName, loc);
4513 return new DynamicInvocation (ctor, argument_list, loc).Resolve (ec) as ExpressionStatement;
4517 type = ec.CurrentType;
4518 if (this is ConstructorBaseInitializer) {
4519 if (ec.CurrentType.BaseType == null)
4522 type = ec.CurrentType.BaseType;
4523 if (TypeManager.IsStruct (ec.CurrentType)) {
4524 Report.Error (522, loc,
4525 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4530 // It is legal to have "this" initializers that take no arguments
4531 // in structs, they are just no-ops.
4533 // struct D { public D (int a) : this () {}
4535 if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
4539 base_constructor_group = MemberLookupFinal (
4540 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4541 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4542 loc) as MethodGroupExpr;
4544 if (base_constructor_group == null)
4547 base_constructor_group = base_constructor_group.OverloadResolve (
4548 ec, ref argument_list, false, loc);
4550 if (base_constructor_group == null)
4554 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4556 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4558 if (base_ctor == caller_builder){
4559 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4565 public override void Emit (EmitContext ec)
4567 // It can be null for static initializers
4568 if (base_constructor_group == null)
4573 base_constructor_group.EmitCall (ec, argument_list);
4576 public override void EmitStatement (EmitContext ec)
4582 public class ConstructorBaseInitializer : ConstructorInitializer {
4583 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
4584 base (argument_list, l)
4589 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4590 public GeneratedBaseInitializer (Location loc):
4596 public class ConstructorThisInitializer : ConstructorInitializer {
4597 public ConstructorThisInitializer (Arguments argument_list, Location l) :
4598 base (argument_list, l)
4603 public class Constructor : MethodCore, IMethodData {
4604 public ConstructorBuilder ConstructorBuilder;
4605 public ConstructorInitializer Initializer;
4606 ListDictionary declarative_security;
4607 bool has_compliant_args;
4610 // Modifiers allowed for a constructor.
4612 public const int AllowedModifiers =
4614 Modifiers.PROTECTED |
4615 Modifiers.INTERNAL |
4621 static readonly string[] attribute_targets = new string [] { "method" };
4624 // The spec claims that static is not permitted, but
4625 // my very own code has static constructors.
4627 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, ParametersCompiled args,
4628 ConstructorInitializer init, Location loc)
4629 : base (parent, null, null, mod, AllowedModifiers,
4630 new MemberName (name, loc), attrs, args)
4635 public bool HasCompliantArgs {
4636 get { return has_compliant_args; }
4639 public override AttributeTargets AttributeTargets {
4640 get { return AttributeTargets.Constructor; }
4644 // Returns true if this is a default constructor
4646 public bool IsDefault ()
4648 if ((ModFlags & Modifiers.STATIC) != 0)
4649 return Parameters.IsEmpty;
4651 return Parameters.IsEmpty &&
4652 (Initializer is ConstructorBaseInitializer) &&
4653 (Initializer.Arguments == null);
4656 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
4658 if (a.IsValidSecurityAttribute ()) {
4659 if (declarative_security == null) {
4660 declarative_security = new ListDictionary ();
4662 a.ExtractSecurityPermissionSet (declarative_security);
4666 if (a.IsInternalMethodImplAttribute) {
4667 is_external_implementation = true;
4670 ConstructorBuilder.SetCustomAttribute (cb);
4673 protected override bool CheckBase ()
4675 if ((ModFlags & Modifiers.STATIC) != 0) {
4676 if (!Parameters.IsEmpty) {
4677 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4678 GetSignatureForError ());
4682 // the rest can be ignored
4686 // Check whether arguments were correct.
4687 if (!DefineParameters (Parameters))
4690 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4691 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4694 if (Parent.PartialContainer.Kind == Kind.Struct) {
4695 if (Parameters.Count == 0) {
4696 Report.Error (568, Location,
4697 "Structs cannot contain explicit parameterless constructors");
4702 CheckProtectedModifier ();
4708 // Creates the ConstructorBuilder
4710 public override bool Define ()
4712 if (ConstructorBuilder != null)
4715 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4716 MethodAttributes.SpecialName);
4718 if ((ModFlags & Modifiers.STATIC) != 0) {
4719 ca |= MethodAttributes.Static | MethodAttributes.Private;
4721 ca |= MethodAttributes.HideBySig;
4723 if ((ModFlags & Modifiers.PUBLIC) != 0)
4724 ca |= MethodAttributes.Public;
4725 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4726 if ((ModFlags & Modifiers.INTERNAL) != 0)
4727 ca |= MethodAttributes.FamORAssem;
4729 ca |= MethodAttributes.Family;
4730 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4731 ca |= MethodAttributes.Assembly;
4733 ca |= MethodAttributes.Private;
4736 if (!CheckAbstractAndExtern (block != null))
4739 // Check if arguments were correct.
4743 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4744 ca, CallingConventions,
4745 Parameters.GetEmitTypes ());
4747 if (Parent.PartialContainer.IsComImport) {
4748 if (!IsDefault ()) {
4749 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4750 Parent.GetSignatureForError ());
4752 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4755 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4756 TypeManager.AddMethod (ConstructorBuilder, this);
4758 // It's here only to report an error
4759 if (block != null && block.IsIterator) {
4760 member_type = TypeManager.void_type;
4761 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4770 public override void Emit ()
4772 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4773 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (ConstructorBuilder);
4775 if (OptAttributes != null)
4776 OptAttributes.Emit ();
4781 // If we use a "this (...)" constructor initializer, then
4782 // do not emit field initializers, they are initialized in the other constructor
4784 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4785 !(Initializer is ConstructorThisInitializer);
4787 BlockContext bc = new BlockContext (this, block, TypeManager.void_type);
4788 bc.Set (EmitContext.Options.ConstructorScope);
4790 if (emit_field_initializers)
4791 Parent.PartialContainer.ResolveFieldInitializers (bc);
4793 if (block != null) {
4794 // If this is a non-static `struct' constructor and doesn't have any
4795 // initializer, it must initialize all of the struct's fields.
4796 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4797 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4798 block.AddThisVariable (Parent, Location);
4800 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4801 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4802 Initializer = new GeneratedBaseInitializer (Location);
4804 if (Initializer != null) {
4805 block.AddScopeStatement (new StatementExpression (Initializer));
4810 Parameters.ApplyAttributes (ConstructorBuilder);
4812 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4814 if (block != null) {
4815 if (block.Resolve (null, bc, Parameters, this)) {
4816 EmitContext ec = CreateEmitContext (null);
4817 ec.Set (EmitContext.Options.ConstructorScope);
4819 ec.ReturnLabel = bc.ReturnLabel;
4820 ec.HasReturnLabel = bc.HasReturnLabel;
4826 source.CloseMethod ();
4828 if (declarative_security != null) {
4829 foreach (DictionaryEntry de in declarative_security) {
4830 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4837 // Is never override
4838 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4843 public override string GetSignatureForError()
4845 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4848 public override string[] ValidAttributeTargets {
4850 return attribute_targets;
4854 protected override bool VerifyClsCompliance ()
4856 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4860 if (!Parameters.IsEmpty) {
4861 ArrayList al = (ArrayList)Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
4863 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4865 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4866 foreach (Type param in Parameters.Types) {
4867 if (param.IsArray) {
4873 has_compliant_args = true;
4877 #region IMethodData Members
4879 public MemberName MethodName {
4885 public Type ReturnType {
4891 public EmitContext CreateEmitContext (ILGenerator ig)
4893 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4894 EmitContext ec = new EmitContext (this, ig_, TypeManager.void_type);
4898 public bool IsExcluded()
4903 GenericMethod IMethodData.GenericMethod {
4909 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4916 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4918 public interface IMethodData
4920 CallingConventions CallingConventions { get; }
4921 Location Location { get; }
4922 MemberName MethodName { get; }
4923 Type ReturnType { get; }
4924 GenericMethod GenericMethod { get; }
4925 ParametersCompiled ParameterInfo { get; }
4927 Attributes OptAttributes { get; }
4928 ToplevelBlock Block { get; set; }
4930 EmitContext CreateEmitContext (ILGenerator ig);
4931 ObsoleteAttribute GetObsoleteAttribute ();
4932 string GetSignatureForError ();
4934 bool IsClsComplianceRequired ();
4935 void SetMemberIsUsed ();
4936 void EmitExtraSymbolInfo (SourceMethod source);
4940 // Encapsulates most of the Method's state
4942 public class MethodData {
4943 static FieldInfo methodbuilder_attrs_field;
4944 public readonly IMethodData method;
4946 public readonly GenericMethod GenericMethod;
4949 // Are we implementing an interface ?
4951 public MethodInfo implementing;
4956 protected InterfaceMemberBase member;
4957 protected int modifiers;
4958 protected MethodAttributes flags;
4959 protected Type declaring_type;
4960 protected MethodInfo parent_method;
4962 MethodBuilder builder = null;
4963 public MethodBuilder MethodBuilder {
4969 public Type DeclaringType {
4971 return declaring_type;
4975 public MethodData (InterfaceMemberBase member,
4976 int modifiers, MethodAttributes flags, IMethodData method)
4978 this.member = member;
4979 this.modifiers = modifiers;
4982 this.method = method;
4985 public MethodData (InterfaceMemberBase member,
4986 int modifiers, MethodAttributes flags,
4987 IMethodData method, MethodBuilder builder,
4988 GenericMethod generic, MethodInfo parent_method)
4989 : this (member, modifiers, flags, method)
4991 this.builder = builder;
4992 this.GenericMethod = generic;
4993 this.parent_method = parent_method;
4996 public bool Define (DeclSpace parent, string method_full_name)
4998 string name = method.MethodName.Basename;
5000 TypeContainer container = parent.PartialContainer;
5002 PendingImplementation pending = container.PendingImplementations;
5003 if (pending != null){
5004 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
5006 if (member.InterfaceType != null){
5007 if (implementing == null){
5008 if (member is PropertyBase) {
5009 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5010 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5011 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5014 Report.Error (539, method.Location,
5015 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5016 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5020 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5021 Report.SymbolRelatedToPreviousError (implementing);
5022 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5023 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5027 if (implementing != null) {
5028 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5029 if (prop_method == null) {
5030 if (TypeManager.IsSpecialMethod (implementing)) {
5031 Report.SymbolRelatedToPreviousError (implementing);
5032 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5033 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5034 implementing.Name.StartsWith ("get_") ? "get" : "set");
5036 } else if (implementing.DeclaringType.IsInterface) {
5037 if (!implementing.IsSpecialName) {
5038 Report.SymbolRelatedToPreviousError (implementing);
5039 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5040 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5043 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5044 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5045 Report.SymbolRelatedToPreviousError (implementing);
5046 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5047 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5056 // For implicit implementations, make sure we are public, for
5057 // explicit implementations, make sure we are private.
5059 if (implementing != null){
5061 // Setting null inside this block will trigger a more
5062 // verbose error reporting for missing interface implementations
5064 // The "candidate" function has been flagged already
5065 // but it wont get cleared
5067 if (member.IsExplicitImpl){
5068 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5069 Report.SymbolRelatedToPreviousError (implementing);
5070 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5071 method.GetSignatureForError ());
5075 if (implementing.DeclaringType.IsInterface) {
5077 // If this is an interface method implementation,
5078 // check for public accessibility
5080 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5082 implementing = null;
5084 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5085 // We may never be private.
5086 implementing = null;
5088 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5090 // We may be protected if we're overriding something.
5092 implementing = null;
5097 // Static is not allowed
5099 if ((modifiers & Modifiers.STATIC) != 0){
5100 implementing = null;
5105 // If implementing is still valid, set flags
5107 if (implementing != null){
5109 // When implementing interface methods, set NewSlot
5110 // unless, we are overwriting a method.
5112 if (implementing.DeclaringType.IsInterface){
5113 if ((modifiers & Modifiers.OVERRIDE) == 0)
5114 flags |= MethodAttributes.NewSlot;
5117 MethodAttributes.Virtual |
5118 MethodAttributes.HideBySig;
5120 // Set Final unless we're virtual, abstract or already overriding a method.
5121 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5122 flags |= MethodAttributes.Final;
5125 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5127 if (builder == null)
5130 if (container.CurrentType != null)
5131 declaring_type = container.CurrentType;
5133 declaring_type = container.TypeBuilder;
5135 if (implementing != null && member.IsExplicitImpl) {
5136 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5139 TypeManager.AddMethod (builder, method);
5141 if (GenericMethod != null) {
5142 bool is_override = member.IsExplicitImpl |
5143 ((modifiers & Modifiers.OVERRIDE) != 0);
5145 if (implementing != null)
5146 parent_method = implementing;
5148 EmitContext ec = method.CreateEmitContext (null);
5149 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5158 /// Create the MethodBuilder for the method
5160 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
5162 if (builder == null) {
5163 builder = container.TypeBuilder.DefineMethod (
5164 method_name, flags, method.CallingConventions,
5165 TypeManager.TypeToReflectionType (method.ReturnType),
5166 param.GetEmitTypes ());
5172 // Generic method has been already defined to resolve method parameters
5173 // correctly when they use type parameters
5175 builder.SetParameters (param.GetEmitTypes ());
5176 builder.SetReturnType (method.ReturnType);
5178 if (builder.Attributes != flags) {
5180 if (methodbuilder_attrs_field == null)
5181 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5182 methodbuilder_attrs_field.SetValue (builder, flags);
5184 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5192 public void Emit (DeclSpace parent)
5194 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5196 if (GenericMethod != null)
5197 GenericMethod.EmitAttributes ();
5200 // clear the pending implementation flag
5202 if (implementing != null)
5203 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5204 member.InterfaceType, this, member.IsExplicitImpl);
5206 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5208 ToplevelBlock block = method.Block;
5209 if (block != null) {
5210 EmitContext ec = method.CreateEmitContext (builder.GetILGenerator ());
5211 BlockContext bc = new BlockContext (ec.ResolveContext, block, method.ReturnType);
5212 if (block.Resolve (null, bc, method.ParameterInfo, method)) {
5213 ec.ReturnLabel = bc.ReturnLabel;
5214 ec.HasReturnLabel = bc.HasReturnLabel;
5220 if (source != null) {
5221 method.EmitExtraSymbolInfo (source);
5222 source.CloseMethod ();
5227 public class Destructor : MethodOrOperator
5229 const int AllowedModifiers =
5233 static readonly string[] attribute_targets = new string [] { "method" };
5235 public static readonly string MetadataName = "Finalize";
5237 public Destructor (DeclSpace parent, int mod, ParametersCompiled parameters, Attributes attrs, Location l)
5238 : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
5239 new MemberName (MetadataName, l), attrs, parameters)
5241 ModFlags &= ~Modifiers.PRIVATE;
5242 ModFlags |= Modifiers.PROTECTED;
5245 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
5247 if (a.Type == pa.Conditional) {
5248 Error_ConditionalAttributeIsNotValid ();
5252 base.ApplyAttributeBuilder (a, cb, pa);
5255 protected override bool CheckBase ()
5257 flags |= MethodAttributes.Virtual;
5259 if (!base.CheckBase ())
5262 if (Parent.PartialContainer.BaseCache == null)
5265 Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
5266 if (base_type != null && Block != null) {
5267 MethodGroupExpr method_expr = Expression.MethodLookup (Parent.TypeBuilder, base_type, MetadataName, Location);
5268 if (method_expr == null)
5269 throw new NotImplementedException ();
5271 method_expr.IsBase = true;
5272 method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
5274 ToplevelBlock new_block = new ToplevelBlock (Block.StartLocation);
5275 new_block.EndLocation = Block.EndLocation;
5277 Block finaly_block = new ExplicitBlock (new_block, Location, Location);
5278 Block try_block = new Block (new_block, block);
5281 // 0-size arguments to avoid CS0250 error
5282 // TODO: Should use AddScopeStatement or something else which emits correct
5285 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
5286 new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
5294 public override string GetSignatureForError ()
5296 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5299 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5304 public override string[] ValidAttributeTargets {
5306 return attribute_targets;
5311 public abstract class MemberBase : MemberCore
5313 protected FullNamedExpression type_name;
5314 protected Type member_type;
5316 public readonly DeclSpace ds;
5317 public readonly GenericMethod GenericMethod;
5319 protected MemberBase (DeclSpace parent, GenericMethod generic,
5320 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5321 MemberName name, Attributes attrs)
5322 : base (parent, name, attrs)
5324 this.ds = generic != null ? generic : (DeclSpace) parent;
5325 this.type_name = type;
5326 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5327 GenericMethod = generic;
5328 if (GenericMethod != null)
5329 GenericMethod.ModFlags = ModFlags;
5333 // Main member define entry
5335 public override bool Define ()
5337 DoMemberTypeIndependentChecks ();
5340 // Returns false only when type resolution failed
5342 if (!ResolveMemberType ())
5345 DoMemberTypeDependentChecks ();
5350 // Any type_name independent checks
5352 protected virtual void DoMemberTypeIndependentChecks ()
5354 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5355 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5356 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5357 GetSignatureForError (), Parent.GetSignatureForError ());
5362 // Any type_name dependent checks
5364 protected virtual void DoMemberTypeDependentChecks ()
5366 // verify accessibility
5367 if (!IsAccessibleAs (MemberType)) {
5368 Report.SymbolRelatedToPreviousError (MemberType);
5369 if (this is Property)
5370 Report.Error (53, Location,
5371 "Inconsistent accessibility: property type `" +
5372 TypeManager.CSharpName (MemberType) + "' is less " +
5373 "accessible than property `" + GetSignatureForError () + "'");
5374 else if (this is Indexer)
5375 Report.Error (54, Location,
5376 "Inconsistent accessibility: indexer return type `" +
5377 TypeManager.CSharpName (MemberType) + "' is less " +
5378 "accessible than indexer `" + GetSignatureForError () + "'");
5379 else if (this is MethodCore) {
5380 if (this is Operator)
5381 Report.Error (56, Location,
5382 "Inconsistent accessibility: return type `" +
5383 TypeManager.CSharpName (MemberType) + "' is less " +
5384 "accessible than operator `" + GetSignatureForError () + "'");
5386 Report.Error (50, Location,
5387 "Inconsistent accessibility: return type `" +
5388 TypeManager.CSharpName (MemberType) + "' is less " +
5389 "accessible than method `" + GetSignatureForError () + "'");
5391 Report.Error (52, Location,
5392 "Inconsistent accessibility: field type `" +
5393 TypeManager.CSharpName (MemberType) + "' is less " +
5394 "accessible than field `" + GetSignatureForError () + "'");
5398 Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
5399 TypeManager.CheckTypeVariance (MemberType, variance, this);
5402 protected bool IsTypePermitted ()
5404 if (TypeManager.IsSpecialType (MemberType)) {
5405 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5411 protected virtual bool CheckBase ()
5413 CheckProtectedModifier ();
5418 public Type MemberType {
5419 get { return member_type; }
5422 protected virtual bool ResolveMemberType ()
5424 if (member_type != null)
5425 throw new InternalErrorException ("Multi-resolve");
5427 TypeExpr te = type_name.ResolveAsTypeTerminal (this, false);
5432 // Replace original type name, error reporting can use fully resolved name
5436 member_type = te.Type;
5442 // Abstract class for all fields
5444 abstract public class FieldBase : MemberBase {
5445 public FieldBuilder FieldBuilder;
5446 public Status status;
5447 protected Expression initializer;
5450 public enum Status : byte {
5451 HAS_OFFSET = 4 // Used by FieldMember.
5454 static readonly string[] attribute_targets = new string [] { "field" };
5456 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5457 int allowed_mod, MemberName name, Attributes attrs)
5458 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5461 if ((mod & Modifiers.ABSTRACT) != 0)
5462 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5465 public override AttributeTargets AttributeTargets {
5467 return AttributeTargets.Field;
5471 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
5473 if (a.Type == pa.FieldOffset) {
5474 status |= Status.HAS_OFFSET;
5476 if (!Parent.PartialContainer.HasExplicitLayout) {
5477 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5481 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5482 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5488 if (a.Type == pa.FixedBuffer) {
5489 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5495 if (a.Type == pa.MarshalAs) {
5496 UnmanagedMarshal marshal = a.GetMarshal (this);
5497 if (marshal != null) {
5498 FieldBuilder.SetMarshal (marshal);
5503 if ((a.HasSecurityAttribute)) {
5504 a.Error_InvalidSecurityParent ();
5508 FieldBuilder.SetCustomAttribute (cb);
5511 protected override bool CheckBase ()
5513 if (!base.CheckBase ())
5516 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5517 if (conflict_symbol == null) {
5518 if ((ModFlags & Modifiers.NEW) != 0) {
5519 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5524 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
5525 Report.SymbolRelatedToPreviousError (conflict_symbol);
5526 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5527 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5533 protected override void DoMemberTypeDependentChecks ()
5535 base.DoMemberTypeDependentChecks ();
5537 if (TypeManager.IsGenericParameter (MemberType))
5540 if (MemberType.IsSealed && MemberType.IsAbstract) {
5541 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5549 // Represents header string for documentation comment.
5551 public override string DocCommentHeader {
5552 get { return "F:"; }
5555 public override void Emit ()
5557 if (TypeManager.IsDynamicType (member_type))
5558 PredefinedAttributes.Get.Dynamic.EmitAttribute (FieldBuilder);
5560 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5561 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (FieldBuilder);
5563 if (OptAttributes != null) {
5564 OptAttributes.Emit ();
5567 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5568 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5574 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5576 Report.SymbolRelatedToPreviousError (static_class);
5577 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5581 public Expression Initializer {
5583 if (value != null) {
5584 this.initializer = value;
5589 protected virtual bool IsFieldClsCompliant {
5591 if (FieldBuilder == null)
5594 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5598 public override string[] ValidAttributeTargets
5601 return attribute_targets;
5605 protected override bool VerifyClsCompliance ()
5607 if (!base.VerifyClsCompliance ())
5610 if (!IsFieldClsCompliant) {
5611 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5612 GetSignatureForError ());
5617 public void SetAssigned ()
5619 caching_flags |= Flags.IsAssigned;
5623 interface IFixedBuffer
5625 FieldInfo Element { get; }
5626 Type ElementType { get; }
5629 public class FixedFieldExternal: IFixedBuffer
5631 FieldInfo element_field;
5633 public FixedFieldExternal (FieldInfo fi)
5635 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5638 #region IFixedField Members
5640 public FieldInfo Element {
5642 return element_field;
5646 public Type ElementType {
5648 return element_field.FieldType;
5656 /// Fixed buffer implementation
5658 public class FixedField : FieldBase, IFixedBuffer
5660 public const string FixedElementName = "FixedElementField";
5661 static int GlobalCounter = 0;
5662 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5663 static FieldInfo[] fi;
5665 TypeBuilder fixed_buffer_type;
5666 FieldBuilder element;
5667 Expression size_expr;
5669 const int AllowedModifiers =
5672 Modifiers.PROTECTED |
5673 Modifiers.INTERNAL |
5676 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5677 Expression size_expr, Attributes attrs, Location loc):
5678 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5680 if (RootContext.Version < LanguageVersion.ISO_2)
5681 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5683 this.size_expr = size_expr;
5686 public override bool Define()
5688 if (!base.Define ())
5691 if (!TypeManager.IsPrimitiveType (MemberType)) {
5692 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",
5693 GetSignatureForError ());
5696 // Create nested fixed buffer container
5697 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5698 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
5699 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5701 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5702 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5704 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5705 Parent.MemberCache.AddMember (FieldBuilder, this);
5706 TypeManager.RegisterFieldBase (FieldBuilder, this);
5711 protected override void DoMemberTypeIndependentChecks ()
5713 base.DoMemberTypeIndependentChecks ();
5715 if (!Parent.IsInUnsafeScope)
5716 Expression.UnsafeError (Location);
5718 if (Parent.PartialContainer.Kind != Kind.Struct) {
5719 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5720 GetSignatureForError ());
5724 public override void Emit()
5726 ResolveContext rc = new ResolveContext (this);
5727 Constant c = size_expr.ResolveAsConstant (rc, this);
5731 IntConstant buffer_size_const = c.ImplicitConversionRequired (rc, TypeManager.int32_type, Location) as IntConstant;
5732 if (buffer_size_const == null)
5735 int buffer_size = buffer_size_const.Value;
5737 if (buffer_size <= 0) {
5738 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5742 int type_size = Expression.GetTypeSize (MemberType);
5744 if (buffer_size > int.MaxValue / type_size) {
5745 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5746 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5750 buffer_size *= type_size;
5751 EmitFieldSize (buffer_size);
5753 PredefinedAttributes.Get.UnsafeValueType.EmitAttribute (fixed_buffer_type);
5758 void EmitFieldSize (int buffer_size)
5760 CustomAttributeBuilder cab;
5761 PredefinedAttribute pa;
5763 pa = PredefinedAttributes.Get.StructLayout;
5764 if (pa.Constructor == null &&
5765 !pa.ResolveConstructor (Location, TypeManager.short_type))
5768 // TODO: It's not cleared
5770 fi = new FieldInfo[] { pa.Type.GetField ("Size") };
5772 object[] fi_val = new object[] { buffer_size };
5773 cab = new CustomAttributeBuilder (pa.Constructor,
5774 ctor_args, fi, fi_val);
5775 fixed_buffer_type.SetCustomAttribute (cab);
5778 // Don't emit FixedBufferAttribute attribute for private types
5780 if ((ModFlags & Modifiers.PRIVATE) != 0)
5783 pa = PredefinedAttributes.Get.FixedBuffer;
5784 if (pa.Constructor == null &&
5785 !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
5788 cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType, buffer_size });
5789 FieldBuilder.SetCustomAttribute (cab);
5792 protected override bool IsFieldClsCompliant {
5798 public void SetCharSet (TypeAttributes ta)
5800 TypeAttributes cta = fixed_buffer_type.Attributes;
5801 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5802 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5803 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5804 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5805 else if (cta == 0 && ta != 0)
5806 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5809 void SetTypeBuilderCharSet (TypeAttributes ta)
5811 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5813 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5815 mi.Invoke (fixed_buffer_type, new object [] { ta });
5819 #region IFixedField Members
5821 public FieldInfo Element {
5827 public Type ElementType {
5837 // The Field class is used to represents class/struct fields during parsing.
5839 public class Field : FieldBase {
5841 // Modifiers allowed in a class declaration
5843 const int AllowedModifiers =
5846 Modifiers.PROTECTED |
5847 Modifiers.INTERNAL |
5850 Modifiers.VOLATILE |
5854 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5856 : base (parent, type, mod, AllowedModifiers, name, attrs)
5860 bool CanBeVolatile ()
5862 if (TypeManager.IsReferenceType (MemberType))
5865 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5866 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5867 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5868 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5869 MemberType == TypeManager.float_type ||
5870 MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
5873 if (TypeManager.IsEnumType (MemberType))
5879 bool CheckStructLayout (Type type, bool isStatic)
5881 if (TypeManager.IsBuiltinType (type))
5885 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5889 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5890 if (!TypeManager.IsGenericType (type))
5893 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5894 if (!CheckStructLayout (t, false))
5900 Report.Error (523, Location,
5901 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5902 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5906 public override bool Define ()
5908 if (!base.Define ())
5913 Type[] required_modifier = null;
5914 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5915 if (TypeManager.isvolatile_type == null)
5916 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5917 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5919 if (TypeManager.isvolatile_type != null)
5920 required_modifier = new Type [] { TypeManager.isvolatile_type };
5923 FieldBuilder = Parent.TypeBuilder.DefineField (
5924 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5926 FieldBuilder = Parent.TypeBuilder.DefineField (
5927 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5929 // Don't cache inaccessible fields
5930 if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
5931 Parent.MemberCache.AddMember (FieldBuilder, this);
5934 TypeManager.RegisterFieldBase (FieldBuilder, this);
5936 catch (ArgumentException) {
5937 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5941 if (initializer != null) {
5942 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5943 new FieldInitializer (FieldBuilder, initializer, this));
5945 if (Parent.PartialContainer.Kind == Kind.Struct)
5946 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5952 protected override void DoMemberTypeDependentChecks ()
5954 base.DoMemberTypeDependentChecks ();
5956 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5957 if (!CanBeVolatile ()) {
5958 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5959 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5962 if ((ModFlags & Modifiers.READONLY) != 0) {
5963 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5964 GetSignatureForError ());
5969 protected override bool VerifyClsCompliance ()
5971 if (!base.VerifyClsCompliance ())
5974 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5975 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5983 // `set' and `get' accessors are represented with an Accessor.
5985 public class Accessor {
5987 // Null if the accessor is empty, or a Block if not
5989 public const int AllowedModifiers =
5991 Modifiers.PROTECTED |
5992 Modifiers.INTERNAL |
5995 public ToplevelBlock Block;
5996 public Attributes Attributes;
5997 public Location Location;
5998 public int ModFlags;
5999 public ParametersCompiled Parameters;
6001 public Accessor (ToplevelBlock b, int mod, Attributes attrs, ParametersCompiled p, Location loc)
6007 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6011 // Ooouh Martin, templates are missing here.
6012 // When it will be possible move here a lot of child code and template method type.
6013 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6014 protected MethodData method_data;
6015 protected ToplevelBlock block;
6016 protected ListDictionary declarative_security;
6018 // The accessor are created even if they are not wanted.
6019 // But we need them because their names are reserved.
6020 // Field says whether accessor will be emited or not
6021 public readonly bool IsDummy;
6023 protected readonly string prefix;
6025 ReturnParameter return_attributes;
6027 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6028 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6030 this.prefix = prefix;
6034 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6036 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6037 accessor.Attributes)
6039 this.prefix = prefix;
6040 this.block = accessor.Block;
6043 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6045 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6048 public void UpdateName (InterfaceMemberBase member)
6050 SetMemberName (SetupName (prefix, member, Location));
6053 #region IMethodData Members
6055 public ToplevelBlock Block {
6065 public CallingConventions CallingConventions {
6067 return CallingConventions.Standard;
6071 public bool IsExcluded ()
6076 GenericMethod IMethodData.GenericMethod {
6082 public MemberName MethodName {
6088 public Type[] ParameterTypes {
6090 return ParameterInfo.Types;
6094 public abstract ParametersCompiled ParameterInfo { get ; }
6095 public abstract Type ReturnType { get; }
6096 public abstract EmitContext CreateEmitContext (ILGenerator ig);
6100 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
6102 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
6103 Report.Error (1667, a.Location,
6104 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6105 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6109 if (a.IsValidSecurityAttribute ()) {
6110 if (declarative_security == null)
6111 declarative_security = new ListDictionary ();
6112 a.ExtractSecurityPermissionSet (declarative_security);
6116 if (a.Target == AttributeTargets.Method) {
6117 method_data.MethodBuilder.SetCustomAttribute (cb);
6121 if (a.Target == AttributeTargets.ReturnValue) {
6122 if (return_attributes == null)
6123 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6125 return_attributes.ApplyAttributeBuilder (a, cb, pa);
6129 ApplyToExtraTarget (a, cb, pa);
6132 protected virtual void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
6134 throw new NotSupportedException ("You forgot to define special attribute target handling");
6137 // It is not supported for the accessors
6138 public sealed override bool Define()
6140 throw new NotSupportedException ();
6143 public virtual void Emit (DeclSpace parent)
6145 method_data.Emit (parent);
6147 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6148 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
6149 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6150 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
6152 if (TypeManager.IsDynamicType (ReturnType)) {
6153 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6154 return_attributes.EmitPredefined (PredefinedAttributes.Get.Dynamic, Location);
6157 if (OptAttributes != null)
6158 OptAttributes.Emit ();
6160 if (declarative_security != null) {
6161 foreach (DictionaryEntry de in declarative_security) {
6162 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6169 public override bool EnableOverloadChecks (MemberCore overload)
6171 // This can only happen with indexers and it will
6172 // be catched as indexer difference
6173 if (overload is AbstractPropertyEventMethod)
6176 if (overload is MethodCore) {
6177 caching_flags |= Flags.MethodOverloadsExist;
6183 public override bool IsClsComplianceRequired()
6188 public bool IsDuplicateImplementation (MethodCore method)
6190 if (!MemberName.Equals (method.MemberName))
6193 Type[] param_types = method.ParameterTypes;
6195 if (param_types == null || param_types.Length != ParameterTypes.Length)
6198 for (int i = 0; i < param_types.Length; i++)
6199 if (param_types [i] != ParameterTypes [i])
6202 Report.SymbolRelatedToPreviousError (method);
6203 Report.Error (82, Location, "A member `{0}' is already reserved",
6204 method.GetSignatureForError ());
6208 public override bool IsUsed
6219 // Represents header string for documentation comment.
6221 public override string DocCommentHeader {
6222 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6225 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6230 // Properties and Indexers both generate PropertyBuilders, we use this to share
6231 // their common bits.
6233 abstract public class PropertyBase : PropertyBasedMember {
6235 public class GetMethod : PropertyMethod
6237 static string[] attribute_targets = new string [] { "method", "return" };
6239 public GetMethod (PropertyBase method):
6240 base (method, "get_")
6244 public GetMethod (PropertyBase method, Accessor accessor):
6245 base (method, accessor, "get_")
6249 public override MethodBuilder Define (DeclSpace parent)
6251 base.Define (parent);
6256 method_data = new MethodData (method, ModFlags, flags, this);
6258 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6261 return method_data.MethodBuilder;
6264 public override Type ReturnType {
6266 return method.MemberType;
6270 public override ParametersCompiled ParameterInfo {
6272 return ParametersCompiled.EmptyReadOnlyParameters;
6276 public override string[] ValidAttributeTargets {
6278 return attribute_targets;
6283 public class SetMethod : PropertyMethod {
6285 static string[] attribute_targets = new string [] { "method", "param", "return" };
6286 ImplicitParameter param_attr;
6287 protected ParametersCompiled parameters;
6289 public SetMethod (PropertyBase method) :
6290 base (method, "set_")
6292 parameters = new ParametersCompiled (
6293 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6296 public SetMethod (PropertyBase method, Accessor accessor):
6297 base (method, accessor, "set_")
6299 this.parameters = accessor.Parameters;
6302 protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
6304 if (a.Target == AttributeTargets.Parameter) {
6305 if (param_attr == null)
6306 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6308 param_attr.ApplyAttributeBuilder (a, cb, pa);
6312 base.ApplyAttributeBuilder (a, cb, pa);
6315 public override ParametersCompiled ParameterInfo {
6321 public override MethodBuilder Define (DeclSpace parent)
6323 parameters.Resolve (this);
6325 base.Define (parent);
6330 method_data = new MethodData (method, ModFlags, flags, this);
6332 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6335 return method_data.MethodBuilder;
6338 public override Type ReturnType {
6340 return TypeManager.void_type;
6344 public override string[] ValidAttributeTargets {
6346 return attribute_targets;
6351 static string[] attribute_targets = new string [] { "property" };
6353 public abstract class PropertyMethod : AbstractPropertyEventMethod
6355 protected readonly PropertyBase method;
6356 protected MethodAttributes flags;
6358 public PropertyMethod (PropertyBase method, string prefix)
6359 : base (method, prefix)
6361 this.method = method;
6362 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6365 public PropertyMethod (PropertyBase method, Accessor accessor,
6367 : base (method, accessor, prefix)
6369 this.method = method;
6370 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6372 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6373 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6377 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
6379 if (a.IsInternalMethodImplAttribute) {
6380 method.is_external_implementation = true;
6383 base.ApplyAttributeBuilder (a, cb, pa);
6386 public override AttributeTargets AttributeTargets {
6388 return AttributeTargets.Method;
6392 public override bool IsClsComplianceRequired ()
6394 return method.IsClsComplianceRequired ();
6397 public virtual MethodBuilder Define (DeclSpace parent)
6399 CheckForDuplications ();
6402 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6403 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6404 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6406 Report.SymbolRelatedToPreviousError (mi);
6407 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6408 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6414 TypeContainer container = parent.PartialContainer;
6417 // Check for custom access modifier
6419 if ((ModFlags & Modifiers.Accessibility) == 0) {
6420 ModFlags |= method.ModFlags;
6421 flags = method.flags;
6423 if (container.Kind == Kind.Interface)
6424 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6425 GetSignatureForError ());
6427 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6428 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6431 CheckModifiers (ModFlags);
6432 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6433 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6434 flags = Modifiers.MethodAttr (ModFlags);
6435 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6438 CheckAbstractAndExtern (block != null);
6440 if (block != null && block.IsIterator)
6441 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6446 public bool HasCustomAccessModifier {
6448 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6452 public PropertyBase Property {
6458 public override EmitContext CreateEmitContext (ILGenerator ig)
6460 return new EmitContext (this,
6464 public override ObsoleteAttribute GetObsoleteAttribute ()
6466 return method.GetObsoleteAttribute ();
6469 public override string GetSignatureForError()
6471 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6474 void CheckModifiers (int modflags)
6476 modflags &= Modifiers.Accessibility;
6478 int mflags = method.ModFlags & Modifiers.Accessibility;
6480 if ((mflags & Modifiers.PUBLIC) != 0) {
6481 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6483 else if ((mflags & Modifiers.PROTECTED) != 0) {
6484 if ((mflags & Modifiers.INTERNAL) != 0)
6485 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6487 flags |= Modifiers.PRIVATE;
6489 else if ((mflags & Modifiers.INTERNAL) != 0)
6490 flags |= Modifiers.PRIVATE;
6492 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6493 Report.Error (273, Location,
6494 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6495 GetSignatureForError (), method.GetSignatureForError ());
6499 protected bool CheckForDuplications ()
6501 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6504 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6508 public PropertyMethod Get, Set;
6509 public PropertyBuilder PropertyBuilder;
6510 public MethodBuilder GetBuilder, SetBuilder;
6512 protected bool define_set_first = false;
6514 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6515 int allowed_mod, MemberName name,
6516 Attributes attrs, bool define_set_first)
6517 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6519 this.define_set_first = define_set_first;
6522 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
6524 if (a.HasSecurityAttribute) {
6525 a.Error_InvalidSecurityParent ();
6529 PropertyBuilder.SetCustomAttribute (cb);
6532 public override AttributeTargets AttributeTargets {
6534 return AttributeTargets.Property;
6538 protected override void DoMemberTypeDependentChecks ()
6540 base.DoMemberTypeDependentChecks ();
6544 if (MemberType.IsGenericParameter)
6548 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6549 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6553 protected override void DoMemberTypeIndependentChecks ()
6555 base.DoMemberTypeIndependentChecks ();
6558 // Accessors modifiers check
6560 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6561 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6562 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6563 GetSignatureForError ());
6566 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6567 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6568 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6569 Report.Error (276, Location,
6570 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6571 GetSignatureForError ());
6577 GetBuilder = Get.Define (Parent);
6578 return (Get.IsDummy) ? true : GetBuilder != null;
6581 bool DefineSet (bool define)
6586 SetBuilder = Set.Define (Parent);
6587 return (Set.IsDummy) ? true : SetBuilder != null;
6590 protected bool DefineAccessors ()
6592 return DefineSet (define_set_first) &&
6594 DefineSet (!define_set_first);
6597 protected abstract PropertyInfo ResolveBaseProperty ();
6599 // TODO: rename to Resolve......
6600 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6602 PropertyInfo base_property = ResolveBaseProperty ();
6603 if (base_property == null)
6606 base_ret_type = base_property.PropertyType;
6607 MethodInfo get_accessor = base_property.GetGetMethod (true);
6608 MethodInfo set_accessor = base_property.GetSetMethod (true);
6609 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6612 // Check base property accessors conflict
6614 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6615 if (get_accessor == null) {
6616 if (Get != null && !Get.IsDummy) {
6617 Report.SymbolRelatedToPreviousError (base_property);
6618 Report.Error (545, Location,
6619 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6620 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6623 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6625 if (!Get.IsDummy && !CheckAccessModifiers (
6626 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6627 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6630 if (set_accessor == null) {
6631 if (Set != null && !Set.IsDummy) {
6632 Report.SymbolRelatedToPreviousError (base_property);
6633 Report.Error (546, Location,
6634 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6635 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6638 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6640 if (!Set.IsDummy && !CheckAccessModifiers (
6641 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6642 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6646 // When one accessor does not exist and property hides base one
6647 // we need to propagate this upwards
6648 if (set_accessor == null)
6649 set_accessor = get_accessor;
6652 // Get the less restrictive access
6654 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6657 public override void Emit ()
6660 // The PropertyBuilder can be null for explicit implementations, in that
6661 // case, we do not actually emit the ".property", so there is nowhere to
6662 // put the attribute
6664 if (PropertyBuilder != null) {
6665 if (OptAttributes != null)
6666 OptAttributes.Emit ();
6668 if (TypeManager.IsDynamicType (member_type))
6669 PredefinedAttributes.Get.Dynamic.EmitAttribute (PropertyBuilder);
6682 /// Tests whether accessors are not in collision with some method (CS0111)
6684 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6686 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6689 public override bool IsUsed
6695 return Get.IsUsed | Set.IsUsed;
6699 protected override void SetMemberName (MemberName new_name)
6701 base.SetMemberName (new_name);
6703 Get.UpdateName (this);
6704 Set.UpdateName (this);
6707 public override string[] ValidAttributeTargets {
6709 return attribute_targets;
6714 // Represents header string for documentation comment.
6716 public override string DocCommentHeader {
6717 get { return "P:"; }
6721 public class Property : PropertyBase
6723 public sealed class BackingField : Field
6725 readonly Property property;
6727 public BackingField (Property p)
6728 : base (p.Parent, p.type_name,
6729 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6730 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
6735 public override string GetSignatureForError ()
6737 return property.GetSignatureForError ();
6741 const int AllowedModifiers =
6744 Modifiers.PROTECTED |
6745 Modifiers.INTERNAL |
6749 Modifiers.OVERRIDE |
6750 Modifiers.ABSTRACT |
6755 const int AllowedInterfaceModifiers =
6758 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6759 MemberName name, Attributes attrs, Accessor get_block,
6760 Accessor set_block, bool define_set_first)
6761 : this (parent, type, mod, name, attrs, get_block, set_block,
6762 define_set_first, null)
6766 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6767 MemberName name, Attributes attrs, Accessor get_block,
6768 Accessor set_block, bool define_set_first, Block current_block)
6769 : base (parent, type, mod,
6770 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6771 name, attrs, define_set_first)
6773 if (get_block == null)
6774 Get = new GetMethod (this);
6776 Get = new GetMethod (this, get_block);
6778 if (set_block == null)
6779 Set = new SetMethod (this);
6781 Set = new SetMethod (this, set_block);
6783 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6784 get_block != null && get_block.Block == null &&
6785 set_block != null && set_block.Block == null) {
6786 if (RootContext.Version <= LanguageVersion.ISO_2)
6787 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6789 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
6790 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
6794 void CreateAutomaticProperty ()
6796 // Create backing field
6797 Field field = new BackingField (this);
6798 if (!field.Define ())
6801 Parent.PartialContainer.AddField (field);
6803 FieldExpr fe = new FieldExpr (field.FieldBuilder, Location);
6804 if ((field.ModFlags & Modifiers.STATIC) == 0)
6805 fe.InstanceExpression = new CompilerGeneratedThis (fe.Type, Location);
6808 Get.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
6809 Return r = new Return (fe, Location);
6810 Get.Block.AddStatement (r);
6813 Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
6814 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location));
6815 Set.Block.AddStatement (new StatementExpression (a));
6818 public override bool Define ()
6820 if (!base.Define ())
6823 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6825 if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6826 CreateAutomaticProperty ();
6828 if (!DefineAccessors ())
6834 // FIXME - PropertyAttributes.HasDefault ?
6836 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6837 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6840 PropertyBuilder.SetGetMethod (GetBuilder);
6841 Parent.MemberCache.AddMember (GetBuilder, Get);
6845 PropertyBuilder.SetSetMethod (SetBuilder);
6846 Parent.MemberCache.AddMember (SetBuilder, Set);
6849 TypeManager.RegisterProperty (PropertyBuilder, this);
6850 Parent.MemberCache.AddMember (PropertyBuilder, this);
6854 public override void Emit ()
6856 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6857 Report.Error (842, Location,
6858 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6859 GetSignatureForError ());
6865 protected override PropertyInfo ResolveBaseProperty ()
6867 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6868 Parent.TypeBuilder, Name, ParametersCompiled.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6873 /// Gigantic workaround for lameness in SRE follows :
6874 /// This class derives from EventInfo and attempts to basically
6875 /// wrap around the EventBuilder so that FindMembers can quickly
6876 /// return this in it search for members
6878 public class MyEventBuilder : EventInfo {
6881 // We use this to "point" to our Builder which is
6882 // not really a MemberInfo
6884 EventBuilder MyBuilder;
6887 // We "catch" and wrap these methods
6889 MethodInfo raise, remove, add;
6891 EventAttributes attributes;
6892 Type declaring_type, reflected_type, event_type;
6897 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6899 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6901 // And now store the values in our own fields.
6903 declaring_type = type_builder;
6905 reflected_type = type_builder;
6907 attributes = event_attr;
6910 this.event_type = event_type;
6914 // Methods that you have to override. Note that you only need
6915 // to "implement" the variants that take the argument (those are
6916 // the "abstract" methods, the others (GetAddMethod()) are
6919 public override MethodInfo GetAddMethod (bool nonPublic)
6924 public override MethodInfo GetRemoveMethod (bool nonPublic)
6929 public override MethodInfo GetRaiseMethod (bool nonPublic)
6935 // These methods make "MyEventInfo" look like a Builder
6937 public void SetRaiseMethod (MethodBuilder raiseMethod)
6939 raise = raiseMethod;
6940 MyBuilder.SetRaiseMethod (raiseMethod);
6943 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6945 remove = removeMethod;
6946 MyBuilder.SetRemoveOnMethod (removeMethod);
6949 public void SetAddOnMethod (MethodBuilder addMethod)
6952 MyBuilder.SetAddOnMethod (addMethod);
6955 public void SetCustomAttribute (CustomAttributeBuilder cb)
6957 MyBuilder.SetCustomAttribute (cb);
6960 public override object [] GetCustomAttributes (bool inherit)
6962 // FIXME : There's nothing which can be seemingly done here because
6963 // we have no way of getting at the custom attribute objects of the
6968 public override object [] GetCustomAttributes (Type t, bool inherit)
6970 // FIXME : Same here !
6974 public override bool IsDefined (Type t, bool b)
6979 public override EventAttributes Attributes {
6985 public override string Name {
6991 public override Type DeclaringType {
6993 return declaring_type;
6997 public override Type ReflectedType {
6999 return reflected_type;
7003 public Type EventType {
7009 public void SetUsed ()
7011 if (my_event != null) {
7012 // my_event.SetAssigned ();
7013 my_event.SetMemberIsUsed ();
7019 /// For case when event is declared like property (with add and remove accessors).
7021 public class EventProperty: Event {
7022 abstract class AEventPropertyAccessor : AEventAccessor
7024 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7025 base (method, accessor, prefix)
7029 public override MethodBuilder Define (DeclSpace ds)
7031 CheckAbstractAndExtern (block != null);
7032 return base.Define (ds);
7035 public override string GetSignatureForError ()
7037 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7041 sealed class AddDelegateMethod: AEventPropertyAccessor
7043 public AddDelegateMethod (Event method, Accessor accessor):
7044 base (method, accessor, AddPrefix)
7049 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7051 public RemoveDelegateMethod (Event method, Accessor accessor):
7052 base (method, accessor, RemovePrefix)
7058 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7060 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7062 Attributes attrs, Accessor add, Accessor remove)
7063 : base (parent, type, mod_flags, name, attrs)
7065 Add = new AddDelegateMethod (this, add);
7066 Remove = new RemoveDelegateMethod (this, remove);
7069 public override bool Define()
7071 if (!base.Define ())
7078 public override string[] ValidAttributeTargets {
7080 return attribute_targets;
7086 /// Event is declared like field.
7088 public class EventField : Event {
7089 abstract class EventFieldAccessor : AEventAccessor
7091 protected EventFieldAccessor (Event method, string prefix)
7092 : base (method, prefix)
7096 public override void Emit (DeclSpace parent)
7098 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
7099 if (parent is Class) {
7100 MethodBuilder mb = method_data.MethodBuilder;
7101 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7104 // TODO: because we cannot use generics yet
7105 FieldInfo field_info = ((EventField) method).BackingField.FieldBuilder;
7106 FieldExpr f_expr = new FieldExpr (field_info, Location);
7107 if ((method.ModFlags & Modifiers.STATIC) == 0)
7108 f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.FieldType, Location);
7110 block = new ToplevelBlock (ParameterInfo, Location);
7111 block.AddStatement (new StatementExpression (
7112 new CompoundAssign (Operation,
7114 block.GetParameterReference (ParameterInfo[0].Name, Location))));
7120 protected abstract Binary.Operator Operation { get; }
7123 sealed class AddDelegateMethod: EventFieldAccessor
7125 public AddDelegateMethod (Event method):
7126 base (method, AddPrefix)
7130 protected override Binary.Operator Operation {
7131 get { return Binary.Operator.Addition; }
7135 sealed class RemoveDelegateMethod: EventFieldAccessor
7137 public RemoveDelegateMethod (Event method):
7138 base (method, RemovePrefix)
7142 protected override Binary.Operator Operation {
7143 get { return Binary.Operator.Subtraction; }
7148 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7149 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7151 public Field BackingField;
7152 public Expression Initializer;
7154 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7155 : base (parent, type, mod_flags, name, attrs)
7157 Add = new AddDelegateMethod (this);
7158 Remove = new RemoveDelegateMethod (this);
7161 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
7163 if (a.Target == AttributeTargets.Field) {
7164 BackingField.ApplyAttributeBuilder (a, cb, pa);
7168 if (a.Target == AttributeTargets.Method) {
7169 int errors = Report.Errors;
7170 Add.ApplyAttributeBuilder (a, cb, pa);
7171 if (errors == Report.Errors)
7172 Remove.ApplyAttributeBuilder (a, cb, pa);
7176 base.ApplyAttributeBuilder (a, cb, pa);
7179 public override bool Define()
7181 if (!base.Define ())
7184 if (Initializer != null && (ModFlags & Modifiers.ABSTRACT) != 0) {
7185 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7186 GetSignatureForError ());
7189 if (!HasBackingField) {
7194 // FIXME: We are unable to detect whether generic event is used because
7195 // we are using FieldExpr instead of EventExpr for event access in that
7196 // case. When this issue will be fixed this hack can be removed.
7197 if (TypeManager.IsGenericType (MemberType))
7200 if (Add.IsInterfaceImplementation)
7203 TypeManager.RegisterEventField (EventBuilder, this);
7205 BackingField = new Field (Parent,
7206 new TypeExpression (MemberType, Location),
7207 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
7210 Parent.PartialContainer.AddField (BackingField);
7211 BackingField.Initializer = Initializer;
7212 BackingField.ModFlags &= ~Modifiers.COMPILER_GENERATED;
7214 // Call define because we passed fields definition
7215 return BackingField.Define ();
7218 bool HasBackingField {
7220 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
7224 public override string[] ValidAttributeTargets
7227 return HasBackingField ? attribute_targets : attribute_targets_interface;
7232 public abstract class Event : PropertyBasedMember {
7233 public abstract class AEventAccessor : AbstractPropertyEventMethod
7235 protected readonly Event method;
7236 ImplicitParameter param_attr;
7238 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7240 public const string AddPrefix = "add_";
7241 public const string RemovePrefix = "remove_";
7243 protected AEventAccessor (Event method, string prefix)
7244 : base (method, prefix)
7246 this.method = method;
7247 this.ModFlags = method.ModFlags;
7250 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7251 : base (method, accessor, prefix)
7253 this.method = method;
7254 this.ModFlags = method.ModFlags;
7257 public bool IsInterfaceImplementation {
7258 get { return method_data.implementing != null; }
7261 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
7263 if (a.IsInternalMethodImplAttribute) {
7264 method.is_external_implementation = true;
7267 base.ApplyAttributeBuilder (a, cb, pa);
7270 protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
7272 if (a.Target == AttributeTargets.Parameter) {
7273 if (param_attr == null)
7274 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7276 param_attr.ApplyAttributeBuilder (a, cb, pa);
7280 base.ApplyAttributeBuilder (a, cb, pa);
7283 public override AttributeTargets AttributeTargets {
7285 return AttributeTargets.Method;
7289 public override bool IsClsComplianceRequired ()
7291 return method.IsClsComplianceRequired ();
7294 public virtual MethodBuilder Define (DeclSpace parent)
7296 method_data = new MethodData (method, method.ModFlags,
7297 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7299 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7302 MethodBuilder mb = method_data.MethodBuilder;
7303 ParameterInfo.ApplyAttributes (mb);
7307 public override Type ReturnType {
7309 return TypeManager.void_type;
7313 public override EmitContext CreateEmitContext (ILGenerator ig)
7315 return new EmitContext (
7316 this, ig, ReturnType);
7319 public override ObsoleteAttribute GetObsoleteAttribute ()
7321 return method.GetObsoleteAttribute ();
7324 public override string[] ValidAttributeTargets {
7326 return attribute_targets;
7330 public override ParametersCompiled ParameterInfo {
7332 return method.parameters;
7338 const int AllowedModifiers =
7341 Modifiers.PROTECTED |
7342 Modifiers.INTERNAL |
7347 Modifiers.OVERRIDE |
7349 Modifiers.ABSTRACT |
7352 const int AllowedInterfaceModifiers =
7355 public AEventAccessor Add, Remove;
7356 public MyEventBuilder EventBuilder;
7357 public MethodBuilder AddBuilder, RemoveBuilder;
7359 ParametersCompiled parameters;
7361 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7362 : base (parent, null, type, mod_flags,
7363 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7368 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
7370 if ((a.HasSecurityAttribute)) {
7371 a.Error_InvalidSecurityParent ();
7375 EventBuilder.SetCustomAttribute (cb);
7378 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7380 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7383 public override AttributeTargets AttributeTargets {
7385 return AttributeTargets.Event;
7389 public override bool Define ()
7391 if (!base.Define ())
7394 if (!TypeManager.IsDelegateType (MemberType)) {
7395 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7398 parameters = ParametersCompiled.CreateFullyResolved (
7399 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7404 if (TypeManager.delegate_combine_delegate_delegate == null) {
7405 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7406 TypeManager.delegate_type, "Combine", Location,
7407 TypeManager.delegate_type, TypeManager.delegate_type);
7409 if (TypeManager.delegate_remove_delegate_delegate == null) {
7410 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7411 TypeManager.delegate_type, "Remove", Location,
7412 TypeManager.delegate_type, TypeManager.delegate_type);
7416 // Now define the accessors
7419 AddBuilder = Add.Define (Parent);
7420 if (AddBuilder == null)
7423 RemoveBuilder = Remove.Define (Parent);
7424 if (RemoveBuilder == null)
7427 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7428 EventBuilder.SetAddOnMethod (AddBuilder);
7429 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7431 Parent.MemberCache.AddMember (EventBuilder, this);
7432 Parent.MemberCache.AddMember (AddBuilder, Add);
7433 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7438 public override void Emit ()
7440 if (OptAttributes != null) {
7441 OptAttributes.Emit ();
7445 Remove.Emit (Parent);
7450 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7452 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7453 Parent.TypeBuilder, Name);
7458 AParametersCollection pd = TypeManager.GetParameterData (mi);
7459 base_ret_type = pd.Types [0];
7464 // Represents header string for documentation comment.
7466 public override string DocCommentHeader {
7467 get { return "E:"; }
7472 public class Indexer : PropertyBase
7474 public class GetIndexerMethod : GetMethod
7476 ParametersCompiled parameters;
7478 public GetIndexerMethod (Indexer method):
7481 this.parameters = method.parameters;
7484 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7485 base (method, accessor)
7487 parameters = accessor.Parameters;
7490 public override MethodBuilder Define (DeclSpace parent)
7492 parameters.Resolve (this);
7493 return base.Define (parent);
7496 public override bool EnableOverloadChecks (MemberCore overload)
7498 if (base.EnableOverloadChecks (overload)) {
7499 overload.caching_flags |= Flags.MethodOverloadsExist;
7506 public override ParametersCompiled ParameterInfo {
7513 public class SetIndexerMethod: SetMethod
7515 public SetIndexerMethod (Indexer method):
7518 parameters = ParametersCompiled.MergeGenerated (method.parameters, false, parameters [0], null);
7521 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7522 base (method, accessor)
7524 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7527 public override bool EnableOverloadChecks (MemberCore overload)
7529 if (base.EnableOverloadChecks (overload)) {
7530 overload.caching_flags |= Flags.MethodOverloadsExist;
7538 const int AllowedModifiers =
7541 Modifiers.PROTECTED |
7542 Modifiers.INTERNAL |
7546 Modifiers.OVERRIDE |
7551 const int AllowedInterfaceModifiers =
7554 public readonly ParametersCompiled parameters;
7556 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7557 ParametersCompiled parameters, Attributes attrs,
7558 Accessor get_block, Accessor set_block, bool define_set_first)
7559 : base (parent, type, mod,
7560 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7561 name, attrs, define_set_first)
7563 this.parameters = parameters;
7565 if (get_block == null)
7566 Get = new GetIndexerMethod (this);
7568 Get = new GetIndexerMethod (this, get_block);
7570 if (set_block == null)
7571 Set = new SetIndexerMethod (this);
7573 Set = new SetIndexerMethod (this, set_block);
7576 protected override bool CheckForDuplications ()
7578 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7581 public override bool Define ()
7583 if (!base.Define ())
7586 if (!DefineParameters (parameters))
7589 if (OptAttributes != null) {
7590 Attribute indexer_attr = OptAttributes.Search (PredefinedAttributes.Get.IndexerName);
7591 if (indexer_attr != null) {
7592 // Remove the attribute from the list because it is not emitted
7593 OptAttributes.Attrs.Remove (indexer_attr);
7595 string name = indexer_attr.GetIndexerAttributeValue ();
7601 if (IsExplicitImpl) {
7602 Report.Error (415, indexer_attr.Location,
7603 "The `IndexerName' attribute is valid only on an " +
7604 "indexer that is not an explicit interface member declaration");
7608 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7609 Report.Error (609, indexer_attr.Location,
7610 "Cannot set the `IndexerName' attribute on an indexer marked override");
7616 if (InterfaceType != null) {
7617 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7618 if (base_IndexerName != Name)
7619 ShortName = base_IndexerName;
7622 if (!Parent.PartialContainer.AddMember (this) ||
7623 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7626 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7628 if (!DefineAccessors ())
7635 // Now name the parameters
7637 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7638 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7641 PropertyBuilder.SetGetMethod (GetBuilder);
7642 Parent.MemberCache.AddMember (GetBuilder, Get);
7646 PropertyBuilder.SetSetMethod (SetBuilder);
7647 Parent.MemberCache.AddMember (SetBuilder, Set);
7650 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7651 Parent.MemberCache.AddMember (PropertyBuilder, this);
7655 public override bool EnableOverloadChecks (MemberCore overload)
7657 if (overload is Indexer) {
7658 caching_flags |= Flags.MethodOverloadsExist;
7662 return base.EnableOverloadChecks (overload);
7665 public override string GetDocCommentName (DeclSpace ds)
7667 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7670 public override string GetSignatureForError ()
7672 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7673 if (MemberName.Left != null) {
7675 sb.Append (MemberName.Left.GetSignatureForError ());
7678 sb.Append (".this");
7679 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7680 return sb.ToString ();
7683 protected override PropertyInfo ResolveBaseProperty ()
7685 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7686 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7689 protected override bool VerifyClsCompliance ()
7691 if (!base.VerifyClsCompliance ())
7694 parameters.VerifyClsCompliance ();
7699 public class Operator : MethodOrOperator {
7701 const int AllowedModifiers =
7707 public enum OpType : byte {
7717 // Unary and Binary operators
7740 // Implicit and Explicit
7744 // Just because of enum
7748 public readonly OpType OperatorType;
7750 static readonly string [] [] names;
7754 names = new string[(int)OpType.TOP][];
7755 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7756 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7757 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7758 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7759 names [(int) OpType.True] = new string [] { "true", "op_True" };
7760 names [(int) OpType.False] = new string [] { "false", "op_False" };
7761 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7762 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7763 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7764 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7765 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7766 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7767 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7768 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7769 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7770 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7771 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7772 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7773 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7774 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7775 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7776 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7777 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7778 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7779 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7780 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7783 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7784 int mod_flags, ParametersCompiled parameters,
7785 ToplevelBlock block, Attributes attrs, Location loc)
7786 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7787 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7789 OperatorType = type;
7793 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
7795 if (a.Type == pa.Conditional) {
7796 Error_ConditionalAttributeIsNotValid ();
7800 base.ApplyAttributeBuilder (a, cb, pa);
7803 public override bool Define ()
7805 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7806 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7807 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7810 if (!base.Define ())
7813 // imlicit and explicit operator of same types are not allowed
7814 if (OperatorType == OpType.Explicit)
7815 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7816 else if (OperatorType == OpType.Implicit)
7817 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7819 Type declaring_type = MethodData.DeclaringType;
7820 Type return_type = MemberType;
7821 Type first_arg_type = ParameterTypes [0];
7823 Type first_arg_type_unwrap = first_arg_type;
7824 if (TypeManager.IsNullableType (first_arg_type))
7825 first_arg_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (first_arg_type) [0]);
7827 Type return_type_unwrap = return_type;
7828 if (TypeManager.IsNullableType (return_type))
7829 return_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (return_type) [0]);
7831 if (TypeManager.IsDynamicType (return_type) || TypeManager.IsDynamicType (first_arg_type)) {
7832 Report.Error (1964, Location,
7833 "User-defined operator `{0}' cannot convert to or from the dynamic type",
7834 GetSignatureForError ());
7840 // Rules for conversion operators
7842 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7843 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7844 Report.Error (555, Location,
7845 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7850 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7851 conv_type = first_arg_type;
7852 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7853 conv_type = return_type;
7855 Report.Error (556, Location,
7856 "User-defined conversion must convert to or from the enclosing type");
7861 // Because IsInterface and IsClass are not supported
7863 if (!TypeManager.IsGenericParameter (conv_type)) {
7864 if (conv_type.IsInterface) {
7865 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7866 GetSignatureForError ());
7870 if (conv_type.IsClass) {
7871 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7872 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7873 GetSignatureForError ());
7877 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7878 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7879 GetSignatureForError ());
7884 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7885 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7886 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");
7889 } else if (Parameters.Count == 1) {
7890 // Checks for Unary operators
7892 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7893 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7894 Report.Error (448, Location,
7895 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7898 if (first_arg_type != declaring_type) {
7900 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7905 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7906 Report.Error (562, Location,
7907 "The parameter type of a unary operator must be the containing type");
7911 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7912 if (return_type != TypeManager.bool_type){
7915 "The return type of operator True or False " +
7922 // Checks for Binary operators
7924 if (first_arg_type != declaring_type &&
7925 Parameters.Types [1] != declaring_type){
7928 "One of the parameters of a binary operator must " +
7929 "be the containing type");
7937 protected override bool ResolveMemberType ()
7939 if (!base.ResolveMemberType ())
7942 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7946 // Operator cannot be override
7947 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7952 public static string GetName (OpType ot)
7954 return names [(int) ot] [0];
7957 public static string GetName (string metadata_name)
7959 for (int i = 0; i < names.Length; ++i) {
7960 if (names [i] [1] == metadata_name)
7961 return names [i] [0];
7966 public static string GetMetadataName (OpType ot)
7968 return names [(int) ot] [1];
7971 public static string GetMetadataName (string name)
7973 for (int i = 0; i < names.Length; ++i) {
7974 if (names [i] [0] == name)
7975 return names [i] [1];
7980 public OpType GetMatchingOperator ()
7982 switch (OperatorType) {
7983 case OpType.Equality:
7984 return OpType.Inequality;
7985 case OpType.Inequality:
7986 return OpType.Equality;
7988 return OpType.False;
7991 case OpType.GreaterThan:
7992 return OpType.LessThan;
7993 case OpType.LessThan:
7994 return OpType.GreaterThan;
7995 case OpType.GreaterThanOrEqual:
7996 return OpType.LessThanOrEqual;
7997 case OpType.LessThanOrEqual:
7998 return OpType.GreaterThanOrEqual;
8004 public override string GetSignatureForError ()
8006 StringBuilder sb = new StringBuilder ();
8007 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8008 sb.AppendFormat ("{0}.{1} operator {2}",
8009 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
8012 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8015 sb.Append (Parameters.GetSignatureForError ());
8016 return sb.ToString ();
8021 // This is used to compare method signatures
8023 struct MethodSignature {
8025 public Type RetType;
8026 public Type [] Parameters;
8029 /// This delegate is used to extract methods which have the
8030 /// same signature as the argument
8032 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8034 public MethodSignature (string name, Type ret_type, Type [] parameters)
8039 if (parameters == null)
8040 Parameters = Type.EmptyTypes;
8042 Parameters = parameters;
8045 public override string ToString ()
8048 if (Parameters.Length != 0){
8049 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8050 for (int i = 0; i < Parameters.Length; i++){
8051 sb.Append (Parameters [i]);
8052 if (i+1 < Parameters.Length)
8055 pars = sb.ToString ();
8058 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8061 public override int GetHashCode ()
8063 return Name.GetHashCode ();
8066 public override bool Equals (Object o)
8068 MethodSignature other = (MethodSignature) o;
8070 if (other.Name != Name)
8073 if (other.RetType != RetType)
8076 if (Parameters == null){
8077 if (other.Parameters == null)
8082 if (other.Parameters == null)
8085 int c = Parameters.Length;
8086 if (other.Parameters.Length != c)
8089 for (int i = 0; i < c; i++)
8090 if (other.Parameters [i] != Parameters [i])
8096 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8098 MethodSignature sig = (MethodSignature) filter_criteria;
8100 if (m.Name != sig.Name)
8104 MethodInfo mi = m as MethodInfo;
8105 PropertyInfo pi = m as PropertyInfo;
8108 ReturnType = mi.ReturnType;
8109 else if (pi != null)
8110 ReturnType = pi.PropertyType;
8115 // we use sig.RetType == null to mean `do not check the
8116 // method return value.
8118 if (sig.RetType != null) {
8119 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8125 args = TypeManager.GetParameterData (mi).Types;
8127 args = TypeManager.GetParameterData (pi).Types;
8128 Type [] sigp = sig.Parameters;
8130 if (args.Length != sigp.Length)
8133 for (int i = args.Length - 1; i >= 0; i--)
8134 if (!TypeManager.IsEqual (args [i], sigp [i]))