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 ();
161 GetHashCode = 1 << 1,
162 HasStaticFieldInitializer = 1 << 2
166 // Whether this is a struct, class or interface
167 public readonly Kind Kind;
169 // Holds a list of classes and structures
170 protected ArrayList types;
172 MemberCoreArrayList ordered_explicit_member_list;
173 MemberCoreArrayList ordered_member_list;
175 // Holds the list of properties
176 MemberCoreArrayList properties;
178 // Holds the list of delegates
179 MemberCoreArrayList delegates;
181 // Holds the list of constructors
182 protected MemberCoreArrayList instance_constructors;
184 // Holds the list of fields
185 protected MemberCoreArrayList fields;
187 // Holds a list of fields that have initializers
188 protected ArrayList initialized_fields;
190 // Holds a list of static fields that have initializers
191 protected ArrayList initialized_static_fields;
193 // Holds the list of constants
194 protected MemberCoreArrayList constants;
196 // Holds the methods.
197 MemberCoreArrayList methods;
200 protected MemberCoreArrayList events;
202 // Holds the indexers
205 // Holds the operators
206 MemberCoreArrayList operators;
208 // Holds the compiler generated classes
209 ArrayList compiler_generated;
212 // Pointers to the default constructor and the default static constructor
214 protected Constructor default_constructor;
215 protected Constructor default_static_constructor;
218 // Points to the first non-static field added to the container.
220 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
221 // and the first one's as good as any.
223 FieldBase first_nonstatic_field = null;
226 // This one is computed after we can distinguish interfaces
227 // from classes from the arraylist `type_bases'
230 TypeExpr[] iface_exprs;
233 GenericTypeParameterBuilder[] nested_gen_params;
236 protected ArrayList type_bases;
238 protected bool members_defined;
239 bool members_defined_ok;
241 // The interfaces we implement.
242 protected Type[] ifaces;
244 // The base member cache and our member cache
245 MemberCache base_cache;
246 protected MemberCache member_cache;
248 public const string DefaultIndexerName = "Item";
250 private bool seen_normal_indexers = false;
251 private string indexer_name = DefaultIndexerName;
252 protected bool requires_delayed_unmanagedtype_check;
254 private CachedMethods cached_method;
256 ArrayList partial_parts;
259 /// The pending methods that need to be implemented
260 // (interfaces or abstract methods)
262 PendingImplementation pending;
264 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
265 Attributes attrs, Kind kind)
266 : base (ns, parent, name, attrs)
268 if (parent != null && parent.NamespaceEntry != ns)
269 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
272 this.PartialContainer = this;
275 public bool AddMember (MemberCore symbol)
277 return AddToContainer (symbol, symbol.MemberName.Basename);
280 protected virtual bool AddMemberType (DeclSpace ds)
282 return AddToContainer (ds, ds.Basename);
285 protected virtual void RemoveMemberType (DeclSpace ds)
287 RemoveFromContainer (ds.Basename);
290 public void AddConstant (Const constant)
292 if (!AddMember (constant))
295 if (constants == null)
296 constants = new MemberCoreArrayList ();
298 constants.Add (constant);
301 public TypeContainer AddTypeContainer (TypeContainer tc)
303 if (!AddMemberType (tc))
307 types = new MemberCoreArrayList ();
313 public virtual TypeContainer AddPartial (TypeContainer next_part)
315 return AddPartial (next_part, next_part.Basename);
318 protected TypeContainer AddPartial (TypeContainer next_part, string name)
320 next_part.ModFlags |= Modifiers.PARTIAL;
321 TypeContainer tc = defined_names [name] as TypeContainer;
324 return AddTypeContainer (next_part);
326 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
327 Report.SymbolRelatedToPreviousError (next_part);
328 Error_MissingPartialModifier (tc);
331 if (tc.Kind != next_part.Kind) {
332 Report.SymbolRelatedToPreviousError (tc);
333 Report.Error (261, next_part.Location,
334 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
335 next_part.GetSignatureForError ());
338 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
339 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
340 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
341 Report.SymbolRelatedToPreviousError (tc);
342 Report.Error (262, next_part.Location,
343 "Partial declarations of `{0}' have conflicting accessibility modifiers",
344 next_part.GetSignatureForError ());
347 if (tc.partial_parts == null)
348 tc.partial_parts = new ArrayList (1);
350 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
351 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
352 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
353 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
354 tc.ModFlags |= next_part.ModFlags;
356 tc.ModFlags |= next_part.ModFlags;
359 if (next_part.attributes != null) {
360 if (tc.attributes == null)
361 tc.attributes = next_part.attributes;
363 tc.attributes.AddAttributes (next_part.attributes.Attrs);
366 next_part.PartialContainer = tc;
367 tc.partial_parts.Add (next_part);
371 public virtual void RemoveTypeContainer (TypeContainer next_part)
374 types.Remove (next_part);
375 RemoveMemberType (next_part);
378 public void AddDelegate (Delegate d)
380 if (!AddMemberType (d))
383 if (delegates == null)
384 delegates = new MemberCoreArrayList ();
389 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
391 if (ordered_explicit_member_list == null) {
392 ordered_explicit_member_list = new MemberCoreArrayList ();
393 ordered_member_list = new MemberCoreArrayList ();
397 if (Kind == Kind.Interface) {
398 Report.Error (541, mc.Location,
399 "`{0}': explicit interface declaration can only be declared in a class or struct",
400 mc.GetSignatureForError ());
403 ordered_explicit_member_list.Add (mc);
404 alist.Insert (0, mc);
406 ordered_member_list.Add (mc);
412 public void AddMethod (MethodOrOperator method)
414 if (!AddToContainer (method, method.MemberName.Basename))
418 methods = new MemberCoreArrayList ();
420 if (method.MemberName.Left != null)
421 AddMemberToList (method, methods, true);
423 AddMemberToList (method, methods, false);
426 public void AddConstructor (Constructor c)
428 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
429 if (!AddToContainer (c, is_static ?
430 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
433 if (is_static && c.Parameters.IsEmpty){
434 if (default_static_constructor != null) {
435 Report.SymbolRelatedToPreviousError (default_static_constructor);
436 Report.Error (111, c.Location,
437 "A member `{0}' is already defined. Rename this member or use different parameter types",
438 c.GetSignatureForError ());
442 default_static_constructor = c;
444 if (c.Parameters.IsEmpty)
445 default_constructor = c;
447 if (instance_constructors == null)
448 instance_constructors = new MemberCoreArrayList ();
450 instance_constructors.Add (c);
454 public bool AddField (FieldBase field)
456 if (!AddMember (field))
460 fields = new MemberCoreArrayList ();
464 if ((field.ModFlags & Modifiers.STATIC) != 0)
467 if (first_nonstatic_field == null) {
468 first_nonstatic_field = field;
472 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
473 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
474 Report.Warning (282, 3, field.Location,
475 "struct instance field `{0}' found in different declaration from instance field `{1}'",
476 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
481 public void AddProperty (Property prop)
483 if (!AddMember (prop) ||
484 !AddMember (prop.Get) || !AddMember (prop.Set))
487 if (properties == null)
488 properties = new MemberCoreArrayList ();
490 if (prop.MemberName.Left != null)
491 AddMemberToList (prop, properties, true);
493 AddMemberToList (prop, properties, false);
496 public void AddEvent (Event e)
501 if (e is EventProperty) {
502 if (!AddMember (e.Add))
505 if (!AddMember (e.Remove))
510 events = new MemberCoreArrayList ();
516 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
518 public void AddIndexer (Indexer i)
520 if (indexers == null)
521 indexers = new ArrayList ();
523 if (i.IsExplicitImpl)
524 AddMemberToList (i, indexers, true);
526 AddMemberToList (i, indexers, false);
529 public void AddOperator (Operator op)
534 if (operators == null)
535 operators = new OperatorArrayList (this);
540 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
542 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
544 if (compiler_generated == null)
545 compiler_generated = new ArrayList ();
547 compiler_generated.Add (c);
550 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
552 if (a.Type == TypeManager.default_member_type) {
553 if (Indexers != null) {
554 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
559 base.ApplyAttributeBuilder (a, cb);
562 public override AttributeTargets AttributeTargets {
564 throw new NotSupportedException ();
568 public ArrayList Types {
574 public MemberCoreArrayList Methods {
580 public ArrayList Constants {
586 protected Type BaseType {
588 return TypeBuilder.BaseType;
592 public ArrayList Fields {
598 public ArrayList InstanceConstructors {
600 return instance_constructors;
604 public ArrayList Properties {
610 public ArrayList Events {
616 public ArrayList Indexers {
622 public ArrayList Operators {
628 public ArrayList Delegates {
634 protected override TypeAttributes TypeAttr {
636 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
640 public string IndexerName {
642 return indexers == null ? DefaultIndexerName : indexer_name;
646 public bool IsComImport {
648 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
651 return OptAttributes.Contains (TypeManager.comimport_attr_type);
655 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
657 if ((field.ModFlags & Modifiers.STATIC) != 0){
658 if (initialized_static_fields == null) {
659 PartialContainer.HasStaticFieldInitializer = true;
660 initialized_static_fields = new ArrayList (4);
663 initialized_static_fields.Add (expression);
665 if (initialized_fields == null)
666 initialized_fields = new ArrayList (4);
668 initialized_fields.Add (expression);
672 public void ResolveFieldInitializers (EmitContext ec)
674 if (partial_parts != null) {
675 foreach (TypeContainer part in partial_parts) {
676 part.DoResolveFieldInitializers (ec);
679 DoResolveFieldInitializers (ec);
682 void DoResolveFieldInitializers (EmitContext ec)
685 if (initialized_static_fields == null)
688 bool has_complex_initializer = !RootContext.Optimize;
690 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
691 for (i = 0; i < initialized_static_fields.Count; ++i) {
692 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
693 ExpressionStatement s = fi.ResolveStatement (ec);
695 s = EmptyExpressionStatement.Instance;
696 } else if (fi.IsComplexInitializer) {
697 has_complex_initializer |= true;
703 for (i = 0; i < initialized_static_fields.Count; ++i) {
704 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
706 // Need special check to not optimize code like this
707 // static int a = b = 5;
710 if (!has_complex_initializer && fi.IsDefaultInitializer)
713 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
719 if (initialized_fields == null)
722 for (int i = 0; i < initialized_fields.Count; ++i) {
723 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
724 ExpressionStatement s = fi.ResolveStatement (ec);
729 // Field is re-initialized to its default value => removed
731 if (fi.IsDefaultInitializer && RootContext.Optimize)
734 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
739 // Emits the instance field initializers
741 public bool EmitFieldInitializers (EmitContext ec)
743 if (partial_parts != null) {
744 foreach (TypeContainer part in partial_parts)
745 part.EmitFieldInitializers (ec);
751 fields = initialized_static_fields;
753 fields = initialized_fields;
759 foreach (FieldInitializer f in fields) {
760 f.EmitStatement (ec);
765 public override string DocComment {
777 public PendingImplementation PendingImplementations {
778 get { return pending; }
781 public override bool GetClsCompliantAttributeValue ()
783 if (PartialContainer != this)
784 return PartialContainer.GetClsCompliantAttributeValue ();
786 return base.GetClsCompliantAttributeValue ();
789 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
791 // FIXME: get rid of partial_parts and store lists of bases of each part here
792 // assumed, not verified: 'part' is in 'partial_parts'
793 ((TypeContainer) part).type_bases = bases;
797 /// This function computes the Base class and also the
798 /// list of interfaces that the class or struct @c implements.
800 /// The return value is an array (might be null) of
801 /// interfaces implemented (as Types).
803 /// The @base_class argument is set to the base object or null
804 /// if this is `System.Object'.
806 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
809 if (type_bases == null)
812 int count = type_bases.Count;
813 TypeExpr [] ifaces = null;
814 for (int i = 0, j = 0; i < count; i++){
815 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
818 // Standard ResolveAsTypeTerminal cannot be used in this case because
819 // it does ObsoleteAttribute and constraint checks which require
820 // base type to be set
822 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
823 if (fne_resolved == null)
826 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
827 base_class = fne_resolved;
832 ifaces = new TypeExpr [count - i];
834 if (fne_resolved.Type.IsInterface) {
835 for (int ii = 0; ii < j; ++ii) {
836 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
837 Report.Error (528, Location, "`{0}' is already listed in interface list",
838 fne_resolved.GetSignatureForError ());
843 if (Kind == Kind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
844 Report.Error (61, fne.Location,
845 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
846 fne_resolved.GetSignatureForError (), GetSignatureForError ());
849 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
850 if (Kind != Kind.Class) {
851 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
852 } else if (base_class != null)
853 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
854 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
856 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
857 GetSignatureForError (), fne_resolved.GetSignatureForError ());
861 ifaces [j++] = fne_resolved;
867 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
869 ArrayList ifaces = new ArrayList (0);
870 if (iface_exprs != null)
871 ifaces.AddRange (iface_exprs);
873 foreach (TypeContainer part in partial_parts) {
874 TypeExpr new_base_class;
875 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
876 if (new_base_class != TypeManager.system_object_expr) {
877 if (base_class == TypeManager.system_object_expr)
878 base_class = new_base_class;
880 if (new_base_class != null && !new_base_class.Equals (base_class)) {
881 Report.SymbolRelatedToPreviousError (base_class.Location, "");
882 Report.Error (263, part.Location,
883 "Partial declarations of `{0}' must not specify different base classes",
884 part.GetSignatureForError ());
891 if (new_ifaces == null)
894 foreach (TypeExpr iface in new_ifaces) {
895 if (ifaces.Contains (iface))
902 if (ifaces.Count == 0)
905 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
908 bool CheckGenericInterfaces (Type[] ifaces)
911 ArrayList already_checked = new ArrayList ();
913 for (int i = 0; i < ifaces.Length; i++) {
914 Type iface = ifaces [i];
915 foreach (Type t in already_checked) {
919 Type[] inferred = new Type [CountTypeParameters];
920 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
923 Report.Error (695, Location,
924 "`{0}' cannot implement both `{1}' and `{2}' " +
925 "because they may unify for some type parameter substitutions",
926 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
927 TypeManager.CSharpName (t));
931 already_checked.Add (iface);
940 bool CreateTypeBuilder ()
943 Type default_parent = null;
944 if (Kind == Kind.Struct)
945 default_parent = TypeManager.value_type;
946 else if (Kind == Kind.Enum)
947 default_parent = TypeManager.enum_type;
950 // Sets .size to 1 for structs with no instance fields
952 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
955 if (TypeManager.NamespaceClash (Name, Location)) {
959 ModuleBuilder builder = CodeGen.Module.Builder;
960 TypeBuilder = builder.DefineType (
961 Name, TypeAttr, default_parent, type_size);
963 TypeBuilder builder = Parent.TypeBuilder;
965 TypeBuilder = builder.DefineNestedType (
966 Basename, TypeAttr, default_parent, type_size);
968 } catch (ArgumentException) {
969 Report.RuntimeMissingSupport (Location, "static classes");
973 TypeManager.AddUserType (this);
977 string[] param_names = new string [TypeParameters.Length];
978 for (int i = 0; i < TypeParameters.Length; i++)
979 param_names [i] = TypeParameters [i].Name;
981 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
983 int offset = CountTypeParameters - CurrentTypeParameters.Length;
985 nested_gen_params = new GenericTypeParameterBuilder [offset];
986 Array.Copy (gen_params, nested_gen_params, offset);
989 for (int i = offset; i < gen_params.Length; i++)
990 CurrentTypeParameters [i - offset].Define (gen_params [i]);
997 bool DefineBaseTypes ()
999 iface_exprs = ResolveBaseTypes (out base_type);
1000 if (partial_parts != null) {
1001 iface_exprs = GetNormalPartialBases (ref base_type);
1005 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1006 // which in turn should have called DefineType()s on base types if necessary.
1008 // None of the code below should trigger DefineType()s on classes that we depend on.
1009 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1011 // Let's do it as soon as possible, since code below can call DefineType() on classes
1012 // that depend on us to be populated before they are.
1014 if (!(this is CompilerGeneratedClass))
1015 RootContext.RegisterOrder (this);
1017 if (!CheckRecursiveDefinition (this))
1020 if (base_type != null && base_type.Type != null) {
1021 TypeBuilder.SetParent (base_type.Type);
1024 // add interfaces that were not added at type creation
1025 if (iface_exprs != null) {
1026 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1030 foreach (Type itype in ifaces)
1031 TypeBuilder.AddInterfaceImplementation (itype);
1033 if (!CheckGenericInterfaces (ifaces))
1036 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1043 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1045 public TypeBuilder CreateType ()
1047 if (TypeBuilder != null)
1053 if (!CreateTypeBuilder ()) {
1058 if (partial_parts != null) {
1059 foreach (TypeContainer part in partial_parts)
1060 part.TypeBuilder = TypeBuilder;
1063 if (Types != null) {
1064 foreach (TypeContainer tc in Types) {
1065 if (tc.CreateType () == null) {
1077 public override TypeBuilder DefineType ()
1084 type_defined = true;
1086 if (CreateType () == null) {
1091 if (!DefineBaseTypes ()) {
1096 if (!DefineNestedTypes ()) {
1104 public override void SetParameterInfo (ArrayList constraints_list)
1106 base.SetParameterInfo (constraints_list);
1108 if (!is_generic || PartialContainer == this)
1111 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1112 for (int i = 0; i < tc_names.Length; ++i) {
1113 if (tc_names [i].Name != type_params [i].Name) {
1114 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1115 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1116 GetSignatureForError ());
1123 void UpdateTypeParameterConstraints (TypeContainer part)
1125 TypeParameter[] current_params = CurrentTypeParameters;
1126 for (int i = 0; i < current_params.Length; i++) {
1127 Constraints c = part.CurrentTypeParameters [i].Constraints;
1131 if (current_params [i].UpdateConstraints (part, c))
1134 Report.SymbolRelatedToPreviousError (Location, "");
1135 Report.Error (265, part.Location,
1136 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1137 GetSignatureForError (), current_params [i].GetSignatureForError ());
1142 public bool ResolveType ()
1144 if (!DoResolveType ())
1147 if (compiler_generated != null) {
1148 foreach (CompilerGeneratedClass c in compiler_generated)
1149 if (!c.ResolveType ())
1156 protected virtual bool DoResolveType ()
1162 if (PartialContainer != this)
1163 throw new InternalErrorException ();
1165 TypeExpr current_type = null;
1167 foreach (TypeParameter type_param in CurrentTypeParameters) {
1168 if (!type_param.Resolve (this)) {
1174 if (partial_parts != null && is_generic) {
1175 foreach (TypeContainer part in partial_parts)
1176 UpdateTypeParameterConstraints (part);
1179 for (int i = 0; i < TypeParameters.Length; ++i) {
1181 // FIXME: Same should be done for delegates
1182 // TODO: Quite ugly way how to propagate constraints to
1185 if (nested_gen_params != null && i < nested_gen_params.Length) {
1186 TypeParameters [i].SetConstraints (nested_gen_params [i]);
1188 if (!TypeParameters [i].DefineType (this)) {
1195 // TODO: Very strange, why not simple make generic type from
1196 // current type parameters
1197 current_type = new GenericTypeExpr (this, Location);
1198 current_type = current_type.ResolveAsTypeTerminal (this, false);
1199 if (current_type == null) {
1204 CurrentType = current_type.Type;
1209 protected virtual bool DefineNestedTypes ()
1211 if (Types != null) {
1212 foreach (TypeContainer tc in Types)
1213 if (tc.DefineType () == null)
1217 if (Delegates != null) {
1218 foreach (Delegate d in Delegates)
1219 if (d.DefineType () == null)
1226 TypeContainer InTransit;
1228 protected bool CheckRecursiveDefinition (TypeContainer tc)
1230 if (InTransit != null) {
1231 Report.SymbolRelatedToPreviousError (this);
1232 if (this is Interface)
1234 529, tc.Location, "Inherited interface `{0}' causes a " +
1235 "cycle in the interface hierarchy of `{1}'",
1236 GetSignatureForError (), tc.GetSignatureForError ());
1239 146, tc.Location, "Circular base class dependency " +
1240 "involving `{0}' and `{1}'",
1241 tc.GetSignatureForError (), GetSignatureForError ());
1247 if (base_type != null && base_type.Type != null) {
1248 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1249 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1250 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1254 if (iface_exprs != null) {
1255 foreach (TypeExpr iface in iface_exprs) {
1256 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1257 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1258 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1263 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1271 /// Populates our TypeBuilder with fields and methods
1273 public override bool Define ()
1275 if (members_defined)
1276 return members_defined_ok;
1278 members_defined_ok = DoDefineMembers ();
1279 members_defined = true;
1281 return members_defined_ok;
1284 protected virtual bool DoDefineMembers ()
1286 if (iface_exprs != null) {
1287 foreach (TypeExpr iface in iface_exprs) {
1288 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1289 if ((oa != null) && !IsInObsoleteScope)
1290 AttributeTester.Report_ObsoleteMessage (
1291 oa, iface.GetSignatureForError (), Location);
1293 GenericTypeExpr ct = iface as GenericTypeExpr;
1295 if (!ct.CheckConstraints (this) || !ct.VerifyVariantTypeParameters ())
1301 if (base_type != null) {
1302 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1303 if (obsolete_attr != null && !IsInObsoleteScope)
1304 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1306 GenericTypeExpr ct = base_type as GenericTypeExpr;
1307 if ((ct != null) && !ct.CheckConstraints (this))
1310 TypeContainer baseContainer = TypeManager.LookupTypeContainer(base_type.Type);
1311 if (baseContainer != null)
1312 baseContainer.Define();
1314 member_cache = new MemberCache (base_type.Type, this);
1315 } else if (Kind == Kind.Interface) {
1316 member_cache = new MemberCache (null, this);
1317 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1318 for (int i = 0; i < ifaces.Length; ++i)
1319 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1321 member_cache = new MemberCache (null, this);
1325 foreach (TypeContainer tc in types)
1326 member_cache.AddNestedType (tc);
1328 if (delegates != null)
1329 foreach (Delegate d in delegates)
1330 member_cache.AddNestedType (d);
1332 if (partial_parts != null) {
1333 foreach (TypeContainer part in partial_parts)
1334 part.member_cache = member_cache;
1338 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1339 if (conflict_symbol == null) {
1340 if ((ModFlags & Modifiers.NEW) != 0)
1341 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1343 if ((ModFlags & Modifiers.NEW) == 0) {
1344 Report.SymbolRelatedToPreviousError (conflict_symbol);
1345 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1346 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1351 DefineContainerMembers (constants);
1352 DefineContainerMembers (fields);
1354 if (Kind == Kind.Struct || Kind == Kind.Class) {
1355 pending = PendingImplementation.GetPendingImplementations (this);
1357 if (requires_delayed_unmanagedtype_check) {
1358 requires_delayed_unmanagedtype_check = false;
1359 foreach (Field f in fields) {
1360 if (f.MemberType != null && f.MemberType.IsPointer)
1361 TypeManager.VerifyUnManaged (f.MemberType, f.Location);
1367 // Constructors are not in the defined_names array
1369 DefineContainerMembers (instance_constructors);
1371 DefineContainerMembers (events);
1372 DefineContainerMembers (ordered_explicit_member_list);
1373 DefineContainerMembers (ordered_member_list);
1375 DefineContainerMembers (operators);
1376 DefineContainerMembers (delegates);
1378 ComputeIndexerName();
1379 CheckEqualsAndGetHashCode();
1381 if (CurrentType != null) {
1382 GenericType = CurrentType;
1387 // FIXME: This hack is needed because member cache does not work
1388 // with generic types, we rely on runtime to inflate dynamic types.
1389 // TODO: This hack requires member cache refactoring to be removed
1391 if (TypeBuilder.IsGenericType)
1392 member_cache = new MemberCache (this);
1398 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1401 mcal.DefineContainerMembers ();
1404 protected virtual void ComputeIndexerName ()
1406 if (indexers == null)
1409 string class_indexer_name = null;
1412 // If there's both an explicit and an implicit interface implementation, the
1413 // explicit one actually implements the interface while the other one is just
1414 // a normal indexer. See bug #37714.
1417 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1418 foreach (Indexer i in indexers) {
1419 if (i.InterfaceType != null) {
1420 if (seen_normal_indexers)
1421 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1425 seen_normal_indexers = true;
1427 if (class_indexer_name == null) {
1428 class_indexer_name = i.ShortName;
1432 if (i.ShortName != class_indexer_name)
1433 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");
1436 if (class_indexer_name != null)
1437 indexer_name = class_indexer_name;
1440 protected virtual void EmitIndexerName ()
1442 if (!seen_normal_indexers)
1445 if (TypeManager.default_member_ctor == null) {
1446 if (TypeManager.default_member_type == null) {
1447 TypeManager.default_member_type = TypeManager.CoreLookupType (
1448 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1450 if (TypeManager.default_member_type == null)
1454 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1455 TypeManager.default_member_type, Location, TypeManager.string_type);
1457 if (TypeManager.default_member_ctor == null)
1461 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1462 TypeBuilder.SetCustomAttribute (cb);
1465 protected virtual void CheckEqualsAndGetHashCode ()
1467 if (methods == null)
1470 if (HasEquals && !HasGetHashCode) {
1471 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1475 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1477 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1481 /// This function is based by a delegate to the FindMembers routine
1483 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1489 /// This filter is used by FindMembers, and we just keep
1490 /// a global for the filter to `AlwaysAccept'
1492 static MemberFilter accepting_filter;
1495 static TypeContainer ()
1497 accepting_filter = new MemberFilter (AlwaysAccept);
1500 public MethodInfo[] GetMethods ()
1502 ArrayList members = new ArrayList ();
1506 if (methods != null) {
1507 int len = methods.Count;
1508 for (int i = 0; i < len; i++) {
1509 Method m = (Method) methods [i];
1511 members.Add (m.MethodBuilder);
1515 if (operators != null) {
1516 int len = operators.Count;
1517 for (int i = 0; i < len; i++) {
1518 Operator o = (Operator) operators [i];
1520 members.Add (o.MethodBuilder);
1524 if (properties != null) {
1525 int len = properties.Count;
1526 for (int i = 0; i < len; i++) {
1527 Property p = (Property) properties [i];
1529 if (p.GetBuilder != null)
1530 members.Add (p.GetBuilder);
1531 if (p.SetBuilder != null)
1532 members.Add (p.SetBuilder);
1536 if (indexers != null) {
1537 int len = indexers.Count;
1538 for (int i = 0; i < len; i++) {
1539 Indexer ix = (Indexer) indexers [i];
1541 if (ix.GetBuilder != null)
1542 members.Add (ix.GetBuilder);
1543 if (ix.SetBuilder != null)
1544 members.Add (ix.SetBuilder);
1548 if (events != null) {
1549 int len = events.Count;
1550 for (int i = 0; i < len; i++) {
1551 Event e = (Event) events [i];
1553 if (e.AddBuilder != null)
1554 members.Add (e.AddBuilder);
1555 if (e.RemoveBuilder != null)
1556 members.Add (e.RemoveBuilder);
1560 MethodInfo[] retMethods = new MethodInfo [members.Count];
1561 members.CopyTo (retMethods, 0);
1565 // Indicated whether container has StructLayout attribute set Explicit
1566 public bool HasExplicitLayout {
1567 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1568 set { caching_flags |= Flags.HasExplicitLayout; }
1571 public bool HasStructLayout {
1572 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1573 set { caching_flags |= Flags.HasStructLayout; }
1577 // Return the nested type with name @name. Ensures that the nested type
1578 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1580 public Type FindNestedType (string name)
1582 if (PartialContainer != this)
1583 throw new InternalErrorException ("should not happen");
1585 ArrayList [] lists = { types, delegates };
1587 for (int j = 0; j < lists.Length; ++j) {
1588 ArrayList list = lists [j];
1592 int len = list.Count;
1593 for (int i = 0; i < len; ++i) {
1594 DeclSpace ds = (DeclSpace) list [i];
1595 if (ds.Basename == name) {
1596 return ds.DefineType ();
1604 private void FindMembers_NestedTypes (int modflags,
1605 BindingFlags bf, MemberFilter filter, object criteria,
1606 ref ArrayList members)
1608 ArrayList [] lists = { types, delegates };
1610 for (int j = 0; j < lists.Length; ++j) {
1611 ArrayList list = lists [j];
1615 int len = list.Count;
1616 for (int i = 0; i < len; i++) {
1617 DeclSpace ds = (DeclSpace) list [i];
1619 if ((ds.ModFlags & modflags) == 0)
1622 TypeBuilder tb = ds.TypeBuilder;
1624 if (!(criteria is string) || ds.Basename.Equals (criteria))
1625 tb = ds.DefineType ();
1628 if (tb != null && (filter (tb, criteria) == true)) {
1629 if (members == null)
1630 members = new ArrayList ();
1639 /// This method returns the members of this type just like Type.FindMembers would
1640 /// Only, we need to use this for types which are _being_ defined because MS'
1641 /// implementation can't take care of that.
1644 // FIXME: return an empty static array instead of null, that cleans up
1645 // some code and is consistent with some coding conventions I just found
1649 // Notice that in various cases we check if our field is non-null,
1650 // something that would normally mean that there was a bug elsewhere.
1652 // The problem happens while we are defining p-invoke methods, as those
1653 // will trigger a FindMembers, but this happens before things are defined
1655 // Since the whole process is a no-op, it is fine to check for null here.
1657 // TODO: This approach will be one day completely removed, it's already
1658 // used at few places only
1661 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1662 MemberFilter filter, object criteria)
1664 ArrayList members = null;
1667 if ((bf & BindingFlags.Public) != 0)
1668 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1670 if ((bf & BindingFlags.NonPublic) != 0)
1671 modflags |= Modifiers.PRIVATE;
1673 int static_mask = 0, static_flags = 0;
1674 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1675 case BindingFlags.Static:
1676 static_mask = static_flags = Modifiers.STATIC;
1679 case BindingFlags.Instance:
1680 static_mask = Modifiers.STATIC;
1685 static_mask = static_flags = 0;
1689 Timer.StartTimer (TimerType.TcFindMembers);
1692 filter = accepting_filter;
1694 if ((mt & MemberTypes.Field) != 0) {
1695 if (fields != null) {
1696 int len = fields.Count;
1697 for (int i = 0; i < len; i++) {
1698 FieldBase f = (FieldBase) fields [i];
1700 if ((f.ModFlags & modflags) == 0)
1702 if ((f.ModFlags & static_mask) != static_flags)
1705 FieldBuilder fb = f.FieldBuilder;
1706 if (fb != null && filter (fb, criteria) == true) {
1707 if (members == null)
1708 members = new ArrayList ();
1715 if (constants != null) {
1716 int len = constants.Count;
1717 for (int i = 0; i < len; i++) {
1718 Const con = (Const) constants [i];
1720 if ((con.ModFlags & modflags) == 0)
1722 if ((con.ModFlags & static_mask) != static_flags)
1725 FieldBuilder fb = con.FieldBuilder;
1728 fb = con.FieldBuilder;
1730 if (fb != null && filter (fb, criteria) == true) {
1731 if (members == null)
1732 members = new ArrayList ();
1740 if ((mt & MemberTypes.Method) != 0) {
1741 if (methods != null) {
1742 int len = methods.Count;
1743 for (int i = 0; i < len; i++) {
1744 MethodOrOperator m = (MethodOrOperator) methods [i];
1746 if ((m.ModFlags & modflags) == 0)
1748 if ((m.ModFlags & static_mask) != static_flags)
1751 MethodBuilder mb = m.MethodBuilder;
1753 if (mb != null && filter (mb, criteria) == true) {
1754 if (members == null)
1755 members = new ArrayList ();
1762 if (operators != null) {
1763 int len = operators.Count;
1764 for (int i = 0; i < len; i++) {
1765 Operator o = (Operator) operators [i];
1767 if ((o.ModFlags & modflags) == 0)
1769 if ((o.ModFlags & static_mask) != static_flags)
1772 MethodBuilder ob = o.MethodBuilder;
1773 if (ob != null && filter (ob, criteria) == true) {
1774 if (members == null)
1775 members = new ArrayList ();
1782 if (events != null) {
1783 foreach (Event e in events) {
1784 if ((e.ModFlags & modflags) == 0)
1786 if ((e.ModFlags & static_mask) != static_flags)
1789 MethodBuilder b = e.AddBuilder;
1790 if (b != null && filter (b, criteria)) {
1791 if (members == null)
1792 members = new ArrayList (4);
1797 b = e.RemoveBuilder;
1798 if (b != null && filter (b, criteria)) {
1799 if (members == null)
1800 members = new ArrayList (4);
1807 if (properties != null) {
1808 int len = properties.Count;
1809 for (int i = 0; i < len; i++) {
1810 Property p = (Property) properties [i];
1812 if ((p.ModFlags & modflags) == 0)
1814 if ((p.ModFlags & static_mask) != static_flags)
1820 if (b != null && filter (b, criteria) == true) {
1821 if (members == null)
1822 members = new ArrayList ();
1828 if (b != null && filter (b, criteria) == true) {
1829 if (members == null)
1830 members = new ArrayList ();
1837 if (indexers != null) {
1838 int len = indexers.Count;
1839 for (int i = 0; i < len; i++) {
1840 Indexer ix = (Indexer) indexers [i];
1842 if ((ix.ModFlags & modflags) == 0)
1844 if ((ix.ModFlags & static_mask) != static_flags)
1850 if (b != null && filter (b, criteria) == true) {
1851 if (members == null)
1852 members = new ArrayList ();
1858 if (b != null && filter (b, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1868 if ((mt & MemberTypes.Event) != 0) {
1869 if (events != null) {
1870 int len = events.Count;
1871 for (int i = 0; i < len; i++) {
1872 Event e = (Event) events [i];
1874 if ((e.ModFlags & modflags) == 0)
1876 if ((e.ModFlags & static_mask) != static_flags)
1879 MemberInfo eb = e.EventBuilder;
1880 if (eb != null && filter (eb, criteria) == true) {
1881 if (members == null)
1882 members = new ArrayList ();
1884 members.Add (e.EventBuilder);
1890 if ((mt & MemberTypes.Property) != 0){
1891 if (properties != null) {
1892 int len = properties.Count;
1893 for (int i = 0; i < len; i++) {
1894 Property p = (Property) properties [i];
1896 if ((p.ModFlags & modflags) == 0)
1898 if ((p.ModFlags & static_mask) != static_flags)
1901 MemberInfo pb = p.PropertyBuilder;
1902 if (pb != null && filter (pb, criteria) == true) {
1903 if (members == null)
1904 members = new ArrayList ();
1906 members.Add (p.PropertyBuilder);
1911 if (indexers != null) {
1912 int len = indexers.Count;
1913 for (int i = 0; i < len; i++) {
1914 Indexer ix = (Indexer) indexers [i];
1916 if ((ix.ModFlags & modflags) == 0)
1918 if ((ix.ModFlags & static_mask) != static_flags)
1921 MemberInfo ib = ix.PropertyBuilder;
1922 if (ib != null && filter (ib, criteria) == true) {
1923 if (members == null)
1924 members = new ArrayList ();
1926 members.Add (ix.PropertyBuilder);
1932 if ((mt & MemberTypes.NestedType) != 0)
1933 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1935 if ((mt & MemberTypes.Constructor) != 0){
1936 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1937 int len = instance_constructors.Count;
1938 for (int i = 0; i < len; i++) {
1939 Constructor c = (Constructor) instance_constructors [i];
1941 ConstructorBuilder cb = c.ConstructorBuilder;
1942 if (cb != null && filter (cb, criteria) == true) {
1943 if (members == null)
1944 members = new ArrayList ();
1951 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1952 ConstructorBuilder cb =
1953 default_static_constructor.ConstructorBuilder;
1955 if (cb != null && filter (cb, criteria) == true) {
1956 if (members == null)
1957 members = new ArrayList ();
1965 // Lookup members in base if requested.
1967 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1968 if (TypeBuilder.BaseType != null) {
1969 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1970 if (list.Count > 0) {
1971 if (members == null)
1972 members = new ArrayList ();
1974 members.AddRange (list);
1979 Timer.StopTimer (TimerType.TcFindMembers);
1981 if (members == null)
1982 return MemberList.Empty;
1984 return new MemberList (members);
1987 public override MemberCache MemberCache {
1989 return member_cache;
1993 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1994 MemberFilter filter, object criteria)
1996 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1999 return ds.FindMembers (mt, bf, filter, criteria);
2001 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2005 /// Emits the values for the constants
2007 public void EmitConstants ()
2009 if (constants != null)
2010 foreach (Const con in constants)
2015 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2020 foreach (MemberCore mc in al) {
2021 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2024 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2025 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2030 public virtual void VerifyMembers ()
2033 // Check for internal or private fields that were never assigned
2035 if (Report.WarningLevel >= 3) {
2036 CheckMemberUsage (properties, "property");
2037 CheckMemberUsage (methods, "method");
2038 CheckMemberUsage (constants, "constant");
2040 if (fields != null){
2041 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2042 foreach (FieldBase f in fields) {
2043 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2044 if (is_type_exposed)
2047 f.SetMemberIsUsed ();
2051 if ((f.caching_flags & Flags.IsAssigned) == 0)
2052 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2055 const int error_code = 414;
2057 const int error_code = 169;
2059 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2060 f.GetSignatureForError ());
2066 // Only report 649 on level 4
2068 if (Report.WarningLevel < 4)
2071 if ((f.caching_flags & Flags.IsAssigned) != 0)
2075 // Don't be pendatic over serializable attributes
2077 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2080 Constant c = New.Constantify (f.MemberType);
2081 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2082 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2088 // TODO: move to ClassOrStruct
2089 void EmitConstructors ()
2091 if (instance_constructors == null)
2094 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2095 bool has_compliant_args = false;
2097 foreach (Constructor c in instance_constructors) {
2101 catch (Exception e) {
2102 throw new InternalErrorException (c, e);
2105 if (has_compliant_args)
2108 has_compliant_args = c.HasCompliantArgs;
2110 if (!has_compliant_args)
2111 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2113 foreach (Constructor c in instance_constructors) {
2117 catch (Exception e) {
2118 throw new InternalErrorException (c, e);
2125 /// Emits the code, this step is performed after all
2126 /// the types, enumerations, constructors
2128 public virtual void EmitType ()
2130 if (OptAttributes != null)
2131 OptAttributes.Emit ();
2135 EmitConstructors ();
2137 // Can not continue if constants are broken
2139 if (Report.Errors > 0)
2142 if (default_static_constructor != null)
2143 default_static_constructor.Emit ();
2145 if (operators != null)
2146 foreach (Operator o in operators)
2149 if (properties != null)
2150 foreach (Property p in properties)
2153 if (indexers != null) {
2154 foreach (Indexer indx in indexers)
2159 if (events != null){
2160 foreach (Event e in Events)
2164 if (methods != null) {
2165 for (int i = 0; i < methods.Count; ++i)
2166 ((MethodOrOperator) methods [i]).Emit ();
2170 foreach (FieldBase f in fields)
2173 if (delegates != null) {
2174 foreach (Delegate d in Delegates) {
2179 if (pending != null)
2180 pending.VerifyPendingMethods ();
2182 if (Report.Errors > 0)
2185 if (compiler_generated != null) {
2186 for (int i = 0; i < compiler_generated.Count; ++i)
2187 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2191 public override void CloseType ()
2193 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2197 caching_flags |= Flags.CloseTypeCreated;
2198 TypeBuilder.CreateType ();
2199 } catch (TypeLoadException){
2201 // This is fine, the code still created the type
2203 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2204 // Console.WriteLine (e.Message);
2205 } catch (Exception e) {
2206 throw new InternalErrorException (this, e);
2210 foreach (TypeContainer tc in Types)
2211 if (tc.Kind == Kind.Struct)
2214 foreach (TypeContainer tc in Types)
2215 if (tc.Kind != Kind.Struct)
2219 if (Delegates != null)
2220 foreach (Delegate d in Delegates)
2223 if (compiler_generated != null)
2224 foreach (CompilerGeneratedClass c in compiler_generated)
2227 PartialContainer = null;
2232 initialized_fields = null;
2233 initialized_static_fields = null;
2235 ordered_explicit_member_list = null;
2236 ordered_member_list = null;
2241 compiler_generated = null;
2242 default_constructor = null;
2243 default_static_constructor = null;
2245 OptAttributes = null;
2248 member_cache = null;
2252 // Performs the validation on a Method's modifiers (properties have
2253 // the same properties).
2255 public bool MethodModifiersValid (MemberCore mc)
2257 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2258 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2259 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2261 int flags = mc.ModFlags;
2264 // At most one of static, virtual or override
2266 if ((flags & Modifiers.STATIC) != 0){
2267 if ((flags & vao) != 0){
2268 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2269 mc.GetSignatureForError ());
2274 if (Kind == Kind.Struct){
2275 if ((flags & va) != 0){
2276 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2281 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2282 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2283 mc.GetSignatureForError ());
2288 // If the declaration includes the abstract modifier, then the
2289 // declaration does not include static, virtual or extern
2291 if ((flags & Modifiers.ABSTRACT) != 0){
2292 if ((flags & Modifiers.EXTERN) != 0){
2294 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2298 if ((flags & Modifiers.SEALED) != 0) {
2299 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2303 if ((flags & Modifiers.VIRTUAL) != 0){
2304 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2308 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2309 Report.SymbolRelatedToPreviousError (this);
2310 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2311 mc.GetSignatureForError (), GetSignatureForError ());
2316 if ((flags & Modifiers.PRIVATE) != 0){
2317 if ((flags & vao) != 0){
2318 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2323 if ((flags & Modifiers.SEALED) != 0){
2324 if ((flags & Modifiers.OVERRIDE) == 0){
2325 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2333 public Constructor DefaultStaticConstructor {
2334 get { return default_static_constructor; }
2337 protected override bool VerifyClsCompliance ()
2339 if (!base.VerifyClsCompliance ())
2344 Type base_type = TypeBuilder.BaseType;
2345 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2346 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2353 /// Checks whether container name is CLS Compliant
2355 void VerifyClsName ()
2357 Hashtable base_members = base_cache == null ?
2359 base_cache.GetPublicMembers ();
2360 Hashtable this_members = new Hashtable ();
2362 foreach (DictionaryEntry entry in defined_names) {
2363 MemberCore mc = (MemberCore)entry.Value;
2364 if (!mc.IsClsComplianceRequired ())
2367 string name = (string) entry.Key;
2368 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2370 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2371 object found = base_members [lcase];
2372 if (found == null) {
2373 found = this_members [lcase];
2374 if (found == null) {
2375 this_members.Add (lcase, mc);
2380 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2383 if (found is MemberInfo) {
2384 if (basename == ((MemberInfo) found).Name)
2386 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2388 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2391 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2397 /// Performs checks for an explicit interface implementation. First it
2398 /// checks whether the `interface_type' is a base inteface implementation.
2399 /// Then it checks whether `name' exists in the interface type.
2401 public bool VerifyImplements (InterfaceMemberBase mb)
2403 if (ifaces != null) {
2404 foreach (Type t in ifaces){
2405 if (TypeManager.IsEqual (t, mb.InterfaceType))
2410 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2411 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2412 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2416 public override Type LookupAnyGeneric (string typeName)
2418 if (types != null) {
2419 foreach (TypeContainer tc in types) {
2423 int pos = tc.Basename.LastIndexOf ('`');
2424 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2425 return tc.TypeBuilder;
2429 return base.LookupAnyGeneric (typeName);
2432 public void Mark_HasEquals ()
2434 cached_method |= CachedMethods.Equals;
2437 public void Mark_HasGetHashCode ()
2439 cached_method |= CachedMethods.GetHashCode;
2443 /// Method container contains Equals method
2445 public bool HasEquals {
2447 return (cached_method & CachedMethods.Equals) != 0;
2452 /// Method container contains GetHashCode method
2454 public bool HasGetHashCode {
2456 return (cached_method & CachedMethods.GetHashCode) != 0;
2460 public bool HasStaticFieldInitializer {
2462 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2466 cached_method |= CachedMethods.HasStaticFieldInitializer;
2468 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2476 string IMemberContainer.Name {
2482 Type IMemberContainer.Type {
2488 bool IMemberContainer.IsInterface {
2490 return Kind == Kind.Interface;
2494 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2496 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2498 if (GenericType != null)
2499 return TypeManager.FindMembers (GenericType, mt, new_bf,
2502 return FindMembers (mt, new_bf, null, null);
2506 // Generates xml doc comments (if any), and if required,
2507 // handle warning report.
2509 internal override void GenerateDocComment (DeclSpace ds)
2511 DocUtil.GenerateTypeDocComment (this, ds);
2514 public override string DocCommentHeader {
2515 get { return "T:"; }
2518 public MemberCache BaseCache {
2520 if (base_cache != null)
2522 if (TypeBuilder.BaseType != null)
2523 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2524 if (TypeBuilder.IsInterface)
2525 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2531 public abstract class ClassOrStruct : TypeContainer {
2532 ListDictionary declarative_security;
2534 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2535 MemberName name, Attributes attrs, Kind kind)
2536 : base (ns, parent, name, attrs, kind)
2540 protected override bool AddToContainer (MemberCore symbol, string name)
2542 if (name == MemberName.Name) {
2543 if (symbol is TypeParameter) {
2544 Report.Error (694, symbol.Location,
2545 "Type parameter `{0}' has same name as containing type, or method",
2546 symbol.GetSignatureForError ());
2550 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2551 if (imb == null || !imb.IsExplicitImpl) {
2552 Report.SymbolRelatedToPreviousError (this);
2553 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2554 symbol.GetSignatureForError ());
2559 return base.AddToContainer (symbol, name);
2562 public override void VerifyMembers ()
2564 base.VerifyMembers ();
2566 if ((events != null) && Report.WarningLevel >= 3) {
2567 foreach (Event e in events){
2568 // Note: The event can be assigned from same class only, so we can report
2569 // this warning for all accessibility modes
2570 if ((e.caching_flags & Flags.IsUsed) == 0)
2571 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2576 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2578 if (a.IsValidSecurityAttribute ()) {
2579 if (declarative_security == null)
2580 declarative_security = new ListDictionary ();
2582 a.ExtractSecurityPermissionSet (declarative_security);
2586 if (a.Type == TypeManager.struct_layout_attribute_type) {
2587 PartialContainer.HasStructLayout = true;
2589 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2590 PartialContainer.HasExplicitLayout = true;
2593 base.ApplyAttributeBuilder (a, cb);
2597 /// Defines the default constructors
2599 protected void DefineDefaultConstructor (bool is_static)
2601 // The default instance constructor is public
2602 // If the class is abstract, the default constructor is protected
2603 // The default static constructor is private
2607 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2609 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2612 Constructor c = new Constructor (this, MemberName.Name, mods,
2613 null, ParametersCompiled.EmptyReadOnlyParameters,
2614 new GeneratedBaseInitializer (Location),
2618 c.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
2621 public override bool Define ()
2623 CheckProtectedModifier ();
2627 if (default_static_constructor != null)
2628 default_static_constructor.Define ();
2633 public override void Emit ()
2635 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2636 DefineDefaultConstructor (true);
2637 default_static_constructor.Define ();
2642 if (declarative_security != null) {
2643 foreach (DictionaryEntry de in declarative_security) {
2644 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2649 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2651 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2654 protected override TypeAttributes TypeAttr {
2656 if (default_static_constructor == null)
2657 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2659 return base.TypeAttr;
2665 // TODO: should be sealed
2666 public class Class : ClassOrStruct {
2667 const int AllowedModifiers =
2670 Modifiers.PROTECTED |
2671 Modifiers.INTERNAL |
2673 Modifiers.ABSTRACT |
2678 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2680 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2682 : base (ns, parent, name, attrs, Kind.Class)
2684 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2685 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2687 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2688 Report.FeatureIsNotAvailable (Location, "static classes");
2692 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2694 if (part.Name == "System.Object")
2695 Report.Error (537, part.Location,
2696 "The class System.Object cannot have a base class or implement an interface.");
2697 base.AddBasesForPart (part, bases);
2700 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2702 if (a.Type == TypeManager.attribute_usage_type) {
2703 if (!TypeManager.IsAttributeType (BaseType) &&
2704 TypeBuilder.FullName != "System.Attribute") {
2705 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2709 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2710 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2714 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2715 !attributes.Contains (TypeManager.guid_attr_type)) {
2716 a.Error_MissingGuidAttribute ();
2720 if (a.Type == TypeManager.extension_attribute_type) {
2721 a.Error_MisusedExtensionAttribute ();
2725 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2728 base.ApplyAttributeBuilder (a, cb);
2731 public override AttributeTargets AttributeTargets {
2733 return AttributeTargets.Class;
2737 protected override void DefineContainerMembers (MemberCoreArrayList list)
2743 base.DefineContainerMembers (list);
2747 foreach (MemberCore m in list) {
2748 if (m is Operator) {
2749 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2753 if (m is Destructor) {
2754 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2759 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2763 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2766 if (m is Constructor) {
2767 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2771 Method method = m as Method;
2772 if (method != null && method.Parameters.HasExtensionMethodType) {
2773 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2777 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2780 base.DefineContainerMembers (list);
2783 public override bool Define ()
2785 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2786 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2789 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2790 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2793 return base.Define ();
2796 protected override bool DoDefineMembers ()
2798 if (InstanceConstructors == null && !IsStatic)
2799 DefineDefaultConstructor (false);
2801 return base.DoDefineMembers ();
2804 public override void Emit ()
2809 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2810 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2814 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2816 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2818 if (base_class == null) {
2819 if (RootContext.StdLib)
2820 base_class = TypeManager.system_object_expr;
2821 else if (Name != "System.Object")
2822 base_class = TypeManager.system_object_expr;
2824 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2826 689, base_class.Location,
2827 "Cannot derive from `{0}' because it is a type parameter",
2828 base_class.GetSignatureForError ());
2832 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2833 Report.Error (698, base_class.Location,
2834 "A generic type cannot derive from `{0}' because it is an attribute class",
2835 base_class.GetSignatureForError ());
2838 if (base_class.IsSealed){
2839 Report.SymbolRelatedToPreviousError (base_class.Type);
2840 if (base_class.Type.IsAbstract) {
2841 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2842 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2844 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2845 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2850 if (!base_class.CanInheritFrom ()){
2851 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2852 GetSignatureForError (), base_class.GetSignatureForError ());
2856 if (!IsAccessibleAs (base_class.Type)) {
2857 Report.SymbolRelatedToPreviousError (base_class.Type);
2858 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2859 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2863 if (PartialContainer.IsStaticClass) {
2864 if (base_class.Type != TypeManager.object_type) {
2865 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2866 GetSignatureForError (), base_class.GetSignatureForError ());
2870 if (ifaces != null) {
2871 foreach (TypeExpr t in ifaces)
2872 Report.SymbolRelatedToPreviousError (t.Type);
2873 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2880 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2881 /// Valid only for attribute classes.
2882 public bool IsExcluded ()
2884 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2885 return (caching_flags & Flags.Excluded) != 0;
2887 caching_flags &= ~Flags.Excluded_Undetected;
2889 if (OptAttributes == null)
2892 if (TypeManager.conditional_attribute_type == null)
2895 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2900 foreach (Attribute a in attrs) {
2901 string condition = a.GetConditionalAttributeValue ();
2902 if (Location.CompilationUnit.IsConditionalDefined (condition))
2906 caching_flags |= Flags.Excluded;
2912 return (ModFlags & Modifiers.STATIC) != 0;
2917 // FIXME: How do we deal with the user specifying a different
2920 protected override TypeAttributes TypeAttr {
2922 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2924 ta |= StaticClassAttribute;
2930 public sealed class Struct : ClassOrStruct {
2932 // Modifiers allowed in a struct declaration
2934 const int AllowedModifiers =
2937 Modifiers.PROTECTED |
2938 Modifiers.INTERNAL |
2942 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2943 int mod, Attributes attrs)
2944 : base (ns, parent, name, attrs, Kind.Struct)
2948 if (parent.Parent == null)
2949 accmods = Modifiers.INTERNAL;
2951 accmods = Modifiers.PRIVATE;
2953 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2955 this.ModFlags |= Modifiers.SEALED;
2958 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2960 base.ApplyAttributeBuilder (a, cb);
2963 // When struct constains fixed fixed and struct layout has explicitly
2964 // set CharSet, its value has to be propagated to compiler generated
2965 // fixed field types
2967 if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
2968 for (int i = 0; i < Fields.Count; ++i) {
2969 FixedField ff = Fields [i] as FixedField;
2971 ff.SetCharSet (TypeBuilder.Attributes);
2976 public override AttributeTargets AttributeTargets {
2978 return AttributeTargets.Struct;
2982 public override bool IsUnmanagedType ()
2987 if (requires_delayed_unmanagedtype_check)
2990 foreach (FieldBase f in fields) {
2991 if ((f.ModFlags & Modifiers.STATIC) != 0)
2994 // It can happen when recursive unmanaged types are defined
2995 // struct S { S* s; }
2996 Type mt = f.MemberType;
2998 requires_delayed_unmanagedtype_check = true;
3002 // TODO: Remove when pointer types are under mcs control
3003 while (mt.IsPointer)
3004 mt = TypeManager.GetElementType (mt);
3005 if (TypeManager.IsEqual (mt, TypeBuilder))
3008 if (TypeManager.IsUnmanagedType (mt))
3017 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
3019 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
3021 // If we are compiling our runtime,
3022 // and we are defining ValueType, then our
3023 // base is `System.Object'.
3025 if (base_class == null) {
3026 if (!RootContext.StdLib && Name == "System.ValueType")
3027 base_class = TypeManager.system_object_expr;
3029 base_class = TypeManager.system_valuetype_expr;
3036 // FIXME: Allow the user to specify a different set of attributes
3037 // in some cases (Sealed for example is mandatory for a class,
3038 // but what SequentialLayout can be changed
3040 protected override TypeAttributes TypeAttr {
3042 const TypeAttributes DefaultTypeAttributes =
3043 TypeAttributes.SequentialLayout |
3044 TypeAttributes.Sealed |
3045 TypeAttributes.BeforeFieldInit;
3047 return base.TypeAttr | DefaultTypeAttributes;
3051 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3053 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3054 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3055 field.GetSignatureForError ());
3058 base.RegisterFieldForInitialization (field, expression);
3066 public sealed class Interface : TypeContainer, IMemberContainer {
3069 /// Modifiers allowed in a class declaration
3071 public const int AllowedModifiers =
3074 Modifiers.PROTECTED |
3075 Modifiers.INTERNAL |
3079 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3081 : base (ns, parent, name, attrs, Kind.Interface)
3085 if (parent.Parent == null)
3086 accmods = Modifiers.INTERNAL;
3088 accmods = Modifiers.PRIVATE;
3090 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3093 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3095 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3096 !attributes.Contains (TypeManager.guid_attr_type)) {
3097 a.Error_MissingGuidAttribute ();
3100 base.ApplyAttributeBuilder (a, cb);
3104 public override AttributeTargets AttributeTargets {
3106 return AttributeTargets.Interface;
3110 protected override TypeAttributes TypeAttr {
3112 const TypeAttributes DefaultTypeAttributes =
3113 TypeAttributes.AutoLayout |
3114 TypeAttributes.Abstract |
3115 TypeAttributes.Interface;
3117 return base.TypeAttr | DefaultTypeAttributes;
3121 protected override bool VerifyClsCompliance ()
3123 if (!base.VerifyClsCompliance ())
3126 if (ifaces != null) {
3127 foreach (Type t in ifaces) {
3128 if (AttributeTester.IsClsCompliant (t))
3131 Report.SymbolRelatedToPreviousError (t);
3132 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3133 GetSignatureForError (), TypeManager.CSharpName (t));
3141 // It is used as a base class for all property based members
3142 // This includes properties, indexers, and events
3143 public abstract class PropertyBasedMember : InterfaceMemberBase
3145 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3146 FullNamedExpression type, int mod, int allowed_mod,
3147 MemberName name, Attributes attrs)
3148 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3152 protected override bool VerifyClsCompliance ()
3154 if (!base.VerifyClsCompliance ())
3157 if (!AttributeTester.IsClsCompliant (MemberType)) {
3158 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3159 GetSignatureForError ());
3167 public abstract class MethodCore : InterfaceMemberBase
3169 public readonly ParametersCompiled Parameters;
3170 protected ToplevelBlock block;
3172 public MethodCore (DeclSpace parent, GenericMethod generic,
3173 FullNamedExpression type, int mod, int allowed_mod,
3174 MemberName name, Attributes attrs, ParametersCompiled parameters)
3175 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3177 Parameters = parameters;
3181 // Returns the System.Type array for the parameters of this method
3183 public Type [] ParameterTypes {
3185 return Parameters.Types;
3189 public ParametersCompiled ParameterInfo {
3195 public ToplevelBlock Block {
3205 public CallingConventions CallingConventions {
3207 CallingConventions cc = Parameters.CallingConvention;
3209 if ((ModFlags & Modifiers.STATIC) == 0)
3210 cc |= CallingConventions.HasThis;
3212 // FIXME: How is `ExplicitThis' used in C#?
3218 protected override bool CheckBase ()
3220 // Check whether arguments were correct.
3221 if (!DefineParameters (Parameters))
3224 return base.CheckBase ();
3228 // Returns a string that represents the signature for this
3229 // member which should be used in XML documentation.
3231 public override string GetDocCommentName (DeclSpace ds)
3233 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3237 // Raised (and passed an XmlElement that contains the comment)
3238 // when GenerateDocComment is writing documentation expectedly.
3240 // FIXME: with a few effort, it could be done with XmlReader,
3241 // that means removal of DOM use.
3243 internal override void OnGenerateDocComment (XmlElement el)
3245 DocUtil.OnMethodGenerateDocComment (this, el);
3249 // Represents header string for documentation comment.
3251 public override string DocCommentHeader
3253 get { return "M:"; }
3256 public override bool EnableOverloadChecks (MemberCore overload)
3258 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3259 caching_flags |= Flags.MethodOverloadsExist;
3263 return base.EnableOverloadChecks (overload);
3266 protected override bool VerifyClsCompliance ()
3268 if (!base.VerifyClsCompliance ())
3271 if (Parameters.HasArglist) {
3272 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3275 if (!AttributeTester.IsClsCompliant (MemberType)) {
3276 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3277 GetSignatureForError ());
3280 Parameters.VerifyClsCompliance ();
3286 public abstract class InterfaceMemberBase : MemberBase {
3288 // Whether this is an interface member.
3290 public bool IsInterface;
3293 // If true, this is an explicit interface implementation
3295 public bool IsExplicitImpl;
3297 protected bool is_external_implementation;
3300 // The interface type we are explicitly implementing
3302 public Type InterfaceType;
3305 // The method we're overriding if this is an override method.
3307 protected MethodInfo base_method;
3309 readonly int explicit_mod_flags;
3310 public MethodAttributes flags;
3312 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3313 FullNamedExpression type, int mod, int allowed_mod,
3314 MemberName name, Attributes attrs)
3315 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3318 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3319 IsExplicitImpl = (MemberName.Left != null);
3320 explicit_mod_flags = mod;
3323 protected override bool CheckBase ()
3325 if (!base.CheckBase ())
3328 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3329 CheckForDuplications ();
3334 // Is null for System.Object while compiling corlib and base interfaces
3335 if (Parent.PartialContainer.BaseCache == null) {
3336 if ((ModFlags & Modifiers.NEW) != 0) {
3337 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3342 Type base_ret_type = null;
3343 base_method = FindOutBaseMethod (ref base_ret_type);
3345 // method is override
3346 if (base_method != null) {
3347 if (!CheckMethodAgainstBase (base_ret_type))
3350 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3351 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3353 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3354 Report.SymbolRelatedToPreviousError (base_method);
3355 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3356 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3359 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3360 Report.SymbolRelatedToPreviousError (base_method);
3361 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3362 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3369 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3370 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3371 if (conflict_symbol != null) {
3372 Report.SymbolRelatedToPreviousError (conflict_symbol);
3374 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3375 else if (this is PropertyBase)
3376 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3378 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3380 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3381 GetSignatureForError (), SimpleName.GetMemberType (this));
3386 if (conflict_symbol == null) {
3387 if ((ModFlags & Modifiers.NEW) != 0) {
3388 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3393 if ((ModFlags & Modifiers.NEW) == 0) {
3394 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3397 Report.SymbolRelatedToPreviousError (conflict_symbol);
3398 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3399 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3405 protected virtual bool CheckForDuplications ()
3407 return Parent.MemberCache.CheckExistingMembersOverloads (
3408 this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters);
3412 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3413 // that have been defined.
3415 // `name' is the user visible name for reporting errors (this is used to
3416 // provide the right name regarding method names and properties)
3418 bool CheckMethodAgainstBase (Type base_method_type)
3422 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3423 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3424 Report.SymbolRelatedToPreviousError (base_method);
3425 Report.Error (506, Location,
3426 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3427 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3431 // Now we check that the overriden method is not final
3433 if (base_method.IsFinal) {
3434 Report.SymbolRelatedToPreviousError (base_method);
3435 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3436 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3440 // Check that the permissions are not being changed
3442 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3443 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3445 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3446 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3450 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3451 Report.SymbolRelatedToPreviousError (base_method);
3452 if (this is PropertyBasedMember) {
3453 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3454 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3457 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3458 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3464 if ((ModFlags & Modifiers.NEW) == 0) {
3465 if ((ModFlags & Modifiers.OVERRIDE) == 0) {
3466 ModFlags |= Modifiers.NEW;
3467 Report.SymbolRelatedToPreviousError (base_method);
3468 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3469 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",
3470 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3472 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3473 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3477 if (base_method.IsAbstract && !IsInterface) {
3478 Report.SymbolRelatedToPreviousError (base_method);
3479 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3480 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3488 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3490 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3492 // when overriding protected internal, the method can be declared
3493 // protected internal only within the same assembly or assembly
3494 // which has InternalsVisibleTo
3496 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3497 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3498 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3500 // if it's not "protected internal", it must be "protected"
3504 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3506 // protected within the same assembly - an error
3509 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3510 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3512 // protected ok, but other attributes differ - report an error
3518 return (thisp == base_classp);
3522 public override bool Define ()
3525 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3526 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3528 flags = MethodAttributes.Public |
3529 MethodAttributes.Abstract |
3530 MethodAttributes.HideBySig |
3531 MethodAttributes.NewSlot |
3532 MethodAttributes.Virtual;
3534 Parent.PartialContainer.MethodModifiersValid (this);
3536 flags = Modifiers.MethodAttr (ModFlags);
3539 if (IsExplicitImpl) {
3540 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3541 if (iface_texpr == null)
3544 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3545 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3546 GetSignatureForError ());
3549 InterfaceType = iface_texpr.Type;
3551 if (!InterfaceType.IsInterface) {
3552 Report.SymbolRelatedToPreviousError (InterfaceType);
3553 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3554 TypeManager.CSharpName (InterfaceType));
3556 Parent.PartialContainer.VerifyImplements (this);
3559 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3562 return base.Define ();
3565 protected bool DefineParameters (ParametersCompiled parameters)
3567 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3569 if (!parameters.Resolve (rc))
3573 for (int i = 0; i < parameters.Count; ++i) {
3574 Parameter p = parameters [i];
3575 if (p.CheckAccessibility (this))
3578 Type t = parameters.Types [i];
3579 Report.SymbolRelatedToPreviousError (t);
3580 if (this is Indexer)
3581 Report.Error (55, Location,
3582 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3583 TypeManager.CSharpName (t), GetSignatureForError ());
3584 else if (this is Operator)
3585 Report.Error (57, Location,
3586 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3587 TypeManager.CSharpName (t), GetSignatureForError ());
3589 Report.Error (51, Location,
3590 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3591 TypeManager.CSharpName (t), GetSignatureForError ());
3597 public override void Emit()
3599 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3600 // We are more strict than csc and report this as an error because SRE does not allow emit that
3601 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3602 if (this is Constructor) {
3603 Report.Error (824, Location,
3604 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3606 Report.Error (626, Location,
3607 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3608 GetSignatureForError ());
3615 public override bool EnableOverloadChecks (MemberCore overload)
3618 // Two members can differ in their explicit interface
3619 // type parameter only
3621 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3622 if (imb != null && imb.IsExplicitImpl) {
3623 if (IsExplicitImpl) {
3624 caching_flags |= Flags.MethodOverloadsExist;
3629 return IsExplicitImpl;
3632 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3634 Report.SymbolRelatedToPreviousError (base_method);
3635 string base_name = TypeManager.GetFullNameSignature (base_method);
3636 string this_name = GetSignatureForError ();
3637 if (suffix != null) {
3638 base_name += suffix;
3639 this_name += suffix;
3642 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3643 this_name, Modifiers.GetDescription (ma), base_name);
3646 protected static string Error722 {
3648 return "`{0}': static types cannot be used as return types";
3653 /// Gets base method and its return type
3655 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3658 // The "short" name of this property / indexer / event. This is the
3659 // name without the explicit interface.
3661 public string ShortName
3663 get { return MemberName.Name; }
3664 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3668 // Returns full metadata method name
3670 public string GetFullName (MemberName name)
3672 if (!IsExplicitImpl)
3676 // When dealing with explicit members a full interface type
3677 // name is added to member name to avoid possible name conflicts
3679 // We use CSharpName which gets us full name with benefit of
3680 // replacing predefined names which saves some space and name
3683 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3686 protected override bool VerifyClsCompliance ()
3688 if (!base.VerifyClsCompliance ()) {
3689 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3690 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3693 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3694 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3699 if (GenericMethod != null)
3700 GenericMethod.VerifyClsCompliance ();
3705 public override bool IsUsed
3707 get { return IsExplicitImpl || base.IsUsed; }
3712 public abstract class MethodOrOperator : MethodCore, IMethodData
3714 public MethodBuilder MethodBuilder;
3715 ReturnParameter return_attributes;
3716 ListDictionary declarative_security;
3717 protected MethodData MethodData;
3719 static string[] attribute_targets = new string [] { "method", "return" };
3721 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3722 int allowed_mod, MemberName name,
3723 Attributes attrs, ParametersCompiled parameters)
3724 : base (parent, generic, type, mod, allowed_mod, name,
3729 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3731 if (a.Target == AttributeTargets.ReturnValue) {
3732 if (return_attributes == null)
3733 return_attributes = new ReturnParameter (MethodBuilder, Location);
3735 return_attributes.ApplyAttributeBuilder (a, cb);
3739 if (a.IsInternalMethodImplAttribute) {
3740 is_external_implementation = true;
3743 if (a.Type == TypeManager.dllimport_type) {
3744 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3745 if ((ModFlags & extern_static) != extern_static) {
3746 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3748 is_external_implementation = true;
3751 if (a.IsValidSecurityAttribute ()) {
3752 if (declarative_security == null)
3753 declarative_security = new ListDictionary ();
3754 a.ExtractSecurityPermissionSet (declarative_security);
3758 if (MethodBuilder != null)
3759 MethodBuilder.SetCustomAttribute (cb);
3762 public override AttributeTargets AttributeTargets {
3764 return AttributeTargets.Method;
3768 protected override bool CheckForDuplications ()
3770 string name = GetFullName (MemberName);
3771 if (MemberName.IsGeneric)
3772 name = MemberName.MakeName (name, MemberName.TypeArguments);
3774 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3777 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3779 return new EmitContext (
3780 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3783 protected override bool ResolveMemberType ()
3786 if (GenericMethod != null) {
3787 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3788 if (!GenericMethod.Define (this))
3793 return base.ResolveMemberType ();
3796 public override bool Define ()
3798 if (!base.Define ())
3804 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3806 // Current method is turned into automatically generated
3807 // wrapper which creates an instance of iterator
3809 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3810 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3813 if (IsPartialDefinition) {
3814 caching_flags &= ~Flags.Excluded_Undetected;
3815 caching_flags |= Flags.Excluded;
3816 // Add to member cache only when a partial method implementation is not there
3817 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3818 MethodBase mb = new PartialMethodDefinitionInfo (this);
3819 Parent.MemberCache.AddMember (mb, this);
3820 TypeManager.AddMethod (mb, this);
3826 MethodData = new MethodData (
3827 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3829 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3832 MethodBuilder = MethodData.MethodBuilder;
3835 if (MethodBuilder.IsGenericMethod)
3836 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3839 Parent.MemberCache.AddMember (MethodBuilder, this);
3844 protected override void DoMemberTypeIndependentChecks ()
3846 base.DoMemberTypeIndependentChecks ();
3848 CheckAbstractAndExtern (block != null);
3850 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3851 for (int i = 0; i < Parameters.Count; ++i) {
3852 if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3853 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3854 GetSignatureForError ());
3861 protected override void DoMemberTypeDependentChecks ()
3863 base.DoMemberTypeDependentChecks ();
3865 if (!TypeManager.IsGenericParameter (MemberType)) {
3866 if (MemberType.IsAbstract && MemberType.IsSealed) {
3867 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3872 public override void Emit ()
3875 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3876 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3877 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3878 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3880 if (OptAttributes != null)
3881 OptAttributes.Emit ();
3883 if (declarative_security != null) {
3884 foreach (DictionaryEntry de in declarative_security) {
3885 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3889 if (MethodData != null)
3890 MethodData.Emit (Parent);
3898 protected void Error_ConditionalAttributeIsNotValid ()
3900 Report.Error (577, Location,
3901 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3902 GetSignatureForError ());
3905 public bool IsPartialDefinition {
3907 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3911 public bool IsPartialImplementation {
3913 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3917 public override string[] ValidAttributeTargets {
3919 return attribute_targets;
3923 #region IMethodData Members
3925 public Type ReturnType {
3931 public MemberName MethodName {
3938 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3940 public bool IsExcluded () {
3941 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3942 return (caching_flags & Flags.Excluded) != 0;
3944 caching_flags &= ~Flags.Excluded_Undetected;
3946 if (base_method == null) {
3947 if (OptAttributes == null)
3950 if (TypeManager.conditional_attribute_type == null)
3953 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3958 foreach (Attribute a in attrs) {
3959 string condition = a.GetConditionalAttributeValue ();
3960 if (condition == null)
3963 if (Location.CompilationUnit.IsConditionalDefined (condition))
3967 caching_flags |= Flags.Excluded;
3971 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3973 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3974 caching_flags |= Flags.Excluded;
3980 if (md.IsExcluded ()) {
3981 caching_flags |= Flags.Excluded;
3987 GenericMethod IMethodData.GenericMethod {
3989 return GenericMethod;
3993 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4000 public class SourceMethod : IMethodDef
4003 SourceMethodBuilder builder;
4005 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4007 this.method = method;
4009 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4012 public string Name {
4013 get { return method.Name; }
4018 if (method is MethodBuilder)
4019 return ((MethodBuilder) method).GetToken ().Token;
4020 else if (method is ConstructorBuilder)
4021 return ((ConstructorBuilder) method).GetToken ().Token;
4023 throw new NotSupportedException ();
4027 public void CloseMethod ()
4029 SymbolWriter.CloseMethod ();
4032 public void SetRealMethodName (string name)
4034 if (builder != null)
4035 builder.SetRealMethodName (name);
4038 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4040 if (!SymbolWriter.HasSymbolWriter)
4045 Location start_loc = block.StartLocation;
4046 if (start_loc.IsNull)
4049 ICompileUnit compile_unit = start_loc.CompilationUnit;
4050 if (compile_unit == null)
4053 return new SourceMethod (parent, method, compile_unit);
4057 public class Method : MethodOrOperator {
4060 /// Modifiers allowed in a class declaration
4062 const int AllowedModifiers =
4065 Modifiers.PROTECTED |
4066 Modifiers.INTERNAL |
4071 Modifiers.OVERRIDE |
4072 Modifiers.ABSTRACT |
4076 const int AllowedInterfaceModifiers =
4077 Modifiers.NEW | Modifiers.UNSAFE;
4079 public Method (DeclSpace parent, GenericMethod generic,
4080 FullNamedExpression return_type, int mod,
4081 MemberName name, ParametersCompiled parameters, Attributes attrs)
4082 : base (parent, generic, return_type, mod,
4083 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4084 name, attrs, parameters)
4088 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4089 MemberName name, ParametersCompiled parameters, Attributes attrs)
4090 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4094 public override string GetSignatureForError()
4096 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4099 static void Error_DuplicateEntryPoint (Method b)
4101 Report.Error (17, b.Location,
4102 "Program `{0}' has more than one entry point defined: `{1}'",
4103 CodeGen.FileName, b.GetSignatureForError ());
4106 bool IsEntryPoint ()
4108 if (ReturnType != TypeManager.void_type &&
4109 ReturnType != TypeManager.int32_type)
4112 if (Parameters.Count == 0)
4115 if (Parameters.Count > 1)
4118 Type t = Parameters.Types [0];
4119 return t.IsArray && t.GetArrayRank () == 1 &&
4120 TypeManager.GetElementType (t) == TypeManager.string_type &&
4121 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4124 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4126 if (a.Type == TypeManager.conditional_attribute_type) {
4127 if (IsExplicitImpl) {
4128 Error_ConditionalAttributeIsNotValid ();
4132 if (ReturnType != TypeManager.void_type) {
4133 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4137 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4138 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4143 Report.Error (582, Location, "Conditional not valid on interface members");
4147 if (MethodData.implementing != null) {
4148 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4149 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4150 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4154 for (int i = 0; i < Parameters.Count; ++i) {
4155 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4156 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4162 if (a.Type == TypeManager.extension_attribute_type) {
4163 a.Error_MisusedExtensionAttribute ();
4167 base.ApplyAttributeBuilder (a, cb);
4170 protected override bool CheckForDuplications ()
4172 if (!base.CheckForDuplications ())
4175 ArrayList ar = Parent.PartialContainer.Properties;
4177 for (int i = 0; i < ar.Count; ++i) {
4178 PropertyBase pb = (PropertyBase) ar [i];
4179 if (pb.AreAccessorsDuplicateImplementation (this))
4184 ar = Parent.PartialContainer.Indexers;
4186 for (int i = 0; i < ar.Count; ++i) {
4187 PropertyBase pb = (PropertyBase) ar [i];
4188 if (pb.AreAccessorsDuplicateImplementation (this))
4196 protected override bool CheckBase ()
4198 if (!base.CheckBase ())
4201 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
4202 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
4203 TypeManager.CSharpSignature (base_method));
4212 public override bool Define ()
4214 if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
4215 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4218 if (!base.Define ())
4221 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4222 Error1599 (Location, ReturnType);
4226 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4227 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4228 Parent.PartialContainer.Mark_HasEquals ();
4229 else if (Parameters.IsEmpty && Name == "GetHashCode")
4230 Parent.PartialContainer.Mark_HasGetHashCode ();
4233 if ((ModFlags & Modifiers.STATIC) == 0)
4236 if (Parameters.HasExtensionMethodType) {
4237 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4238 if (!Parent.IsTopLevel)
4239 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4240 GetSignatureForError ());
4242 if (TypeManager.extension_attribute_type == null) {
4243 Report.Error (1110, Location,
4244 "`{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",
4245 GetSignatureForError ());
4246 } else if (TypeManager.extension_attribute_attr == null) {
4247 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4248 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4251 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4254 ModFlags |= Modifiers.METHOD_EXTENSION;
4255 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
4256 CodeGen.Assembly.HasExtensionMethods = true;
4258 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4259 GetSignatureForError ());
4264 // This is used to track the Entry Point,
4266 if (RootContext.NeedsEntryPoint &&
4268 (RootContext.MainClass == null ||
4269 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4270 if (IsEntryPoint ()) {
4272 if (RootContext.EntryPoint == null) {
4273 if (Parent.IsGeneric || MemberName.IsGeneric) {
4274 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4275 GetSignatureForError ());
4278 RootContext.EntryPoint = this;
4281 Error_DuplicateEntryPoint (RootContext.EntryPoint);
4282 Error_DuplicateEntryPoint (this);
4285 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4286 GetSignatureForError ());
4296 public override void Emit ()
4299 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4300 if (IsPartialDefinition) {
4302 // Do attribute checks only when partial implementation does not exist
4304 if (MethodBuilder == null)
4310 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4311 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4312 GetSignatureForError ());
4317 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4318 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4322 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4323 Location, MethodBuilder);
4328 public override bool EnableOverloadChecks (MemberCore overload)
4330 // TODO: It can be deleted when members will be defined in correct order
4331 if (overload is Operator)
4332 return overload.EnableOverloadChecks (this);
4334 if (overload is Indexer)
4337 return base.EnableOverloadChecks (overload);
4340 public static void Error1599 (Location loc, Type t)
4342 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4345 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4347 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4348 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4353 if (mi.IsSpecialName)
4356 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4360 public void SetPartialDefinition (Method methodDefinition)
4362 caching_flags |= Flags.PartialDefinitionExists;
4363 methodDefinition.MethodBuilder = MethodBuilder;
4364 if (methodDefinition.attributes == null)
4367 if (attributes == null) {
4368 attributes = methodDefinition.attributes;
4370 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4374 protected override bool VerifyClsCompliance ()
4376 if (!base.VerifyClsCompliance ())
4379 if (!Parameters.IsEmpty) {
4380 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4382 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4389 public abstract class ConstructorInitializer : ExpressionStatement
4391 ArrayList argument_list;
4392 MethodGroupExpr base_constructor_group;
4394 public ConstructorInitializer (ArrayList argument_list, Location loc)
4396 this.argument_list = argument_list;
4400 public ArrayList Arguments {
4402 return argument_list;
4406 public override Expression CreateExpressionTree (EmitContext ec)
4408 throw new NotSupportedException ("ET");
4411 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4413 if (argument_list != null){
4414 foreach (Argument a in argument_list){
4415 if (!a.Resolve (ec, loc))
4420 if (this is ConstructorBaseInitializer) {
4421 if (ec.ContainerType.BaseType == null)
4424 type = ec.ContainerType.BaseType;
4425 if (TypeManager.IsStruct (ec.ContainerType)) {
4426 Report.Error (522, loc,
4427 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4432 // It is legal to have "this" initializers that take no arguments
4433 // in structs, they are just no-ops.
4435 // struct D { public D (int a) : this () {}
4437 if (TypeManager.IsStruct (ec.ContainerType) && argument_list == null)
4440 type = ec.ContainerType;
4443 base_constructor_group = MemberLookupFinal (
4444 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4445 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4446 loc) as MethodGroupExpr;
4448 if (base_constructor_group == null)
4451 base_constructor_group = base_constructor_group.OverloadResolve (
4452 ec, ref argument_list, false, loc);
4454 if (base_constructor_group == null)
4457 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4459 if (base_ctor == caller_builder){
4460 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4466 public override Expression DoResolve (EmitContext ec)
4468 throw new NotSupportedException ();
4471 public override void Emit (EmitContext ec)
4473 // It can be null for static initializers
4474 if (base_constructor_group == null)
4479 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4481 base_constructor_group.EmitCall (ec, argument_list);
4484 public override void EmitStatement (EmitContext ec)
4490 public class ConstructorBaseInitializer : ConstructorInitializer {
4491 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4492 base (argument_list, l)
4497 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4498 public GeneratedBaseInitializer (Location loc):
4504 public class ConstructorThisInitializer : ConstructorInitializer {
4505 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4506 base (argument_list, l)
4511 public class Constructor : MethodCore, IMethodData {
4512 public ConstructorBuilder ConstructorBuilder;
4513 public ConstructorInitializer Initializer;
4514 ListDictionary declarative_security;
4515 bool has_compliant_args;
4518 // Modifiers allowed for a constructor.
4520 public const int AllowedModifiers =
4522 Modifiers.PROTECTED |
4523 Modifiers.INTERNAL |
4529 static readonly string[] attribute_targets = new string [] { "method" };
4532 // The spec claims that static is not permitted, but
4533 // my very own code has static constructors.
4535 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, ParametersCompiled args,
4536 ConstructorInitializer init, Location loc)
4537 : base (parent, null, null, mod, AllowedModifiers,
4538 new MemberName (name, loc), attrs, args)
4543 public bool HasCompliantArgs {
4544 get { return has_compliant_args; }
4547 public override AttributeTargets AttributeTargets {
4548 get { return AttributeTargets.Constructor; }
4552 // Returns true if this is a default constructor
4554 public bool IsDefault ()
4556 if ((ModFlags & Modifiers.STATIC) != 0)
4557 return Parameters.IsEmpty;
4559 return Parameters.IsEmpty &&
4560 (Initializer is ConstructorBaseInitializer) &&
4561 (Initializer.Arguments == null);
4564 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4566 if (a.IsValidSecurityAttribute ()) {
4567 if (declarative_security == null) {
4568 declarative_security = new ListDictionary ();
4570 a.ExtractSecurityPermissionSet (declarative_security);
4574 if (a.IsInternalMethodImplAttribute) {
4575 is_external_implementation = true;
4578 ConstructorBuilder.SetCustomAttribute (cb);
4581 protected override bool CheckBase ()
4583 if ((ModFlags & Modifiers.STATIC) != 0) {
4584 if (!Parameters.IsEmpty) {
4585 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4586 GetSignatureForError ());
4590 // the rest can be ignored
4594 // Check whether arguments were correct.
4595 if (!DefineParameters (Parameters))
4598 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4599 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4602 if (Parent.PartialContainer.Kind == Kind.Struct) {
4603 if (Parameters.Count == 0) {
4604 Report.Error (568, Location,
4605 "Structs cannot contain explicit parameterless constructors");
4610 CheckProtectedModifier ();
4616 // Creates the ConstructorBuilder
4618 public override bool Define ()
4620 if (ConstructorBuilder != null)
4623 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4624 MethodAttributes.SpecialName);
4626 if ((ModFlags & Modifiers.STATIC) != 0) {
4627 ca |= MethodAttributes.Static | MethodAttributes.Private;
4629 ca |= MethodAttributes.HideBySig;
4631 if ((ModFlags & Modifiers.PUBLIC) != 0)
4632 ca |= MethodAttributes.Public;
4633 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4634 if ((ModFlags & Modifiers.INTERNAL) != 0)
4635 ca |= MethodAttributes.FamORAssem;
4637 ca |= MethodAttributes.Family;
4638 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4639 ca |= MethodAttributes.Assembly;
4641 ca |= MethodAttributes.Private;
4644 if (!CheckAbstractAndExtern (block != null))
4647 // Check if arguments were correct.
4651 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4652 ca, CallingConventions,
4653 Parameters.GetEmitTypes ());
4655 if (Parent.PartialContainer.IsComImport) {
4656 if (!IsDefault ()) {
4657 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4658 Parent.GetSignatureForError ());
4660 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4663 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4664 TypeManager.AddMethod (ConstructorBuilder, this);
4666 // It's here only to report an error
4667 if (block != null && block.IsIterator) {
4668 member_type = TypeManager.void_type;
4669 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4678 public override void Emit ()
4680 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4681 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4683 if (OptAttributes != null)
4684 OptAttributes.Emit ();
4688 EmitContext ec = CreateEmitContext (null, null);
4691 // If we use a "this (...)" constructor initializer, then
4692 // do not emit field initializers, they are initialized in the other constructor
4694 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4695 !(Initializer is ConstructorThisInitializer);
4697 if (emit_field_initializers)
4698 Parent.PartialContainer.ResolveFieldInitializers (ec);
4700 if (block != null) {
4701 // If this is a non-static `struct' constructor and doesn't have any
4702 // initializer, it must initialize all of the struct's fields.
4703 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4704 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4705 block.AddThisVariable (Parent, Location);
4707 if (!block.ResolveMeta (ec, Parameters))
4710 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4711 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4712 Initializer = new GeneratedBaseInitializer (Location);
4715 // Spec mandates that Initializers will not have `this' access
4717 if (Initializer != null) {
4719 Initializer.Resolve (ConstructorBuilder, ec);
4720 ec.IsStatic = false;
4721 block.AddScopeStatement (new StatementExpression (Initializer));
4726 Parameters.ApplyAttributes (ConstructorBuilder);
4728 SourceMethod source = null;
4730 ec.OmitDebuggingInfo = true;
4732 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4734 bool unreachable = false;
4735 if (block != null) {
4736 if (!ec.ResolveTopBlock (null, block, Parameters, this, out unreachable))
4739 ec.EmitMeta (block);
4741 if (Report.Errors > 0)
4744 ec.EmitResolvedTopBlock (block, unreachable);
4748 source.CloseMethod ();
4750 if (declarative_security != null) {
4751 foreach (DictionaryEntry de in declarative_security) {
4752 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4759 // Is never override
4760 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4765 public override string GetSignatureForError()
4767 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4770 public override string[] ValidAttributeTargets {
4772 return attribute_targets;
4776 protected override bool VerifyClsCompliance ()
4778 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4782 if (!Parameters.IsEmpty) {
4783 ArrayList al = (ArrayList)Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
4785 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4787 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4788 foreach (Type param in Parameters.Types) {
4789 if (param.IsArray) {
4795 has_compliant_args = true;
4799 #region IMethodData Members
4801 public MemberName MethodName {
4807 public Type ReturnType {
4813 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4815 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4816 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4817 ec.CurrentBlock = block;
4821 public bool IsExcluded()
4826 GenericMethod IMethodData.GenericMethod {
4832 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4839 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4841 public interface IMethodData
4843 CallingConventions CallingConventions { get; }
4844 Location Location { get; }
4845 MemberName MethodName { get; }
4846 Type ReturnType { get; }
4847 GenericMethod GenericMethod { get; }
4848 ParametersCompiled ParameterInfo { get; }
4850 Attributes OptAttributes { get; }
4851 ToplevelBlock Block { get; set; }
4853 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4854 ObsoleteAttribute GetObsoleteAttribute ();
4855 string GetSignatureForError ();
4857 bool IsClsComplianceRequired ();
4858 void SetMemberIsUsed ();
4859 void EmitExtraSymbolInfo (SourceMethod source);
4863 // Encapsulates most of the Method's state
4865 public class MethodData {
4867 static FieldInfo methodbuilder_attrs_field;
4869 public readonly IMethodData method;
4871 public readonly GenericMethod GenericMethod;
4874 // Are we implementing an interface ?
4876 public MethodInfo implementing;
4881 protected InterfaceMemberBase member;
4882 protected int modifiers;
4883 protected MethodAttributes flags;
4884 protected Type declaring_type;
4885 protected MethodInfo parent_method;
4887 MethodBuilder builder = null;
4888 public MethodBuilder MethodBuilder {
4894 public Type DeclaringType {
4896 return declaring_type;
4900 public MethodData (InterfaceMemberBase member,
4901 int modifiers, MethodAttributes flags, IMethodData method)
4903 this.member = member;
4904 this.modifiers = modifiers;
4907 this.method = method;
4910 public MethodData (InterfaceMemberBase member,
4911 int modifiers, MethodAttributes flags,
4912 IMethodData method, MethodBuilder builder,
4913 GenericMethod generic, MethodInfo parent_method)
4914 : this (member, modifiers, flags, method)
4916 this.builder = builder;
4917 this.GenericMethod = generic;
4918 this.parent_method = parent_method;
4921 public bool Define (DeclSpace parent, string method_full_name)
4923 string name = method.MethodName.Basename;
4925 TypeContainer container = parent.PartialContainer;
4927 PendingImplementation pending = container.PendingImplementations;
4928 if (pending != null){
4929 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4931 if (member.InterfaceType != null){
4932 if (implementing == null){
4933 if (member is PropertyBase) {
4934 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4935 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4936 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4939 Report.Error (539, method.Location,
4940 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4941 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4945 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4946 Report.SymbolRelatedToPreviousError (implementing);
4947 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4948 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4952 if (implementing != null) {
4953 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4954 if (prop_method == null) {
4955 if (TypeManager.IsSpecialMethod (implementing)) {
4956 Report.SymbolRelatedToPreviousError (implementing);
4957 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4958 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4959 implementing.Name.StartsWith ("get_") ? "get" : "set");
4961 } else if (implementing.DeclaringType.IsInterface) {
4962 if (!implementing.IsSpecialName) {
4963 Report.SymbolRelatedToPreviousError (implementing);
4964 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4965 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4968 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4969 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4970 Report.SymbolRelatedToPreviousError (implementing);
4971 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4972 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4981 // For implicit implementations, make sure we are public, for
4982 // explicit implementations, make sure we are private.
4984 if (implementing != null){
4986 // Setting null inside this block will trigger a more
4987 // verbose error reporting for missing interface implementations
4989 // The "candidate" function has been flagged already
4990 // but it wont get cleared
4992 if (member.IsExplicitImpl){
4993 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4994 Report.SymbolRelatedToPreviousError (implementing);
4995 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4996 method.GetSignatureForError ());
5000 if (implementing.DeclaringType.IsInterface) {
5002 // If this is an interface method implementation,
5003 // check for public accessibility
5005 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5007 implementing = null;
5009 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5010 // We may never be private.
5011 implementing = null;
5013 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5015 // We may be protected if we're overriding something.
5017 implementing = null;
5022 // Static is not allowed
5024 if ((modifiers & Modifiers.STATIC) != 0){
5025 implementing = null;
5030 // If implementing is still valid, set flags
5032 if (implementing != null){
5034 // When implementing interface methods, set NewSlot
5035 // unless, we are overwriting a method.
5037 if (implementing.DeclaringType.IsInterface){
5038 if ((modifiers & Modifiers.OVERRIDE) == 0)
5039 flags |= MethodAttributes.NewSlot;
5042 MethodAttributes.Virtual |
5043 MethodAttributes.HideBySig;
5045 // Set Final unless we're virtual, abstract or already overriding a method.
5046 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5047 flags |= MethodAttributes.Final;
5050 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5052 if (builder == null)
5055 if (container.CurrentType != null)
5056 declaring_type = container.CurrentType;
5058 declaring_type = container.TypeBuilder;
5060 if (implementing != null && member.IsExplicitImpl) {
5061 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5064 TypeManager.AddMethod (builder, method);
5066 if (GenericMethod != null) {
5067 bool is_override = member.IsExplicitImpl |
5068 ((modifiers & Modifiers.OVERRIDE) != 0);
5070 if (implementing != null)
5071 parent_method = implementing;
5073 EmitContext ec = method.CreateEmitContext (container, null);
5074 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5083 /// Create the MethodBuilder for the method
5085 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
5087 if (builder == null) {
5088 builder = container.TypeBuilder.DefineMethod (
5089 method_name, flags, method.CallingConventions,
5090 method.ReturnType, param.GetEmitTypes ());
5096 // Generic method has been already defined to resolve method parameters
5097 // correctly when they use type parameters
5099 builder.SetParameters (param.GetEmitTypes ());
5100 builder.SetReturnType (method.ReturnType);
5102 if (builder.Attributes != flags) {
5104 if (methodbuilder_attrs_field == null)
5105 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5106 methodbuilder_attrs_field.SetValue (builder, flags);
5108 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5112 throw new InternalErrorException ();
5119 public void Emit (DeclSpace parent)
5121 ToplevelBlock block = method.Block;
5125 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5127 ec = method.CreateEmitContext (parent, null);
5129 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5131 if (GenericMethod != null)
5132 GenericMethod.EmitAttributes ();
5135 // clear the pending implementation flag
5137 if (implementing != null)
5138 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5139 member.InterfaceType, this, member.IsExplicitImpl);
5141 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5143 ec.EmitTopBlock (method, block);
5145 if (source != null) {
5146 method.EmitExtraSymbolInfo (source);
5147 source.CloseMethod ();
5152 public class Destructor : MethodOrOperator
5154 const int AllowedModifiers =
5158 static readonly string[] attribute_targets = new string [] { "method" };
5160 public static readonly string MetadataName = "Finalize";
5162 public Destructor (DeclSpace parent, int mod, ParametersCompiled parameters, Attributes attrs, Location l)
5163 : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
5164 new MemberName (MetadataName, l), attrs, parameters)
5166 ModFlags &= ~Modifiers.PRIVATE;
5167 ModFlags |= Modifiers.PROTECTED;
5170 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5172 if (a.Type == TypeManager.conditional_attribute_type) {
5173 Error_ConditionalAttributeIsNotValid ();
5177 base.ApplyAttributeBuilder (a, cb);
5180 protected override bool CheckBase ()
5182 flags |= MethodAttributes.Virtual;
5184 if (!base.CheckBase ())
5187 if (Parent.PartialContainer.BaseCache == null)
5190 Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
5191 if (base_type != null && Block != null) {
5192 MethodGroupExpr method_expr = Expression.MethodLookup (Parent.TypeBuilder, base_type, MetadataName, Location);
5193 if (method_expr == null)
5194 throw new NotImplementedException ();
5196 method_expr.IsBase = true;
5197 method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
5199 ToplevelBlock new_block = new ToplevelBlock (Block.StartLocation);
5200 new_block.EndLocation = Block.EndLocation;
5202 Block finaly_block = new ExplicitBlock (new_block, Location, Location);
5203 Block try_block = new Block (new_block, block);
5206 // 0-size arguments to avoid CS0250 error
5207 // TODO: Should use AddScopeStatement or something else which emits correct
5210 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new ArrayList (0))));
5211 new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
5219 public override string GetSignatureForError ()
5221 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5224 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5229 public override string[] ValidAttributeTargets {
5231 return attribute_targets;
5236 public abstract class MemberBase : MemberCore
5238 protected FullNamedExpression type_name;
5239 protected Type member_type;
5241 public readonly DeclSpace ds;
5242 public readonly GenericMethod GenericMethod;
5244 protected MemberBase (DeclSpace parent, GenericMethod generic,
5245 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5246 MemberName name, Attributes attrs)
5247 : base (parent, name, attrs)
5249 this.ds = generic != null ? generic : (DeclSpace) parent;
5250 this.type_name = type;
5251 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5252 GenericMethod = generic;
5253 if (GenericMethod != null)
5254 GenericMethod.ModFlags = ModFlags;
5258 // Main member define entry
5260 public override bool Define ()
5262 DoMemberTypeIndependentChecks ();
5265 // Returns false only when type resolution failed
5267 if (!ResolveMemberType ())
5270 DoMemberTypeDependentChecks ();
5275 // Any type_name independent checks
5277 protected virtual void DoMemberTypeIndependentChecks ()
5279 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5280 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5281 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5282 GetSignatureForError (), Parent.GetSignatureForError ());
5287 // Any type_name dependent checks
5289 protected virtual void DoMemberTypeDependentChecks ()
5291 // verify accessibility
5292 if (!IsAccessibleAs (MemberType)) {
5293 Report.SymbolRelatedToPreviousError (MemberType);
5294 if (this is Property)
5295 Report.Error (53, Location,
5296 "Inconsistent accessibility: property type `" +
5297 TypeManager.CSharpName (MemberType) + "' is less " +
5298 "accessible than property `" + GetSignatureForError () + "'");
5299 else if (this is Indexer)
5300 Report.Error (54, Location,
5301 "Inconsistent accessibility: indexer return type `" +
5302 TypeManager.CSharpName (MemberType) + "' is less " +
5303 "accessible than indexer `" + GetSignatureForError () + "'");
5304 else if (this is MethodCore) {
5305 if (this is Operator)
5306 Report.Error (56, Location,
5307 "Inconsistent accessibility: return type `" +
5308 TypeManager.CSharpName (MemberType) + "' is less " +
5309 "accessible than operator `" + GetSignatureForError () + "'");
5311 Report.Error (50, Location,
5312 "Inconsistent accessibility: return type `" +
5313 TypeManager.CSharpName (MemberType) + "' is less " +
5314 "accessible than method `" + GetSignatureForError () + "'");
5316 Report.Error (52, Location,
5317 "Inconsistent accessibility: field type `" +
5318 TypeManager.CSharpName (MemberType) + "' is less " +
5319 "accessible than field `" + GetSignatureForError () + "'");
5323 if (MemberType.IsGenericParameter && (MemberType.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0) {
5324 Report.Error (-33, Location, "Contravariant type parameters can only be used in input positions");
5329 protected bool IsTypePermitted ()
5331 if (TypeManager.IsSpecialType (MemberType)) {
5332 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5338 protected virtual bool CheckBase ()
5340 CheckProtectedModifier ();
5345 public Type MemberType {
5346 get { return member_type; }
5349 protected virtual bool ResolveMemberType ()
5351 if (member_type != null)
5352 throw new InternalErrorException ("Multi-resolve");
5354 IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5355 TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5360 // Replace original type name, error reporting can use fully resolved name
5364 member_type = te.Type;
5370 // Abstract class for all fields
5372 abstract public class FieldBase : MemberBase {
5373 public FieldBuilder FieldBuilder;
5374 public Status status;
5375 protected Expression initializer;
5378 public enum Status : byte {
5379 HAS_OFFSET = 4 // Used by FieldMember.
5382 static readonly string[] attribute_targets = new string [] { "field" };
5384 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5385 int allowed_mod, MemberName name, Attributes attrs)
5386 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5389 if ((mod & Modifiers.ABSTRACT) != 0)
5390 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5393 public override AttributeTargets AttributeTargets {
5395 return AttributeTargets.Field;
5399 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5401 if (a.Type == TypeManager.field_offset_attribute_type) {
5402 status |= Status.HAS_OFFSET;
5404 if (!Parent.PartialContainer.HasExplicitLayout) {
5405 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5409 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5410 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5416 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5417 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5423 if (a.Type == TypeManager.marshal_as_attr_type) {
5424 UnmanagedMarshal marshal = a.GetMarshal (this);
5425 if (marshal != null) {
5426 FieldBuilder.SetMarshal (marshal);
5431 if ((a.HasSecurityAttribute)) {
5432 a.Error_InvalidSecurityParent ();
5436 FieldBuilder.SetCustomAttribute (cb);
5439 protected override bool CheckBase ()
5441 if (!base.CheckBase ())
5444 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5445 if (conflict_symbol == null) {
5446 if ((ModFlags & Modifiers.NEW) != 0) {
5447 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5452 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5453 Report.SymbolRelatedToPreviousError (conflict_symbol);
5454 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5455 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5461 protected override void DoMemberTypeDependentChecks ()
5463 base.DoMemberTypeDependentChecks ();
5465 if (TypeManager.IsGenericParameter (MemberType))
5468 if (MemberType.IsSealed && MemberType.IsAbstract) {
5469 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5477 // Represents header string for documentation comment.
5479 public override string DocCommentHeader {
5480 get { return "F:"; }
5483 public override void Emit ()
5486 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5487 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5490 if (OptAttributes != null) {
5491 OptAttributes.Emit ();
5494 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5495 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5501 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5503 Report.SymbolRelatedToPreviousError (static_class);
5504 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5508 public Expression Initializer {
5510 if (value != null) {
5511 this.initializer = value;
5516 protected virtual bool IsFieldClsCompliant {
5518 if (FieldBuilder == null)
5521 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5525 public override string[] ValidAttributeTargets
5528 return attribute_targets;
5532 protected override bool VerifyClsCompliance ()
5534 if (!base.VerifyClsCompliance ())
5537 if (!IsFieldClsCompliant) {
5538 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5539 GetSignatureForError ());
5544 public void SetAssigned ()
5546 caching_flags |= Flags.IsAssigned;
5550 interface IFixedBuffer
5552 FieldInfo Element { get; }
5553 Type ElementType { get; }
5556 public class FixedFieldExternal: IFixedBuffer
5558 FieldInfo element_field;
5560 public FixedFieldExternal (FieldInfo fi)
5562 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5565 #region IFixedField Members
5567 public FieldInfo Element {
5569 return element_field;
5573 public Type ElementType {
5575 return element_field.FieldType;
5583 /// Fixed buffer implementation
5585 public class FixedField : FieldBase, IFixedBuffer
5587 public const string FixedElementName = "FixedElementField";
5588 static int GlobalCounter = 0;
5589 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5590 static FieldInfo[] fi;
5592 TypeBuilder fixed_buffer_type;
5593 FieldBuilder element;
5594 Expression size_expr;
5596 const int AllowedModifiers =
5599 Modifiers.PROTECTED |
5600 Modifiers.INTERNAL |
5603 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5604 Expression size_expr, Attributes attrs, Location loc):
5605 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5607 if (RootContext.Version < LanguageVersion.ISO_2)
5608 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5610 this.size_expr = size_expr;
5613 public override bool Define()
5615 if (!base.Define ())
5618 if (!TypeManager.IsPrimitiveType (MemberType)) {
5619 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",
5620 GetSignatureForError ());
5623 // Create nested fixed buffer container
5624 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5625 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5626 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5628 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5629 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5631 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5632 Parent.MemberCache.AddMember (FieldBuilder, this);
5633 TypeManager.RegisterFieldBase (FieldBuilder, this);
5638 protected override void DoMemberTypeIndependentChecks ()
5640 base.DoMemberTypeIndependentChecks ();
5642 if (!Parent.IsInUnsafeScope)
5643 Expression.UnsafeError (Location);
5645 if (Parent.PartialContainer.Kind != Kind.Struct) {
5646 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5647 GetSignatureForError ());
5651 public override void Emit()
5653 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5654 Constant c = size_expr.ResolveAsConstant (ec, this);
5658 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5659 if (buffer_size_const == null)
5662 int buffer_size = buffer_size_const.Value;
5664 if (buffer_size <= 0) {
5665 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5669 int type_size = Expression.GetTypeSize (MemberType);
5671 if (buffer_size > int.MaxValue / type_size) {
5672 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5673 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5677 buffer_size *= type_size;
5678 EmitFieldSize (buffer_size);
5682 // Emit compiler generated fixed buffer type attribute
5684 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5686 Type attr_type = TypeManager.CoreLookupType (
5687 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5689 if (attr_type != null) {
5690 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5692 cab = new CustomAttributeBuilder (ci, new object [0]);
5693 TypeManager.unsafe_value_type_attr = cab;
5699 fixed_buffer_type.SetCustomAttribute (cab);
5704 void EmitFieldSize (int buffer_size)
5706 if (TypeManager.struct_layout_attribute_type == null) {
5707 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5708 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5710 if (TypeManager.struct_layout_attribute_type == null)
5715 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5717 object [] fi_val = new object [] { buffer_size };
5719 if (TypeManager.struct_layout_attribute_ctor == null) {
5720 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5721 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5722 if (TypeManager.struct_layout_attribute_ctor == null)
5726 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5727 ctor_args, fi, fi_val);
5728 fixed_buffer_type.SetCustomAttribute (cab);
5731 // Don't emit FixedBufferAttribute attribute for private types
5733 if ((ModFlags & Modifiers.PRIVATE) != 0)
5736 if (TypeManager.fixed_buffer_attr_ctor == null) {
5737 if (TypeManager.fixed_buffer_attr_type == null) {
5738 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5739 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5741 if (TypeManager.fixed_buffer_attr_type == null)
5745 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5746 Location, TypeManager.type_type, TypeManager.int32_type);
5748 if (TypeManager.fixed_buffer_attr_ctor == null)
5752 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5753 FieldBuilder.SetCustomAttribute (cab);
5756 protected override bool IsFieldClsCompliant {
5762 public void SetCharSet (TypeAttributes ta)
5764 TypeAttributes cta = fixed_buffer_type.Attributes;
5765 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5766 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5767 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5768 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5769 else if (cta == 0 && ta != 0)
5770 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5773 void SetTypeBuilderCharSet (TypeAttributes ta)
5775 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5777 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5779 mi.Invoke (fixed_buffer_type, new object [] { ta });
5783 #region IFixedField Members
5785 public FieldInfo Element {
5791 public Type ElementType {
5801 // The Field class is used to represents class/struct fields during parsing.
5803 public class Field : FieldBase {
5805 // Modifiers allowed in a class declaration
5807 const int AllowedModifiers =
5810 Modifiers.PROTECTED |
5811 Modifiers.INTERNAL |
5814 Modifiers.VOLATILE |
5818 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5820 : base (parent, type, mod, AllowedModifiers, name, attrs)
5824 bool CanBeVolatile ()
5826 if (TypeManager.IsReferenceType (MemberType))
5829 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5830 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5831 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5832 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5833 MemberType == TypeManager.float_type)
5836 if (TypeManager.IsEnumType (MemberType))
5842 bool CheckStructLayout (Type type, bool isStatic)
5844 if (TypeManager.IsBuiltinType (type))
5848 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5852 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5853 if (!TypeManager.IsGenericType (type))
5856 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5857 if (!CheckStructLayout (t, false))
5863 Report.Error (523, Location,
5864 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5865 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5869 public override bool Define ()
5871 if (!base.Define ())
5876 Type[] required_modifier = null;
5877 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5878 if (TypeManager.isvolatile_type == null)
5879 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5880 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5882 if (TypeManager.isvolatile_type != null)
5883 required_modifier = new Type [] { TypeManager.isvolatile_type };
5886 FieldBuilder = Parent.TypeBuilder.DefineField (
5887 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5889 FieldBuilder = Parent.TypeBuilder.DefineField (
5890 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5892 // Don't cache inaccessible fields
5893 if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
5894 Parent.MemberCache.AddMember (FieldBuilder, this);
5897 TypeManager.RegisterFieldBase (FieldBuilder, this);
5899 catch (ArgumentException) {
5900 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5904 if (initializer != null) {
5905 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5906 new FieldInitializer (FieldBuilder, initializer, this));
5908 if (Parent.PartialContainer.Kind == Kind.Struct)
5909 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5915 protected override void DoMemberTypeDependentChecks ()
5917 base.DoMemberTypeDependentChecks ();
5919 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5920 if (!CanBeVolatile ()) {
5921 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5922 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5925 if ((ModFlags & Modifiers.READONLY) != 0) {
5926 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5927 GetSignatureForError ());
5932 protected override bool VerifyClsCompliance ()
5934 if (!base.VerifyClsCompliance ())
5937 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5938 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5946 // `set' and `get' accessors are represented with an Accessor.
5948 public class Accessor {
5950 // Null if the accessor is empty, or a Block if not
5952 public const int AllowedModifiers =
5954 Modifiers.PROTECTED |
5955 Modifiers.INTERNAL |
5958 public ToplevelBlock Block;
5959 public Attributes Attributes;
5960 public Location Location;
5961 public int ModFlags;
5962 public ParametersCompiled Parameters;
5964 public Accessor (ToplevelBlock b, int mod, Attributes attrs, ParametersCompiled p, Location loc)
5970 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5974 // Ooouh Martin, templates are missing here.
5975 // When it will be possible move here a lot of child code and template method type.
5976 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5977 protected MethodData method_data;
5978 protected ToplevelBlock block;
5979 protected ListDictionary declarative_security;
5981 // The accessor are created even if they are not wanted.
5982 // But we need them because their names are reserved.
5983 // Field says whether accessor will be emited or not
5984 public readonly bool IsDummy;
5986 protected readonly string prefix;
5988 ReturnParameter return_attributes;
5990 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5991 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5993 this.prefix = prefix;
5997 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5999 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6000 accessor.Attributes)
6002 this.prefix = prefix;
6003 this.block = accessor.Block;
6006 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6008 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6011 public void UpdateName (InterfaceMemberBase member)
6013 SetMemberName (SetupName (prefix, member, Location));
6016 #region IMethodData Members
6018 public ToplevelBlock Block {
6028 public CallingConventions CallingConventions {
6030 return CallingConventions.Standard;
6034 public bool IsExcluded ()
6039 GenericMethod IMethodData.GenericMethod {
6045 public MemberName MethodName {
6051 public Type[] ParameterTypes {
6053 return ParameterInfo.Types;
6057 public abstract ParametersCompiled ParameterInfo { get ; }
6058 public abstract Type ReturnType { get; }
6059 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6063 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6065 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6066 a.Type == TypeManager.conditional_attribute_type) {
6067 Report.Error (1667, a.Location,
6068 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6069 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6073 if (a.IsValidSecurityAttribute ()) {
6074 if (declarative_security == null)
6075 declarative_security = new ListDictionary ();
6076 a.ExtractSecurityPermissionSet (declarative_security);
6080 if (a.Target == AttributeTargets.Method) {
6081 method_data.MethodBuilder.SetCustomAttribute (cb);
6085 if (a.Target == AttributeTargets.ReturnValue) {
6086 if (return_attributes == null)
6087 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6089 return_attributes.ApplyAttributeBuilder (a, cb);
6093 ApplyToExtraTarget (a, cb);
6096 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6098 throw new NotSupportedException ("You forgot to define special attribute target handling");
6101 // It is not supported for the accessors
6102 public sealed override bool Define()
6104 throw new NotSupportedException ();
6107 public virtual void Emit (DeclSpace parent)
6109 method_data.Emit (parent);
6112 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6113 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6114 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6115 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6117 if (OptAttributes != null)
6118 OptAttributes.Emit ();
6120 if (declarative_security != null) {
6121 foreach (DictionaryEntry de in declarative_security) {
6122 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6129 public override bool EnableOverloadChecks (MemberCore overload)
6131 // This can only happen with indexers and it will
6132 // be catched as indexer difference
6133 if (overload is AbstractPropertyEventMethod)
6136 if (overload is MethodCore) {
6137 caching_flags |= Flags.MethodOverloadsExist;
6143 public override bool IsClsComplianceRequired()
6148 public bool IsDuplicateImplementation (MethodCore method)
6150 if (!MemberName.Equals (method.MemberName))
6153 Type[] param_types = method.ParameterTypes;
6155 if (param_types == null || param_types.Length != ParameterTypes.Length)
6158 for (int i = 0; i < param_types.Length; i++)
6159 if (param_types [i] != ParameterTypes [i])
6162 Report.SymbolRelatedToPreviousError (method);
6163 Report.Error (82, Location, "A member `{0}' is already reserved",
6164 method.GetSignatureForError ());
6168 public override bool IsUsed
6179 // Represents header string for documentation comment.
6181 public override string DocCommentHeader {
6182 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6185 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6190 // Properties and Indexers both generate PropertyBuilders, we use this to share
6191 // their common bits.
6193 abstract public class PropertyBase : PropertyBasedMember {
6195 public class GetMethod : PropertyMethod
6197 static string[] attribute_targets = new string [] { "method", "return" };
6199 public GetMethod (PropertyBase method):
6200 base (method, "get_")
6204 public GetMethod (PropertyBase method, Accessor accessor):
6205 base (method, accessor, "get_")
6209 public override MethodBuilder Define (DeclSpace parent)
6211 base.Define (parent);
6216 method_data = new MethodData (method, ModFlags, flags, this);
6218 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6221 return method_data.MethodBuilder;
6224 public override Type ReturnType {
6226 return method.MemberType;
6230 public override ParametersCompiled ParameterInfo {
6232 return ParametersCompiled.EmptyReadOnlyParameters;
6236 public override string[] ValidAttributeTargets {
6238 return attribute_targets;
6243 public class SetMethod : PropertyMethod {
6245 static string[] attribute_targets = new string [] { "method", "param", "return" };
6246 ImplicitParameter param_attr;
6247 protected ParametersCompiled parameters;
6249 public SetMethod (PropertyBase method) :
6250 base (method, "set_")
6252 parameters = new ParametersCompiled (
6253 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6256 public SetMethod (PropertyBase method, Accessor accessor):
6257 base (method, accessor, "set_")
6259 this.parameters = accessor.Parameters;
6262 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6264 if (a.Target == AttributeTargets.Parameter) {
6265 if (param_attr == null)
6266 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6268 param_attr.ApplyAttributeBuilder (a, cb);
6272 base.ApplyAttributeBuilder (a, cb);
6275 public override ParametersCompiled ParameterInfo {
6281 public override MethodBuilder Define (DeclSpace parent)
6283 parameters.Resolve (ResolveContext);
6285 base.Define (parent);
6290 method_data = new MethodData (method, ModFlags, flags, this);
6292 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6295 return method_data.MethodBuilder;
6298 public override Type ReturnType {
6300 return TypeManager.void_type;
6304 public override string[] ValidAttributeTargets {
6306 return attribute_targets;
6311 static string[] attribute_targets = new string [] { "property" };
6313 public abstract class PropertyMethod : AbstractPropertyEventMethod
6315 protected readonly PropertyBase method;
6316 protected MethodAttributes flags;
6318 public PropertyMethod (PropertyBase method, string prefix)
6319 : base (method, prefix)
6321 this.method = method;
6322 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6325 public PropertyMethod (PropertyBase method, Accessor accessor,
6327 : base (method, accessor, prefix)
6329 this.method = method;
6330 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6332 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6333 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6337 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6339 if (a.IsInternalMethodImplAttribute) {
6340 method.is_external_implementation = true;
6343 base.ApplyAttributeBuilder (a, cb);
6346 public override AttributeTargets AttributeTargets {
6348 return AttributeTargets.Method;
6352 public override bool IsClsComplianceRequired ()
6354 return method.IsClsComplianceRequired ();
6357 public virtual MethodBuilder Define (DeclSpace parent)
6359 CheckForDuplications ();
6362 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6363 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6364 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6366 Report.SymbolRelatedToPreviousError (mi);
6367 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6368 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6374 TypeContainer container = parent.PartialContainer;
6377 // Check for custom access modifier
6379 if ((ModFlags & Modifiers.Accessibility) == 0) {
6380 ModFlags |= method.ModFlags;
6381 flags = method.flags;
6383 if (container.Kind == Kind.Interface)
6384 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6385 GetSignatureForError ());
6387 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6388 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6391 CheckModifiers (ModFlags);
6392 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6393 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6394 flags = Modifiers.MethodAttr (ModFlags);
6395 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6398 CheckAbstractAndExtern (block != null);
6400 if (block != null && block.IsIterator)
6401 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6406 public bool HasCustomAccessModifier {
6408 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6412 public PropertyBase Property {
6418 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6420 return new EmitContext (this,
6421 ds, method.ds, method.Location, ig, ReturnType,
6422 method.ModFlags, false);
6425 public override ObsoleteAttribute GetObsoleteAttribute ()
6427 return method.GetObsoleteAttribute ();
6430 public override string GetSignatureForError()
6432 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6435 void CheckModifiers (int modflags)
6437 modflags &= Modifiers.Accessibility;
6439 int mflags = method.ModFlags & Modifiers.Accessibility;
6441 if ((mflags & Modifiers.PUBLIC) != 0) {
6442 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6444 else if ((mflags & Modifiers.PROTECTED) != 0) {
6445 if ((mflags & Modifiers.INTERNAL) != 0)
6446 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6448 flags |= Modifiers.PRIVATE;
6450 else if ((mflags & Modifiers.INTERNAL) != 0)
6451 flags |= Modifiers.PRIVATE;
6453 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6454 Report.Error (273, Location,
6455 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6456 GetSignatureForError (), method.GetSignatureForError ());
6460 protected bool CheckForDuplications ()
6462 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6465 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6469 public PropertyMethod Get, Set;
6470 public PropertyBuilder PropertyBuilder;
6471 public MethodBuilder GetBuilder, SetBuilder;
6473 protected bool define_set_first = false;
6475 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6476 int allowed_mod, MemberName name,
6477 Attributes attrs, bool define_set_first)
6478 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6480 this.define_set_first = define_set_first;
6483 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6485 if (a.HasSecurityAttribute) {
6486 a.Error_InvalidSecurityParent ();
6490 PropertyBuilder.SetCustomAttribute (cb);
6493 public override AttributeTargets AttributeTargets {
6495 return AttributeTargets.Property;
6499 protected override void DoMemberTypeDependentChecks ()
6501 base.DoMemberTypeDependentChecks ();
6505 if (MemberType.IsGenericParameter)
6509 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6510 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6514 protected override void DoMemberTypeIndependentChecks ()
6516 base.DoMemberTypeIndependentChecks ();
6519 // Accessors modifiers check
6521 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6522 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6523 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6524 GetSignatureForError ());
6527 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6528 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6529 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6530 Report.Error (276, Location,
6531 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6532 GetSignatureForError ());
6538 GetBuilder = Get.Define (Parent);
6539 return (Get.IsDummy) ? true : GetBuilder != null;
6542 bool DefineSet (bool define)
6547 SetBuilder = Set.Define (Parent);
6548 return (Set.IsDummy) ? true : SetBuilder != null;
6551 protected bool DefineAccessors ()
6553 return DefineSet (define_set_first) &&
6555 DefineSet (!define_set_first);
6558 protected abstract PropertyInfo ResolveBaseProperty ();
6560 // TODO: rename to Resolve......
6561 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6563 PropertyInfo base_property = ResolveBaseProperty ();
6564 if (base_property == null)
6567 base_ret_type = base_property.PropertyType;
6568 MethodInfo get_accessor = base_property.GetGetMethod (true);
6569 MethodInfo set_accessor = base_property.GetSetMethod (true);
6570 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6573 // Check base property accessors conflict
6575 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6576 if (get_accessor == null) {
6577 if (Get != null && !Get.IsDummy) {
6578 Report.SymbolRelatedToPreviousError (base_property);
6579 Report.Error (545, Location,
6580 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6581 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6584 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6586 if (!Get.IsDummy && !CheckAccessModifiers (
6587 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6588 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6591 if (set_accessor == null) {
6592 if (Set != null && !Set.IsDummy) {
6593 Report.SymbolRelatedToPreviousError (base_property);
6594 Report.Error (546, Location,
6595 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6596 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6599 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6601 if (!Set.IsDummy && !CheckAccessModifiers (
6602 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6603 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6607 // When one accessor does not exist and property hides base one
6608 // we need to propagate this upwards
6609 if (set_accessor == null)
6610 set_accessor = get_accessor;
6613 // Get the less restrictive access
6615 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6618 public override void Emit ()
6621 // The PropertyBuilder can be null for explicit implementations, in that
6622 // case, we do not actually emit the ".property", so there is nowhere to
6623 // put the attribute
6625 if (PropertyBuilder != null && OptAttributes != null)
6626 OptAttributes.Emit ();
6638 /// Tests whether accessors are not in collision with some method (CS0111)
6640 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6642 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6645 public override bool IsUsed
6651 return Get.IsUsed | Set.IsUsed;
6655 protected override void SetMemberName (MemberName new_name)
6657 base.SetMemberName (new_name);
6659 Get.UpdateName (this);
6660 Set.UpdateName (this);
6663 public override string[] ValidAttributeTargets {
6665 return attribute_targets;
6670 // Represents header string for documentation comment.
6672 public override string DocCommentHeader {
6673 get { return "P:"; }
6677 public class Property : PropertyBase
6679 public sealed class BackingField : Field
6681 readonly Property property;
6683 public BackingField (Property p)
6684 : base (p.Parent, p.type_name,
6685 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6686 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
6691 public override string GetSignatureForError ()
6693 return property.GetSignatureForError ();
6697 const int AllowedModifiers =
6700 Modifiers.PROTECTED |
6701 Modifiers.INTERNAL |
6705 Modifiers.OVERRIDE |
6706 Modifiers.ABSTRACT |
6711 const int AllowedInterfaceModifiers =
6714 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6715 MemberName name, Attributes attrs, Accessor get_block,
6716 Accessor set_block, bool define_set_first)
6717 : this (parent, type, mod, name, attrs, get_block, set_block,
6718 define_set_first, null)
6722 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6723 MemberName name, Attributes attrs, Accessor get_block,
6724 Accessor set_block, bool define_set_first, Block current_block)
6725 : base (parent, type, mod,
6726 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6727 name, attrs, define_set_first)
6729 if (get_block == null)
6730 Get = new GetMethod (this);
6732 Get = new GetMethod (this, get_block);
6734 if (set_block == null)
6735 Set = new SetMethod (this);
6737 Set = new SetMethod (this, set_block);
6739 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6740 get_block != null && get_block.Block == null &&
6741 set_block != null && set_block.Block == null) {
6742 if (RootContext.Version <= LanguageVersion.ISO_2)
6743 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6745 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
6746 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
6750 void CreateAutomaticProperty ()
6752 // Create backing field
6753 Field field = new BackingField (this);
6754 if (!field.Define ())
6757 Parent.PartialContainer.AddField (field);
6759 FieldExpr fe = new FieldExpr (field.FieldBuilder, Location);
6760 if ((field.ModFlags & Modifiers.STATIC) == 0)
6761 fe.InstanceExpression = new CompilerGeneratedThis (fe.Type, Location);
6764 Get.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
6765 Return r = new Return (fe, Location);
6766 Get.Block.AddStatement (r);
6769 Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
6770 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location));
6771 Set.Block.AddStatement (new StatementExpression (a));
6774 public override bool Define ()
6776 if (!base.Define ())
6779 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6781 if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6782 CreateAutomaticProperty ();
6784 if (!DefineAccessors ())
6790 // FIXME - PropertyAttributes.HasDefault ?
6792 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6793 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6796 PropertyBuilder.SetGetMethod (GetBuilder);
6797 Parent.MemberCache.AddMember (GetBuilder, Get);
6801 PropertyBuilder.SetSetMethod (SetBuilder);
6802 Parent.MemberCache.AddMember (SetBuilder, Set);
6805 TypeManager.RegisterProperty (PropertyBuilder, this);
6806 Parent.MemberCache.AddMember (PropertyBuilder, this);
6810 public override void Emit ()
6812 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6813 Report.Error (842, Location,
6814 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6815 GetSignatureForError ());
6821 protected override PropertyInfo ResolveBaseProperty ()
6823 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6824 Parent.TypeBuilder, Name, ParametersCompiled.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6829 /// Gigantic workaround for lameness in SRE follows :
6830 /// This class derives from EventInfo and attempts to basically
6831 /// wrap around the EventBuilder so that FindMembers can quickly
6832 /// return this in it search for members
6834 public class MyEventBuilder : EventInfo {
6837 // We use this to "point" to our Builder which is
6838 // not really a MemberInfo
6840 EventBuilder MyBuilder;
6843 // We "catch" and wrap these methods
6845 MethodInfo raise, remove, add;
6847 EventAttributes attributes;
6848 Type declaring_type, reflected_type, event_type;
6853 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6855 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6857 // And now store the values in our own fields.
6859 declaring_type = type_builder;
6861 reflected_type = type_builder;
6863 attributes = event_attr;
6866 this.event_type = event_type;
6870 // Methods that you have to override. Note that you only need
6871 // to "implement" the variants that take the argument (those are
6872 // the "abstract" methods, the others (GetAddMethod()) are
6875 public override MethodInfo GetAddMethod (bool nonPublic)
6880 public override MethodInfo GetRemoveMethod (bool nonPublic)
6885 public override MethodInfo GetRaiseMethod (bool nonPublic)
6891 // These methods make "MyEventInfo" look like a Builder
6893 public void SetRaiseMethod (MethodBuilder raiseMethod)
6895 raise = raiseMethod;
6896 MyBuilder.SetRaiseMethod (raiseMethod);
6899 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6901 remove = removeMethod;
6902 MyBuilder.SetRemoveOnMethod (removeMethod);
6905 public void SetAddOnMethod (MethodBuilder addMethod)
6908 MyBuilder.SetAddOnMethod (addMethod);
6911 public void SetCustomAttribute (CustomAttributeBuilder cb)
6913 MyBuilder.SetCustomAttribute (cb);
6916 public override object [] GetCustomAttributes (bool inherit)
6918 // FIXME : There's nothing which can be seemingly done here because
6919 // we have no way of getting at the custom attribute objects of the
6924 public override object [] GetCustomAttributes (Type t, bool inherit)
6926 // FIXME : Same here !
6930 public override bool IsDefined (Type t, bool b)
6935 public override EventAttributes Attributes {
6941 public override string Name {
6947 public override Type DeclaringType {
6949 return declaring_type;
6953 public override Type ReflectedType {
6955 return reflected_type;
6959 public Type EventType {
6965 public void SetUsed ()
6967 if (my_event != null) {
6968 // my_event.SetAssigned ();
6969 my_event.SetMemberIsUsed ();
6975 /// For case when event is declared like property (with add and remove accessors).
6977 public class EventProperty: Event {
6978 abstract class AEventPropertyAccessor : AEventAccessor
6980 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6981 base (method, accessor, prefix)
6985 public override MethodBuilder Define (DeclSpace ds)
6987 CheckAbstractAndExtern (block != null);
6988 return base.Define (ds);
6991 public override string GetSignatureForError ()
6993 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6997 sealed class AddDelegateMethod: AEventPropertyAccessor
6999 public AddDelegateMethod (Event method, Accessor accessor):
7000 base (method, accessor, "add_")
7005 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7007 public RemoveDelegateMethod (Event method, Accessor accessor):
7008 base (method, accessor, "remove_")
7014 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7016 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7018 Attributes attrs, Accessor add, Accessor remove)
7019 : base (parent, type, mod_flags, name, attrs)
7021 Add = new AddDelegateMethod (this, add);
7022 Remove = new RemoveDelegateMethod (this, remove);
7025 public override bool Define()
7027 if (!base.Define ())
7034 public override string[] ValidAttributeTargets {
7036 return attribute_targets;
7042 /// Event is declared like field.
7044 public class EventField : Event {
7045 abstract class EventFieldAccessor : AEventAccessor
7047 protected EventFieldAccessor (Event method, string prefix)
7048 : base (method, prefix)
7052 public override void Emit (DeclSpace parent)
7054 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
7055 if (parent is Class) {
7056 MethodBuilder mb = method_data.MethodBuilder;
7057 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7060 // TODO: because we cannot use generics yet
7061 FieldInfo field_info = ((EventField) method).BackingField.FieldBuilder;
7062 FieldExpr f_expr = new FieldExpr (field_info, Location);
7063 if ((method.ModFlags & Modifiers.STATIC) == 0)
7064 f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.FieldType, Location);
7066 block = new ToplevelBlock (ParameterInfo, Location);
7067 block.AddStatement (new StatementExpression (
7068 new CompoundAssign (Operation,
7070 block.GetParameterReference (ParameterInfo[0].Name, Location))));
7076 protected abstract Binary.Operator Operation { get; }
7079 sealed class AddDelegateMethod: EventFieldAccessor
7081 public AddDelegateMethod (Event method):
7082 base (method, "add_")
7086 protected override Binary.Operator Operation {
7087 get { return Binary.Operator.Addition; }
7091 sealed class RemoveDelegateMethod: EventFieldAccessor
7093 public RemoveDelegateMethod (Event method):
7094 base (method, "remove_")
7098 protected override Binary.Operator Operation {
7099 get { return Binary.Operator.Subtraction; }
7104 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7105 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7107 public Field BackingField;
7108 public Expression Initializer;
7110 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7111 : base (parent, type, mod_flags, name, attrs)
7113 Add = new AddDelegateMethod (this);
7114 Remove = new RemoveDelegateMethod (this);
7117 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7119 if (a.Target == AttributeTargets.Field) {
7120 BackingField.ApplyAttributeBuilder (a, cb);
7124 if (a.Target == AttributeTargets.Method) {
7125 int errors = Report.Errors;
7126 Add.ApplyAttributeBuilder (a, cb);
7127 if (errors == Report.Errors)
7128 Remove.ApplyAttributeBuilder (a, cb);
7132 base.ApplyAttributeBuilder (a, cb);
7135 public override bool Define()
7137 if (!base.Define ())
7140 if (Initializer != null && (ModFlags & Modifiers.ABSTRACT) != 0) {
7141 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7142 GetSignatureForError ());
7145 if (!HasBackingField)
7148 // FIXME: We are unable to detect whether generic event is used because
7149 // we are using FieldExpr instead of EventExpr for event access in that
7150 // case. When this issue will be fixed this hack can be removed.
7151 if (TypeManager.IsGenericType (MemberType))
7154 if (Add.IsInterfaceImplementation)
7157 TypeManager.RegisterEventField (EventBuilder, this);
7159 BackingField = new Field (Parent,
7160 new TypeExpression (MemberType, Location),
7161 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
7164 Parent.PartialContainer.AddField (BackingField);
7165 BackingField.Initializer = Initializer;
7166 BackingField.ModFlags &= ~Modifiers.COMPILER_GENERATED;
7168 // Call define because we passed fields definition
7169 return BackingField.Define ();
7172 bool HasBackingField {
7174 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
7178 public override string[] ValidAttributeTargets
7181 return HasBackingField ? attribute_targets : attribute_targets_interface;
7186 public abstract class Event : PropertyBasedMember {
7187 public abstract class AEventAccessor : AbstractPropertyEventMethod
7189 protected readonly Event method;
7190 ImplicitParameter param_attr;
7192 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7194 protected AEventAccessor (Event method, string prefix)
7195 : base (method, prefix)
7197 this.method = method;
7198 this.ModFlags = method.ModFlags;
7201 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7202 : base (method, accessor, prefix)
7204 this.method = method;
7205 this.ModFlags = method.ModFlags;
7208 public bool IsInterfaceImplementation {
7209 get { return method_data.implementing != null; }
7212 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7214 if (a.IsInternalMethodImplAttribute) {
7215 method.is_external_implementation = true;
7218 base.ApplyAttributeBuilder (a, cb);
7221 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7223 if (a.Target == AttributeTargets.Parameter) {
7224 if (param_attr == null)
7225 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7227 param_attr.ApplyAttributeBuilder (a, cb);
7231 base.ApplyAttributeBuilder (a, cb);
7234 public override AttributeTargets AttributeTargets {
7236 return AttributeTargets.Method;
7240 public override bool IsClsComplianceRequired ()
7242 return method.IsClsComplianceRequired ();
7245 public virtual MethodBuilder Define (DeclSpace parent)
7247 method_data = new MethodData (method, method.ModFlags,
7248 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7250 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7253 MethodBuilder mb = method_data.MethodBuilder;
7254 ParameterInfo.ApplyAttributes (mb);
7258 public override Type ReturnType {
7260 return TypeManager.void_type;
7264 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7266 return new EmitContext (
7267 this, method.Parent, Location, ig, ReturnType,
7268 method.ModFlags, false);
7271 public override ObsoleteAttribute GetObsoleteAttribute ()
7273 return method.GetObsoleteAttribute ();
7276 public override string[] ValidAttributeTargets {
7278 return attribute_targets;
7282 public override ParametersCompiled ParameterInfo {
7284 return method.parameters;
7290 const int AllowedModifiers =
7293 Modifiers.PROTECTED |
7294 Modifiers.INTERNAL |
7299 Modifiers.OVERRIDE |
7301 Modifiers.ABSTRACT |
7304 const int AllowedInterfaceModifiers =
7307 public AEventAccessor Add, Remove;
7308 public MyEventBuilder EventBuilder;
7309 public MethodBuilder AddBuilder, RemoveBuilder;
7311 ParametersCompiled parameters;
7313 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7314 : base (parent, null, type, mod_flags,
7315 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7320 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7322 if ((a.HasSecurityAttribute)) {
7323 a.Error_InvalidSecurityParent ();
7327 EventBuilder.SetCustomAttribute (cb);
7330 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7332 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7335 public override AttributeTargets AttributeTargets {
7337 return AttributeTargets.Event;
7341 public override bool Define ()
7343 if (!base.Define ())
7346 if (!TypeManager.IsDelegateType (MemberType)) {
7347 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7350 parameters = ParametersCompiled.CreateFullyResolved (
7351 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7356 if (TypeManager.delegate_combine_delegate_delegate == null) {
7357 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7358 TypeManager.delegate_type, "Combine", Location,
7359 TypeManager.delegate_type, TypeManager.delegate_type);
7361 if (TypeManager.delegate_remove_delegate_delegate == null) {
7362 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7363 TypeManager.delegate_type, "Remove", Location,
7364 TypeManager.delegate_type, TypeManager.delegate_type);
7368 // Now define the accessors
7371 AddBuilder = Add.Define (Parent);
7372 if (AddBuilder == null)
7375 RemoveBuilder = Remove.Define (Parent);
7376 if (RemoveBuilder == null)
7379 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7380 EventBuilder.SetAddOnMethod (AddBuilder);
7381 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7383 Parent.MemberCache.AddMember (EventBuilder, this);
7384 Parent.MemberCache.AddMember (AddBuilder, Add);
7385 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7390 public override void Emit ()
7392 if (OptAttributes != null) {
7393 OptAttributes.Emit ();
7397 Remove.Emit (Parent);
7402 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7404 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7405 Parent.TypeBuilder, Name);
7410 AParametersCollection pd = TypeManager.GetParameterData (mi);
7411 base_ret_type = pd.Types [0];
7416 // Represents header string for documentation comment.
7418 public override string DocCommentHeader {
7419 get { return "E:"; }
7424 public class Indexer : PropertyBase
7426 public class GetIndexerMethod : GetMethod
7428 ParametersCompiled parameters;
7430 public GetIndexerMethod (Indexer method):
7433 this.parameters = method.parameters;
7436 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7437 base (method, accessor)
7439 parameters = accessor.Parameters;
7442 public override MethodBuilder Define (DeclSpace parent)
7444 parameters.Resolve (ResolveContext);
7445 return base.Define (parent);
7448 public override bool EnableOverloadChecks (MemberCore overload)
7450 if (base.EnableOverloadChecks (overload)) {
7451 overload.caching_flags |= Flags.MethodOverloadsExist;
7458 public override ParametersCompiled ParameterInfo {
7465 public class SetIndexerMethod: SetMethod
7467 public SetIndexerMethod (Indexer method):
7470 parameters = ParametersCompiled.MergeGenerated (method.parameters, false, parameters [0], null);
7473 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7474 base (method, accessor)
7476 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7479 public override bool EnableOverloadChecks (MemberCore overload)
7481 if (base.EnableOverloadChecks (overload)) {
7482 overload.caching_flags |= Flags.MethodOverloadsExist;
7490 const int AllowedModifiers =
7493 Modifiers.PROTECTED |
7494 Modifiers.INTERNAL |
7498 Modifiers.OVERRIDE |
7503 const int AllowedInterfaceModifiers =
7506 public readonly ParametersCompiled parameters;
7508 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7509 ParametersCompiled parameters, Attributes attrs,
7510 Accessor get_block, Accessor set_block, bool define_set_first)
7511 : base (parent, type, mod,
7512 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7513 name, attrs, define_set_first)
7515 this.parameters = parameters;
7517 if (get_block == null)
7518 Get = new GetIndexerMethod (this);
7520 Get = new GetIndexerMethod (this, get_block);
7522 if (set_block == null)
7523 Set = new SetIndexerMethod (this);
7525 Set = new SetIndexerMethod (this, set_block);
7528 protected override bool CheckForDuplications ()
7530 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7533 public override bool Define ()
7535 if (!base.Define ())
7538 if (!DefineParameters (parameters))
7541 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7542 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7543 if (indexer_attr != null) {
7544 // Remove the attribute from the list because it is not emitted
7545 OptAttributes.Attrs.Remove (indexer_attr);
7547 string name = indexer_attr.GetIndexerAttributeValue ();
7553 if (IsExplicitImpl) {
7554 Report.Error (415, indexer_attr.Location,
7555 "The `IndexerName' attribute is valid only on an " +
7556 "indexer that is not an explicit interface member declaration");
7560 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7561 Report.Error (609, indexer_attr.Location,
7562 "Cannot set the `IndexerName' attribute on an indexer marked override");
7568 if (InterfaceType != null) {
7569 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7570 if (base_IndexerName != Name)
7571 ShortName = base_IndexerName;
7574 if (!Parent.PartialContainer.AddMember (this) ||
7575 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7578 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7580 if (!DefineAccessors ())
7587 // Now name the parameters
7589 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7590 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7593 PropertyBuilder.SetGetMethod (GetBuilder);
7594 Parent.MemberCache.AddMember (GetBuilder, Get);
7598 PropertyBuilder.SetSetMethod (SetBuilder);
7599 Parent.MemberCache.AddMember (SetBuilder, Set);
7602 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7603 Parent.MemberCache.AddMember (PropertyBuilder, this);
7607 public override bool EnableOverloadChecks (MemberCore overload)
7609 if (overload is Indexer) {
7610 caching_flags |= Flags.MethodOverloadsExist;
7614 return base.EnableOverloadChecks (overload);
7617 public override string GetDocCommentName (DeclSpace ds)
7619 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7622 public override string GetSignatureForError ()
7624 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7625 if (MemberName.Left != null) {
7627 sb.Append (MemberName.Left.GetSignatureForError ());
7630 sb.Append (".this");
7631 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7632 return sb.ToString ();
7635 protected override PropertyInfo ResolveBaseProperty ()
7637 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7638 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7641 protected override bool VerifyClsCompliance ()
7643 if (!base.VerifyClsCompliance ())
7646 parameters.VerifyClsCompliance ();
7651 public class Operator : MethodOrOperator {
7653 const int AllowedModifiers =
7659 public enum OpType : byte {
7669 // Unary and Binary operators
7692 // Implicit and Explicit
7696 // Just because of enum
7700 public readonly OpType OperatorType;
7702 static readonly string [] [] names;
7706 names = new string[(int)OpType.TOP][];
7707 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7708 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7709 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7710 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7711 names [(int) OpType.True] = new string [] { "true", "op_True" };
7712 names [(int) OpType.False] = new string [] { "false", "op_False" };
7713 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7714 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7715 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7716 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7717 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7718 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7719 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7720 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7721 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7722 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7723 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7724 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7725 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7726 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7727 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7728 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7729 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7730 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7731 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7732 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7735 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7736 int mod_flags, ParametersCompiled parameters,
7737 ToplevelBlock block, Attributes attrs, Location loc)
7738 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7739 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7741 OperatorType = type;
7745 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7747 if (a.Type == TypeManager.conditional_attribute_type) {
7748 Error_ConditionalAttributeIsNotValid ();
7752 base.ApplyAttributeBuilder (a, cb);
7755 public override bool Define ()
7757 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7758 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7759 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7762 if (!base.Define ())
7765 // imlicit and explicit operator of same types are not allowed
7766 if (OperatorType == OpType.Explicit)
7767 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7768 else if (OperatorType == OpType.Implicit)
7769 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7771 Type declaring_type = MethodData.DeclaringType;
7772 Type return_type = MemberType;
7773 Type first_arg_type = ParameterTypes [0];
7775 Type first_arg_type_unwrap = first_arg_type;
7776 if (TypeManager.IsNullableType (first_arg_type))
7777 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7779 Type return_type_unwrap = return_type;
7780 if (TypeManager.IsNullableType (return_type))
7781 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7784 // Rules for conversion operators
7786 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7787 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7788 Report.Error (555, Location,
7789 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7794 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7795 conv_type = first_arg_type;
7796 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7797 conv_type = return_type;
7799 Report.Error (556, Location,
7800 "User-defined conversion must convert to or from the enclosing type");
7805 // Because IsInterface and IsClass are not supported
7807 if (!TypeManager.IsGenericParameter (conv_type)) {
7808 if (conv_type.IsInterface) {
7809 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7810 GetSignatureForError ());
7814 if (conv_type.IsClass) {
7815 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7816 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7817 GetSignatureForError ());
7821 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7822 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7823 GetSignatureForError ());
7828 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7829 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7830 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");
7833 } else if (Parameters.Count == 1) {
7834 // Checks for Unary operators
7836 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7837 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7838 Report.Error (448, Location,
7839 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7842 if (first_arg_type != declaring_type) {
7844 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7849 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7850 Report.Error (562, Location,
7851 "The parameter type of a unary operator must be the containing type");
7855 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7856 if (return_type != TypeManager.bool_type){
7859 "The return type of operator True or False " +
7866 // Checks for Binary operators
7868 if (first_arg_type != declaring_type &&
7869 Parameters.Types [1] != declaring_type){
7872 "One of the parameters of a binary operator must " +
7873 "be the containing type");
7881 protected override bool ResolveMemberType ()
7883 if (!base.ResolveMemberType ())
7886 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7890 // Operator cannot be override
7891 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7896 public static string GetName (OpType ot)
7898 return names [(int) ot] [0];
7901 public static string GetName (string metadata_name)
7903 for (int i = 0; i < names.Length; ++i) {
7904 if (names [i] [1] == metadata_name)
7905 return names [i] [0];
7910 public static string GetMetadataName (OpType ot)
7912 return names [(int) ot] [1];
7915 public static string GetMetadataName (string name)
7917 for (int i = 0; i < names.Length; ++i) {
7918 if (names [i] [0] == name)
7919 return names [i] [1];
7924 public OpType GetMatchingOperator ()
7926 switch (OperatorType) {
7927 case OpType.Equality:
7928 return OpType.Inequality;
7929 case OpType.Inequality:
7930 return OpType.Equality;
7932 return OpType.False;
7935 case OpType.GreaterThan:
7936 return OpType.LessThan;
7937 case OpType.LessThan:
7938 return OpType.GreaterThan;
7939 case OpType.GreaterThanOrEqual:
7940 return OpType.LessThanOrEqual;
7941 case OpType.LessThanOrEqual:
7942 return OpType.GreaterThanOrEqual;
7948 public override string GetSignatureForError ()
7950 StringBuilder sb = new StringBuilder ();
7951 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7952 sb.AppendFormat ("{0}.{1} operator {2}",
7953 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7956 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7959 sb.Append (Parameters.GetSignatureForError ());
7960 return sb.ToString ();
7965 // This is used to compare method signatures
7967 struct MethodSignature {
7969 public Type RetType;
7970 public Type [] Parameters;
7973 /// This delegate is used to extract methods which have the
7974 /// same signature as the argument
7976 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7978 public MethodSignature (string name, Type ret_type, Type [] parameters)
7983 if (parameters == null)
7984 Parameters = Type.EmptyTypes;
7986 Parameters = parameters;
7989 public override string ToString ()
7992 if (Parameters.Length != 0){
7993 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7994 for (int i = 0; i < Parameters.Length; i++){
7995 sb.Append (Parameters [i]);
7996 if (i+1 < Parameters.Length)
7999 pars = sb.ToString ();
8002 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8005 public override int GetHashCode ()
8007 return Name.GetHashCode ();
8010 public override bool Equals (Object o)
8012 MethodSignature other = (MethodSignature) o;
8014 if (other.Name != Name)
8017 if (other.RetType != RetType)
8020 if (Parameters == null){
8021 if (other.Parameters == null)
8026 if (other.Parameters == null)
8029 int c = Parameters.Length;
8030 if (other.Parameters.Length != c)
8033 for (int i = 0; i < c; i++)
8034 if (other.Parameters [i] != Parameters [i])
8040 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8042 MethodSignature sig = (MethodSignature) filter_criteria;
8044 if (m.Name != sig.Name)
8048 MethodInfo mi = m as MethodInfo;
8049 PropertyInfo pi = m as PropertyInfo;
8052 ReturnType = mi.ReturnType;
8053 else if (pi != null)
8054 ReturnType = pi.PropertyType;
8059 // we use sig.RetType == null to mean `do not check the
8060 // method return value.
8062 if (sig.RetType != null) {
8063 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8069 args = TypeManager.GetParameterData (mi).Types;
8071 args = TypeManager.GetParameterData (pi).Types;
8072 Type [] sigp = sig.Parameters;
8074 if (args.Length != sigp.Length)
8077 for (int i = args.Length - 1; i >= 0; i--)
8078 if (!TypeManager.IsEqual (args [i], sigp [i]))