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 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 protected ArrayList type_bases;
235 protected bool members_defined;
236 bool members_defined_ok;
238 // The interfaces we implement.
239 protected Type[] ifaces;
241 // The base member cache and our member cache
242 MemberCache base_cache;
243 protected MemberCache member_cache;
245 public const string DefaultIndexerName = "Item";
247 private bool seen_normal_indexers = false;
248 private string indexer_name = DefaultIndexerName;
250 private CachedMethods cached_method;
252 ArrayList partial_parts;
255 /// The pending methods that need to be implemented
256 // (interfaces or abstract methods)
258 PendingImplementation pending;
260 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
261 Attributes attrs, Kind kind)
262 : base (ns, parent, name, attrs)
264 if (parent != null && parent.NamespaceEntry != ns)
265 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
268 this.PartialContainer = this;
271 public bool AddMember (MemberCore symbol)
273 return AddToContainer (symbol, symbol.MemberName.Basename);
276 protected virtual bool AddMemberType (DeclSpace ds)
278 return AddToContainer (ds, ds.Basename);
281 protected virtual void RemoveMemberType (DeclSpace ds)
283 RemoveFromContainer (ds.Basename);
286 public void AddConstant (Const constant)
288 if (!AddMember (constant))
291 if (constants == null)
292 constants = new MemberCoreArrayList ();
294 constants.Add (constant);
297 public TypeContainer AddTypeContainer (TypeContainer tc)
299 if (!AddMemberType (tc))
303 types = new MemberCoreArrayList ();
309 public virtual TypeContainer AddPartial (TypeContainer next_part)
311 return AddPartial (next_part, next_part.Basename);
314 protected TypeContainer AddPartial (TypeContainer next_part, string name)
316 next_part.ModFlags |= Modifiers.PARTIAL;
317 TypeContainer tc = defined_names [name] as TypeContainer;
320 return AddTypeContainer (next_part);
322 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
323 Report.SymbolRelatedToPreviousError (next_part);
324 Error_MissingPartialModifier (tc);
327 if (tc.Kind != next_part.Kind) {
328 Report.SymbolRelatedToPreviousError (tc);
329 Report.Error (261, next_part.Location,
330 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
331 next_part.GetSignatureForError ());
334 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
335 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
336 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
337 Report.SymbolRelatedToPreviousError (tc);
338 Report.Error (262, next_part.Location,
339 "Partial declarations of `{0}' have conflicting accessibility modifiers",
340 next_part.GetSignatureForError ());
343 if (tc.partial_parts == null)
344 tc.partial_parts = new ArrayList (1);
346 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
347 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
348 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
349 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
350 tc.ModFlags |= next_part.ModFlags;
352 tc.ModFlags |= next_part.ModFlags;
355 if (next_part.attributes != null) {
356 if (tc.attributes == null)
357 tc.attributes = next_part.attributes;
359 tc.attributes.AddAttributes (next_part.attributes.Attrs);
362 next_part.PartialContainer = tc;
363 tc.partial_parts.Add (next_part);
367 public virtual void RemoveTypeContainer (TypeContainer next_part)
370 types.Remove (next_part);
371 RemoveMemberType (next_part);
374 public void AddDelegate (Delegate d)
376 if (!AddMemberType (d))
379 if (delegates == null)
380 delegates = new MemberCoreArrayList ();
385 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
387 if (ordered_explicit_member_list == null) {
388 ordered_explicit_member_list = new MemberCoreArrayList ();
389 ordered_member_list = new MemberCoreArrayList ();
393 if (Kind == Kind.Interface) {
394 Report.Error (541, mc.Location,
395 "`{0}': explicit interface declaration can only be declared in a class or struct",
396 mc.GetSignatureForError ());
399 ordered_explicit_member_list.Add (mc);
400 alist.Insert (0, mc);
402 ordered_member_list.Add (mc);
408 public void AddMethod (Method method)
410 if (!AddToContainer (method, method.MemberName.Basename))
414 methods = new MemberCoreArrayList ();
416 if (method.MemberName.Left != null)
417 AddMemberToList (method, methods, true);
419 AddMemberToList (method, methods, false);
422 public void AddConstructor (Constructor c)
424 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
425 if (!AddToContainer (c, is_static ?
426 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
429 if (is_static && c.Parameters.IsEmpty){
430 if (default_static_constructor != null) {
431 Report.SymbolRelatedToPreviousError (default_static_constructor);
432 Report.Error (111, c.Location,
433 "A member `{0}' is already defined. Rename this member or use different parameter types",
434 c.GetSignatureForError ());
438 default_static_constructor = c;
440 if (c.Parameters.IsEmpty)
441 default_constructor = c;
443 if (instance_constructors == null)
444 instance_constructors = new MemberCoreArrayList ();
446 instance_constructors.Add (c);
450 public bool AddField (FieldBase field)
452 if (!AddMember (field))
456 fields = new MemberCoreArrayList ();
460 if ((field.ModFlags & Modifiers.STATIC) != 0)
463 if (first_nonstatic_field == null) {
464 first_nonstatic_field = field;
468 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
469 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
470 Report.Warning (282, 3, field.Location,
471 "struct instance field `{0}' found in different declaration from instance field `{1}'",
472 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
477 public void AddProperty (Property prop)
479 if (!AddMember (prop) ||
480 !AddMember (prop.Get) || !AddMember (prop.Set))
483 if (properties == null)
484 properties = new MemberCoreArrayList ();
486 if (prop.MemberName.Left != null)
487 AddMemberToList (prop, properties, true);
489 AddMemberToList (prop, properties, false);
492 public void AddEvent (Event e)
497 if (e is EventProperty) {
498 if (!AddMember (e.Add))
501 if (!AddMember (e.Remove))
506 events = new MemberCoreArrayList ();
512 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
514 public void AddIndexer (Indexer i)
516 if (indexers == null)
517 indexers = new ArrayList ();
519 if (i.IsExplicitImpl)
520 AddMemberToList (i, indexers, true);
522 AddMemberToList (i, indexers, false);
525 public void AddOperator (Operator op)
530 if (operators == null)
531 operators = new OperatorArrayList (this);
536 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
538 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
540 if (compiler_generated == null)
541 compiler_generated = new ArrayList ();
543 compiler_generated.Add (c);
546 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
548 if (a.Type == TypeManager.default_member_type) {
549 if (Indexers != null) {
550 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
555 base.ApplyAttributeBuilder (a, cb);
558 public override AttributeTargets AttributeTargets {
560 throw new NotSupportedException ();
564 public ArrayList Types {
570 public MemberCoreArrayList Methods {
576 public ArrayList Constants {
582 protected Type BaseType {
584 return TypeBuilder.BaseType;
588 public ArrayList Fields {
594 public ArrayList InstanceConstructors {
596 return instance_constructors;
600 public ArrayList Properties {
606 public ArrayList Events {
612 public ArrayList Indexers {
618 public ArrayList Operators {
624 public ArrayList Delegates {
630 protected override TypeAttributes TypeAttr {
632 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
636 public string IndexerName {
638 return indexers == null ? DefaultIndexerName : indexer_name;
642 public bool IsComImport {
644 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
647 return OptAttributes.Contains (TypeManager.comimport_attr_type);
651 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
653 if ((field.ModFlags & Modifiers.STATIC) != 0){
654 if (initialized_static_fields == null) {
655 PartialContainer.HasStaticFieldInitializer = true;
656 initialized_static_fields = new ArrayList (4);
659 initialized_static_fields.Add (expression);
661 if (initialized_fields == null)
662 initialized_fields = new ArrayList (4);
664 initialized_fields.Add (expression);
668 public void ResolveFieldInitializers (EmitContext ec)
670 if (partial_parts != null) {
671 foreach (TypeContainer part in partial_parts) {
672 part.DoResolveFieldInitializers (ec);
675 DoResolveFieldInitializers (ec);
678 void DoResolveFieldInitializers (EmitContext ec)
681 if (initialized_static_fields == null)
684 bool has_complex_initializer = !RootContext.Optimize;
686 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
687 for (i = 0; i < initialized_static_fields.Count; ++i) {
688 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
689 ExpressionStatement s = fi.ResolveStatement (ec);
691 s = EmptyExpressionStatement.Instance;
692 } else if (fi.IsComplexInitializer) {
693 has_complex_initializer |= true;
699 for (i = 0; i < initialized_static_fields.Count; ++i) {
700 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
702 // Need special check to not optimize code like this
703 // static int a = b = 5;
706 if (!has_complex_initializer && fi.IsDefaultInitializer)
709 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
715 if (initialized_fields == null)
718 for (int i = 0; i < initialized_fields.Count; ++i) {
719 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
720 ExpressionStatement s = fi.ResolveStatement (ec);
725 // Field is re-initialized to its default value => removed
727 if (fi.IsDefaultInitializer && RootContext.Optimize)
730 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
735 // Emits the instance field initializers
737 public bool EmitFieldInitializers (EmitContext ec)
739 if (partial_parts != null) {
740 foreach (TypeContainer part in partial_parts)
741 part.EmitFieldInitializers (ec);
747 fields = initialized_static_fields;
749 fields = initialized_fields;
755 foreach (FieldInitializer f in fields) {
756 f.EmitStatement (ec);
761 public override string DocComment {
773 public PendingImplementation PendingImplementations {
774 get { return pending; }
777 public override bool GetClsCompliantAttributeValue ()
779 if (PartialContainer != this)
780 return PartialContainer.GetClsCompliantAttributeValue ();
782 return base.GetClsCompliantAttributeValue ();
785 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
787 // FIXME: get rid of partial_parts and store lists of bases of each part here
788 // assumed, not verified: 'part' is in 'partial_parts'
789 ((TypeContainer) part).type_bases = bases;
793 /// This function computes the Base class and also the
794 /// list of interfaces that the class or struct @c implements.
796 /// The return value is an array (might be null) of
797 /// interfaces implemented (as Types).
799 /// The @base_class argument is set to the base object or null
800 /// if this is `System.Object'.
802 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
805 if (type_bases == null)
808 int count = type_bases.Count;
809 TypeExpr [] ifaces = null;
810 for (int i = 0, j = 0; i < count; i++){
811 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
814 // Standard ResolveAsTypeTerminal cannot be used in this case because
815 // it does ObsoleteAttribute and constraint checks which require
816 // base type to be set
818 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
819 if (fne_resolved == null)
822 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
823 base_class = fne_resolved;
828 ifaces = new TypeExpr [count - i];
830 if (fne_resolved.Type.IsInterface) {
831 for (int ii = 0; ii < j; ++ii) {
832 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
833 Report.Error (528, Location, "`{0}' is already listed in interface list",
834 fne_resolved.GetSignatureForError ());
839 if (Kind == Kind.Interface && !fne_resolved.AsAccessible (this)) {
840 Report.Error (61, fne.Location,
841 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
842 fne_resolved.GetSignatureForError (), GetSignatureForError ());
845 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
846 if (Kind != Kind.Class) {
847 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
848 } else if (base_class != null)
849 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
850 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
852 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
853 GetSignatureForError (), fne_resolved.GetSignatureForError ());
857 ifaces [j++] = fne_resolved;
863 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
865 ArrayList ifaces = new ArrayList (0);
866 if (iface_exprs != null)
867 ifaces.AddRange (iface_exprs);
869 foreach (TypeContainer part in partial_parts) {
870 TypeExpr new_base_class;
871 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
872 if (new_base_class != TypeManager.system_object_expr) {
873 if (base_class == TypeManager.system_object_expr)
874 base_class = new_base_class;
876 if (new_base_class != null && !new_base_class.Equals (base_class)) {
877 Report.SymbolRelatedToPreviousError (base_class.Location, "");
878 Report.Error (263, part.Location,
879 "Partial declarations of `{0}' must not specify different base classes",
880 part.GetSignatureForError ());
887 if (new_ifaces == null)
890 foreach (TypeExpr iface in new_ifaces) {
891 if (ifaces.Contains (iface))
898 if (ifaces.Count == 0)
901 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
904 bool CheckGenericInterfaces (Type[] ifaces)
907 ArrayList already_checked = new ArrayList ();
909 for (int i = 0; i < ifaces.Length; i++) {
910 Type iface = ifaces [i];
911 foreach (Type t in already_checked) {
915 Type[] inferred = new Type [CountTypeParameters];
916 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
919 Report.Error (695, Location,
920 "`{0}' cannot implement both `{1}' and `{2}' " +
921 "because they may unify for some type parameter substitutions",
922 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
923 TypeManager.CSharpName (t));
927 already_checked.Add (iface);
936 bool CreateTypeBuilder ()
939 Type default_parent = null;
940 if (Kind == Kind.Struct)
941 default_parent = TypeManager.value_type;
942 else if (Kind == Kind.Enum)
943 default_parent = TypeManager.enum_type;
946 // Sets .size to 1 for structs with no instance fields
948 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
951 if (TypeManager.NamespaceClash (Name, Location)) {
955 ModuleBuilder builder = CodeGen.Module.Builder;
956 TypeBuilder = builder.DefineType (
957 Name, TypeAttr, default_parent, type_size);
959 TypeBuilder builder = Parent.TypeBuilder;
961 TypeBuilder = builder.DefineNestedType (
962 Basename, TypeAttr, default_parent, type_size);
964 } catch (ArgumentException) {
965 Report.RuntimeMissingSupport (Location, "static classes");
969 TypeManager.AddUserType (this);
973 string[] param_names = new string [TypeParameters.Length];
974 for (int i = 0; i < TypeParameters.Length; i++)
975 param_names [i] = TypeParameters [i].Name;
977 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
979 int offset = CountTypeParameters - CurrentTypeParameters.Length;
980 for (int i = offset; i < gen_params.Length; i++)
981 CurrentTypeParameters [i - offset].Define (gen_params [i]);
988 bool DefineBaseTypes ()
990 iface_exprs = ResolveBaseTypes (out base_type);
991 if (partial_parts != null) {
992 iface_exprs = GetNormalPartialBases (ref base_type);
996 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
997 // which in turn should have called DefineType()s on base types if necessary.
999 // None of the code below should trigger DefineType()s on classes that we depend on.
1000 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1002 // Let's do it as soon as possible, since code below can call DefineType() on classes
1003 // that depend on us to be populated before they are.
1005 if (!(this is CompilerGeneratedClass))
1006 RootContext.RegisterOrder (this);
1008 if (!CheckRecursiveDefinition (this))
1011 if (base_type != null && base_type.Type != null) {
1012 TypeBuilder.SetParent (base_type.Type);
1015 // add interfaces that were not added at type creation
1016 if (iface_exprs != null) {
1017 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1021 foreach (Type itype in ifaces)
1022 TypeBuilder.AddInterfaceImplementation (itype);
1024 if (!CheckGenericInterfaces (ifaces))
1027 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1034 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1036 public TypeBuilder CreateType ()
1038 if (TypeBuilder != null)
1044 if (!CreateTypeBuilder ()) {
1049 if (partial_parts != null) {
1050 foreach (TypeContainer part in partial_parts)
1051 part.TypeBuilder = TypeBuilder;
1054 if (Types != null) {
1055 foreach (TypeContainer tc in Types) {
1056 if (tc.CreateType () == null) {
1068 public override TypeBuilder DefineType ()
1075 type_defined = true;
1077 if (CreateType () == null) {
1082 if (!DefineBaseTypes ()) {
1087 if (!DefineNestedTypes ()) {
1095 public override void SetParameterInfo (ArrayList constraints_list)
1097 base.SetParameterInfo (constraints_list);
1099 if (!is_generic || PartialContainer == this)
1102 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1103 for (int i = 0; i < tc_names.Length; ++i) {
1104 if (tc_names [i].Name != type_params [i].Name) {
1105 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1106 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1107 GetSignatureForError ());
1113 void UpdateTypeParameterConstraints (TypeContainer part)
1115 TypeParameter[] current_params = CurrentTypeParameters;
1116 for (int i = 0; i < current_params.Length; i++) {
1117 Constraints c = part.CurrentTypeParameters [i].Constraints;
1121 if (current_params [i].UpdateConstraints (part, c))
1124 Report.SymbolRelatedToPreviousError (Location, "");
1125 Report.Error (265, part.Location,
1126 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1127 GetSignatureForError (), current_params [i].GetSignatureForError ());
1131 public bool ResolveType ()
1133 if (!DoResolveType ())
1136 if (compiler_generated != null) {
1137 foreach (CompilerGeneratedClass c in compiler_generated)
1138 if (!c.ResolveType ())
1145 protected virtual bool DoResolveType ()
1147 if ((base_type != null) &&
1148 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1156 if (PartialContainer != this)
1157 throw new InternalErrorException ();
1159 TypeExpr current_type = null;
1161 foreach (TypeParameter type_param in CurrentTypeParameters) {
1162 if (!type_param.Resolve (this)) {
1168 if (partial_parts != null && is_generic) {
1169 foreach (TypeContainer part in partial_parts)
1170 UpdateTypeParameterConstraints (part);
1173 foreach (TypeParameter type_param in TypeParameters) {
1174 if (!type_param.DefineType (this)) {
1180 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1181 current_type = current_type.ResolveAsTypeTerminal (this, false);
1182 if (current_type == null) {
1187 CurrentType = current_type.Type;
1191 protected virtual bool DefineNestedTypes ()
1193 if (Types != null) {
1194 foreach (TypeContainer tc in Types)
1195 if (tc.DefineType () == null)
1199 if (Delegates != null) {
1200 foreach (Delegate d in Delegates)
1201 if (d.DefineType () == null)
1208 TypeContainer InTransit;
1210 protected bool CheckRecursiveDefinition (TypeContainer tc)
1212 if (InTransit != null) {
1213 Report.SymbolRelatedToPreviousError (this);
1214 if (this is Interface)
1216 529, tc.Location, "Inherited interface `{0}' causes a " +
1217 "cycle in the interface hierarchy of `{1}'",
1218 GetSignatureForError (), tc.GetSignatureForError ());
1221 146, tc.Location, "Circular base class dependency " +
1222 "involving `{0}' and `{1}'",
1223 tc.GetSignatureForError (), GetSignatureForError ());
1229 if (base_type != null && base_type.Type != null) {
1230 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1231 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1232 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1236 if (iface_exprs != null) {
1237 foreach (TypeExpr iface in iface_exprs) {
1238 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1239 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1240 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1245 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1253 /// Populates our TypeBuilder with fields and methods
1255 public override bool Define ()
1257 if (members_defined)
1258 return members_defined_ok;
1260 members_defined_ok = DoDefineMembers ();
1261 members_defined = true;
1263 return members_defined_ok;
1266 protected virtual bool DoDefineMembers ()
1268 if (iface_exprs != null) {
1269 foreach (TypeExpr iface in iface_exprs) {
1270 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1271 if ((oa != null) && !IsInObsoleteScope)
1272 AttributeTester.Report_ObsoleteMessage (
1273 oa, iface.GetSignatureForError (), Location);
1275 ConstructedType ct = iface as ConstructedType;
1276 if ((ct != null) && !ct.CheckConstraints (this))
1281 if (base_type != null) {
1282 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1283 if (obsolete_attr != null && !IsInObsoleteScope)
1284 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1286 ConstructedType ct = base_type as ConstructedType;
1287 if ((ct != null) && !ct.CheckConstraints (this))
1290 member_cache = new MemberCache (base_type.Type, this);
1291 } else if (Kind == Kind.Interface) {
1292 member_cache = new MemberCache (null, this);
1293 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1294 for (int i = 0; i < ifaces.Length; ++i)
1295 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1297 member_cache = new MemberCache (null, this);
1301 foreach (TypeContainer tc in types)
1302 member_cache.AddNestedType (tc);
1304 if (delegates != null)
1305 foreach (Delegate d in delegates)
1306 member_cache.AddNestedType (d);
1308 if (partial_parts != null) {
1309 foreach (TypeContainer part in partial_parts)
1310 part.member_cache = member_cache;
1314 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1315 if (conflict_symbol == null) {
1316 if ((ModFlags & Modifiers.NEW) != 0)
1317 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1319 if ((ModFlags & Modifiers.NEW) == 0) {
1320 Report.SymbolRelatedToPreviousError (conflict_symbol);
1321 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1322 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1327 DefineContainerMembers (constants);
1328 DefineContainerMembers (fields);
1330 if (Kind == Kind.Struct || Kind == Kind.Class) {
1331 pending = PendingImplementation.GetPendingImplementations (this);
1335 // Constructors are not in the defined_names array
1337 DefineContainerMembers (instance_constructors);
1339 DefineContainerMembers (events);
1340 DefineContainerMembers (ordered_explicit_member_list);
1341 DefineContainerMembers (ordered_member_list);
1343 DefineContainerMembers (operators);
1344 DefineContainerMembers (delegates);
1346 ComputeIndexerName();
1347 CheckEqualsAndGetHashCode();
1349 if (CurrentType != null) {
1350 GenericType = CurrentType;
1355 // FIXME: This hack is needed because member cache does not work
1356 // with generic types, we rely on runtime to inflate dynamic types.
1357 // TODO: This hack requires member cache refactoring to be removed
1359 if (TypeBuilder.IsGenericType)
1360 member_cache = new MemberCache (this);
1366 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1369 mcal.DefineContainerMembers ();
1372 protected virtual void ComputeIndexerName ()
1374 if (indexers == null)
1377 string class_indexer_name = null;
1380 // If there's both an explicit and an implicit interface implementation, the
1381 // explicit one actually implements the interface while the other one is just
1382 // a normal indexer. See bug #37714.
1385 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1386 foreach (Indexer i in indexers) {
1387 if (i.InterfaceType != null) {
1388 if (seen_normal_indexers)
1389 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1393 seen_normal_indexers = true;
1395 if (class_indexer_name == null) {
1396 class_indexer_name = i.ShortName;
1400 if (i.ShortName != class_indexer_name)
1401 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");
1404 if (class_indexer_name != null)
1405 indexer_name = class_indexer_name;
1408 protected virtual void EmitIndexerName ()
1410 if (!seen_normal_indexers)
1413 if (TypeManager.default_member_ctor == null) {
1414 if (TypeManager.default_member_type == null) {
1415 TypeManager.default_member_type = TypeManager.CoreLookupType (
1416 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1418 if (TypeManager.default_member_type == null)
1422 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1423 TypeManager.default_member_type, Location, TypeManager.string_type);
1425 if (TypeManager.default_member_ctor == null)
1429 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1430 TypeBuilder.SetCustomAttribute (cb);
1433 protected virtual void CheckEqualsAndGetHashCode ()
1435 if (methods == null)
1438 if (HasEquals && !HasGetHashCode) {
1439 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1443 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1445 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1449 /// This function is based by a delegate to the FindMembers routine
1451 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1457 /// This filter is used by FindMembers, and we just keep
1458 /// a global for the filter to `AlwaysAccept'
1460 static MemberFilter accepting_filter;
1463 static TypeContainer ()
1465 accepting_filter = new MemberFilter (AlwaysAccept);
1468 public MethodInfo[] GetMethods ()
1470 ArrayList members = new ArrayList ();
1474 if (methods != null) {
1475 int len = methods.Count;
1476 for (int i = 0; i < len; i++) {
1477 Method m = (Method) methods [i];
1479 members.Add (m.MethodBuilder);
1483 if (operators != null) {
1484 int len = operators.Count;
1485 for (int i = 0; i < len; i++) {
1486 Operator o = (Operator) operators [i];
1488 members.Add (o.MethodBuilder);
1492 if (properties != null) {
1493 int len = properties.Count;
1494 for (int i = 0; i < len; i++) {
1495 Property p = (Property) properties [i];
1497 if (p.GetBuilder != null)
1498 members.Add (p.GetBuilder);
1499 if (p.SetBuilder != null)
1500 members.Add (p.SetBuilder);
1504 if (indexers != null) {
1505 int len = indexers.Count;
1506 for (int i = 0; i < len; i++) {
1507 Indexer ix = (Indexer) indexers [i];
1509 if (ix.GetBuilder != null)
1510 members.Add (ix.GetBuilder);
1511 if (ix.SetBuilder != null)
1512 members.Add (ix.SetBuilder);
1516 if (events != null) {
1517 int len = events.Count;
1518 for (int i = 0; i < len; i++) {
1519 Event e = (Event) events [i];
1521 if (e.AddBuilder != null)
1522 members.Add (e.AddBuilder);
1523 if (e.RemoveBuilder != null)
1524 members.Add (e.RemoveBuilder);
1528 MethodInfo[] retMethods = new MethodInfo [members.Count];
1529 members.CopyTo (retMethods, 0);
1533 // Indicated whether container has StructLayout attribute set Explicit
1534 public bool HasExplicitLayout {
1535 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1536 set { caching_flags |= Flags.HasExplicitLayout; }
1539 public bool HasStructLayout {
1540 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1541 set { caching_flags |= Flags.HasStructLayout; }
1545 // Return the nested type with name @name. Ensures that the nested type
1546 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1548 public Type FindNestedType (string name)
1550 if (PartialContainer != this)
1551 throw new InternalErrorException ("should not happen");
1553 ArrayList [] lists = { types, delegates };
1555 for (int j = 0; j < lists.Length; ++j) {
1556 ArrayList list = lists [j];
1560 int len = list.Count;
1561 for (int i = 0; i < len; ++i) {
1562 DeclSpace ds = (DeclSpace) list [i];
1563 if (ds.Basename == name) {
1564 return ds.DefineType ();
1572 private void FindMembers_NestedTypes (int modflags,
1573 BindingFlags bf, MemberFilter filter, object criteria,
1574 ref ArrayList members)
1576 ArrayList [] lists = { types, delegates };
1578 for (int j = 0; j < lists.Length; ++j) {
1579 ArrayList list = lists [j];
1583 int len = list.Count;
1584 for (int i = 0; i < len; i++) {
1585 DeclSpace ds = (DeclSpace) list [i];
1587 if ((ds.ModFlags & modflags) == 0)
1590 TypeBuilder tb = ds.TypeBuilder;
1592 if (!(criteria is string) || ds.Basename.Equals (criteria))
1593 tb = ds.DefineType ();
1596 if (tb != null && (filter (tb, criteria) == true)) {
1597 if (members == null)
1598 members = new ArrayList ();
1607 /// This method returns the members of this type just like Type.FindMembers would
1608 /// Only, we need to use this for types which are _being_ defined because MS'
1609 /// implementation can't take care of that.
1612 // FIXME: return an empty static array instead of null, that cleans up
1613 // some code and is consistent with some coding conventions I just found
1617 // Notice that in various cases we check if our field is non-null,
1618 // something that would normally mean that there was a bug elsewhere.
1620 // The problem happens while we are defining p-invoke methods, as those
1621 // will trigger a FindMembers, but this happens before things are defined
1623 // Since the whole process is a no-op, it is fine to check for null here.
1625 // TODO: This approach will be one day completely removed, it's already
1626 // used at few places only
1629 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1630 MemberFilter filter, object criteria)
1632 ArrayList members = null;
1635 if ((bf & BindingFlags.Public) != 0)
1636 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1638 if ((bf & BindingFlags.NonPublic) != 0)
1639 modflags |= Modifiers.PRIVATE;
1641 int static_mask = 0, static_flags = 0;
1642 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1643 case BindingFlags.Static:
1644 static_mask = static_flags = Modifiers.STATIC;
1647 case BindingFlags.Instance:
1648 static_mask = Modifiers.STATIC;
1653 static_mask = static_flags = 0;
1657 Timer.StartTimer (TimerType.TcFindMembers);
1660 filter = accepting_filter;
1662 if ((mt & MemberTypes.Field) != 0) {
1663 if (fields != null) {
1664 int len = fields.Count;
1665 for (int i = 0; i < len; i++) {
1666 FieldBase f = (FieldBase) fields [i];
1668 if ((f.ModFlags & modflags) == 0)
1670 if ((f.ModFlags & static_mask) != static_flags)
1673 FieldBuilder fb = f.FieldBuilder;
1674 if (fb != null && filter (fb, criteria) == true) {
1675 if (members == null)
1676 members = new ArrayList ();
1683 if (constants != null) {
1684 int len = constants.Count;
1685 for (int i = 0; i < len; i++) {
1686 Const con = (Const) constants [i];
1688 if ((con.ModFlags & modflags) == 0)
1690 if ((con.ModFlags & static_mask) != static_flags)
1693 FieldBuilder fb = con.FieldBuilder;
1696 fb = con.FieldBuilder;
1698 if (fb != null && filter (fb, criteria) == true) {
1699 if (members == null)
1700 members = new ArrayList ();
1708 if ((mt & MemberTypes.Method) != 0) {
1709 if (methods != null) {
1710 int len = methods.Count;
1711 for (int i = 0; i < len; i++) {
1712 Method m = (Method) methods [i];
1714 if ((m.ModFlags & modflags) == 0)
1716 if ((m.ModFlags & static_mask) != static_flags)
1719 MethodBuilder mb = m.MethodBuilder;
1721 if (mb != null && filter (mb, criteria) == true) {
1722 if (members == null)
1723 members = new ArrayList ();
1730 if (operators != null) {
1731 int len = operators.Count;
1732 for (int i = 0; i < len; i++) {
1733 Operator o = (Operator) operators [i];
1735 if ((o.ModFlags & modflags) == 0)
1737 if ((o.ModFlags & static_mask) != static_flags)
1740 MethodBuilder ob = o.MethodBuilder;
1741 if (ob != null && filter (ob, criteria) == true) {
1742 if (members == null)
1743 members = new ArrayList ();
1750 if (events != null) {
1751 foreach (Event e in events) {
1752 if ((e.ModFlags & modflags) == 0)
1754 if ((e.ModFlags & static_mask) != static_flags)
1757 MethodBuilder b = e.AddBuilder;
1758 if (b != null && filter (b, criteria)) {
1759 if (members == null)
1760 members = new ArrayList (4);
1765 b = e.RemoveBuilder;
1766 if (b != null && filter (b, criteria)) {
1767 if (members == null)
1768 members = new ArrayList (4);
1775 if (properties != null) {
1776 int len = properties.Count;
1777 for (int i = 0; i < len; i++) {
1778 Property p = (Property) properties [i];
1780 if ((p.ModFlags & modflags) == 0)
1782 if ((p.ModFlags & static_mask) != static_flags)
1788 if (b != null && filter (b, criteria) == true) {
1789 if (members == null)
1790 members = new ArrayList ();
1796 if (b != null && filter (b, criteria) == true) {
1797 if (members == null)
1798 members = new ArrayList ();
1805 if (indexers != null) {
1806 int len = indexers.Count;
1807 for (int i = 0; i < len; i++) {
1808 Indexer ix = (Indexer) indexers [i];
1810 if ((ix.ModFlags & modflags) == 0)
1812 if ((ix.ModFlags & static_mask) != static_flags)
1818 if (b != null && filter (b, criteria) == true) {
1819 if (members == null)
1820 members = new ArrayList ();
1826 if (b != null && filter (b, criteria) == true) {
1827 if (members == null)
1828 members = new ArrayList ();
1836 if ((mt & MemberTypes.Event) != 0) {
1837 if (events != null) {
1838 int len = events.Count;
1839 for (int i = 0; i < len; i++) {
1840 Event e = (Event) events [i];
1842 if ((e.ModFlags & modflags) == 0)
1844 if ((e.ModFlags & static_mask) != static_flags)
1847 MemberInfo eb = e.EventBuilder;
1848 if (eb != null && filter (eb, criteria) == true) {
1849 if (members == null)
1850 members = new ArrayList ();
1852 members.Add (e.EventBuilder);
1858 if ((mt & MemberTypes.Property) != 0){
1859 if (properties != null) {
1860 int len = properties.Count;
1861 for (int i = 0; i < len; i++) {
1862 Property p = (Property) properties [i];
1864 if ((p.ModFlags & modflags) == 0)
1866 if ((p.ModFlags & static_mask) != static_flags)
1869 MemberInfo pb = p.PropertyBuilder;
1870 if (pb != null && filter (pb, criteria) == true) {
1871 if (members == null)
1872 members = new ArrayList ();
1874 members.Add (p.PropertyBuilder);
1879 if (indexers != null) {
1880 int len = indexers.Count;
1881 for (int i = 0; i < len; i++) {
1882 Indexer ix = (Indexer) indexers [i];
1884 if ((ix.ModFlags & modflags) == 0)
1886 if ((ix.ModFlags & static_mask) != static_flags)
1889 MemberInfo ib = ix.PropertyBuilder;
1890 if (ib != null && filter (ib, criteria) == true) {
1891 if (members == null)
1892 members = new ArrayList ();
1894 members.Add (ix.PropertyBuilder);
1900 if ((mt & MemberTypes.NestedType) != 0)
1901 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1903 if ((mt & MemberTypes.Constructor) != 0){
1904 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1905 int len = instance_constructors.Count;
1906 for (int i = 0; i < len; i++) {
1907 Constructor c = (Constructor) instance_constructors [i];
1909 ConstructorBuilder cb = c.ConstructorBuilder;
1910 if (cb != null && filter (cb, criteria) == true) {
1911 if (members == null)
1912 members = new ArrayList ();
1919 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1920 ConstructorBuilder cb =
1921 default_static_constructor.ConstructorBuilder;
1923 if (cb != null && filter (cb, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1933 // Lookup members in base if requested.
1935 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1936 if (TypeBuilder.BaseType != null) {
1937 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1938 if (list.Count > 0) {
1939 if (members == null)
1940 members = new ArrayList ();
1942 members.AddRange (list);
1947 Timer.StopTimer (TimerType.TcFindMembers);
1949 if (members == null)
1950 return MemberList.Empty;
1952 return new MemberList (members);
1955 public override MemberCache MemberCache {
1957 return member_cache;
1961 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1962 MemberFilter filter, object criteria)
1964 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1967 return ds.FindMembers (mt, bf, filter, criteria);
1969 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1973 /// Emits the values for the constants
1975 public void EmitConstants ()
1977 if (constants != null)
1978 foreach (Const con in constants)
1983 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1988 foreach (MemberCore mc in al) {
1989 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1992 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1993 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1998 public virtual void VerifyMembers ()
2001 // Check for internal or private fields that were never assigned
2003 if (Report.WarningLevel >= 3) {
2004 CheckMemberUsage (properties, "property");
2005 CheckMemberUsage (methods, "method");
2006 CheckMemberUsage (constants, "constant");
2008 if (fields != null){
2009 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2010 foreach (FieldBase f in fields) {
2011 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2012 if (is_type_exposed)
2015 f.SetMemberIsUsed ();
2019 if ((f.caching_flags & Flags.IsAssigned) == 0)
2020 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2023 const int error_code = 414;
2025 const int error_code = 169;
2027 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2028 f.GetSignatureForError ());
2034 // Only report 649 on level 4
2036 if (Report.WarningLevel < 4)
2039 if ((f.caching_flags & Flags.IsAssigned) != 0)
2043 // Don't be pendatic over serializable attributes
2045 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2048 Constant c = New.Constantify (f.MemberType);
2049 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2050 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2056 // TODO: move to ClassOrStruct
2057 void EmitConstructors ()
2059 if (instance_constructors == null)
2062 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2063 bool has_compliant_args = false;
2065 foreach (Constructor c in instance_constructors) {
2069 catch (Exception e) {
2070 throw new InternalErrorException (c, e);
2073 if (has_compliant_args)
2076 has_compliant_args = c.HasCompliantArgs;
2078 if (!has_compliant_args)
2079 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2081 foreach (Constructor c in instance_constructors) {
2085 catch (Exception e) {
2086 throw new InternalErrorException (c, e);
2093 /// Emits the code, this step is performed after all
2094 /// the types, enumerations, constructors
2096 public virtual void EmitType ()
2098 if (OptAttributes != null)
2099 OptAttributes.Emit ();
2103 EmitConstructors ();
2105 // Can not continue if constants are broken
2107 if (Report.Errors > 0)
2110 if (default_static_constructor != null)
2111 default_static_constructor.Emit ();
2113 if (operators != null)
2114 foreach (Operator o in operators)
2117 if (properties != null)
2118 foreach (Property p in properties)
2121 if (indexers != null) {
2122 foreach (Indexer indx in indexers)
2127 if (events != null){
2128 foreach (Event e in Events)
2132 if (methods != null) {
2133 for (int i = 0; i < methods.Count; ++i)
2134 ((Method) methods [i]).Emit ();
2138 foreach (FieldBase f in fields)
2141 if (delegates != null) {
2142 foreach (Delegate d in Delegates) {
2147 if (pending != null)
2148 pending.VerifyPendingMethods ();
2150 if (Report.Errors > 0)
2153 if (compiler_generated != null) {
2154 for (int i = 0; i < compiler_generated.Count; ++i)
2155 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2159 public override void CloseType ()
2161 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2165 caching_flags |= Flags.CloseTypeCreated;
2166 TypeBuilder.CreateType ();
2167 } catch (TypeLoadException){
2169 // This is fine, the code still created the type
2171 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2172 // Console.WriteLine (e.Message);
2173 } catch (Exception e) {
2174 throw new InternalErrorException (this, e);
2178 foreach (TypeContainer tc in Types)
2179 if (tc.Kind == Kind.Struct)
2182 foreach (TypeContainer tc in Types)
2183 if (tc.Kind != Kind.Struct)
2187 if (Delegates != null)
2188 foreach (Delegate d in Delegates)
2191 if (compiler_generated != null)
2192 foreach (CompilerGeneratedClass c in compiler_generated)
2199 initialized_fields = null;
2200 initialized_static_fields = null;
2202 ordered_explicit_member_list = null;
2203 ordered_member_list = null;
2208 compiler_generated = null;
2209 default_constructor = null;
2210 default_static_constructor = null;
2212 OptAttributes = null;
2215 member_cache = null;
2219 // Performs the validation on a Method's modifiers (properties have
2220 // the same properties).
2222 public bool MethodModifiersValid (MemberCore mc)
2224 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2225 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2226 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2228 int flags = mc.ModFlags;
2231 // At most one of static, virtual or override
2233 if ((flags & Modifiers.STATIC) != 0){
2234 if ((flags & vao) != 0){
2235 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2236 mc.GetSignatureForError ());
2241 if (Kind == Kind.Struct){
2242 if ((flags & va) != 0){
2243 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2248 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2249 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2250 mc.GetSignatureForError ());
2255 // If the declaration includes the abstract modifier, then the
2256 // declaration does not include static, virtual or extern
2258 if ((flags & Modifiers.ABSTRACT) != 0){
2259 if ((flags & Modifiers.EXTERN) != 0){
2261 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2265 if ((flags & Modifiers.SEALED) != 0) {
2266 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2270 if ((flags & Modifiers.VIRTUAL) != 0){
2271 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2275 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2276 Report.SymbolRelatedToPreviousError (this);
2277 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2278 mc.GetSignatureForError (), GetSignatureForError ());
2283 if ((flags & Modifiers.PRIVATE) != 0){
2284 if ((flags & vao) != 0){
2285 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2290 if ((flags & Modifiers.SEALED) != 0){
2291 if ((flags & Modifiers.OVERRIDE) == 0){
2292 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2300 public Constructor DefaultStaticConstructor {
2301 get { return default_static_constructor; }
2304 protected override bool VerifyClsCompliance ()
2306 if (!base.VerifyClsCompliance ())
2311 Type base_type = TypeBuilder.BaseType;
2312 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2313 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2320 /// Checks whether container name is CLS Compliant
2322 void VerifyClsName ()
2324 Hashtable base_members = base_cache == null ?
2326 base_cache.GetPublicMembers ();
2327 Hashtable this_members = new Hashtable ();
2329 foreach (DictionaryEntry entry in defined_names) {
2330 MemberCore mc = (MemberCore)entry.Value;
2331 if (!mc.IsClsComplianceRequired ())
2334 string name = (string) entry.Key;
2335 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2337 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2338 object found = base_members [lcase];
2339 if (found == null) {
2340 found = this_members [lcase];
2341 if (found == null) {
2342 this_members.Add (lcase, mc);
2347 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2350 if (found is MemberInfo) {
2351 if (basename == ((MemberInfo) found).Name)
2353 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2355 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2358 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2364 /// Performs checks for an explicit interface implementation. First it
2365 /// checks whether the `interface_type' is a base inteface implementation.
2366 /// Then it checks whether `name' exists in the interface type.
2368 public bool VerifyImplements (InterfaceMemberBase mb)
2370 if (ifaces != null) {
2371 foreach (Type t in ifaces){
2372 if (TypeManager.IsEqual (t, mb.InterfaceType))
2377 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2378 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2379 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2383 public override Type LookupAnyGeneric (string typeName)
2385 if (types != null) {
2386 foreach (TypeContainer tc in types) {
2390 int pos = tc.Basename.LastIndexOf ('`');
2391 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2392 return tc.TypeBuilder;
2396 return base.LookupAnyGeneric (typeName);
2399 public void Mark_HasEquals ()
2401 cached_method |= CachedMethods.Equals;
2404 public void Mark_HasGetHashCode ()
2406 cached_method |= CachedMethods.GetHashCode;
2410 /// Method container contains Equals method
2412 public bool HasEquals {
2414 return (cached_method & CachedMethods.Equals) != 0;
2419 /// Method container contains GetHashCode method
2421 public bool HasGetHashCode {
2423 return (cached_method & CachedMethods.GetHashCode) != 0;
2427 public bool HasStaticFieldInitializer {
2429 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2433 cached_method |= CachedMethods.HasStaticFieldInitializer;
2435 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2443 string IMemberContainer.Name {
2449 Type IMemberContainer.Type {
2455 bool IMemberContainer.IsInterface {
2457 return Kind == Kind.Interface;
2461 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2463 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2465 if (GenericType != null)
2466 return TypeManager.FindMembers (GenericType, mt, new_bf,
2469 return FindMembers (mt, new_bf, null, null);
2473 // Generates xml doc comments (if any), and if required,
2474 // handle warning report.
2476 internal override void GenerateDocComment (DeclSpace ds)
2478 DocUtil.GenerateTypeDocComment (this, ds);
2481 public override string DocCommentHeader {
2482 get { return "T:"; }
2485 public MemberCache BaseCache {
2487 if (base_cache != null)
2489 if (TypeBuilder.BaseType != null)
2490 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2491 if (TypeBuilder.IsInterface)
2492 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2498 public abstract class ClassOrStruct : TypeContainer {
2499 ListDictionary declarative_security;
2501 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2502 MemberName name, Attributes attrs, Kind kind)
2503 : base (ns, parent, name, attrs, kind)
2507 protected override bool AddToContainer (MemberCore symbol, string name)
2509 if (name == MemberName.Name && symbol.MemberName.Left == null) {
2510 if (symbol is TypeParameter) {
2511 Report.Error (694, symbol.Location,
2512 "Type parameter `{0}' has same name as containing type, or method",
2513 symbol.GetSignatureForError ());
2517 Report.SymbolRelatedToPreviousError (this);
2518 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2519 symbol.GetSignatureForError ());
2523 return base.AddToContainer (symbol, name);
2526 public override void VerifyMembers ()
2528 base.VerifyMembers ();
2530 if ((events != null) && Report.WarningLevel >= 3) {
2531 foreach (Event e in events){
2532 // Note: The event can be assigned from same class only, so we can report
2533 // this warning for all accessibility modes
2534 if ((e.caching_flags & Flags.IsUsed) == 0)
2535 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2540 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2542 if (a.IsValidSecurityAttribute ()) {
2543 if (declarative_security == null)
2544 declarative_security = new ListDictionary ();
2546 a.ExtractSecurityPermissionSet (declarative_security);
2550 if (a.Type == TypeManager.struct_layout_attribute_type) {
2551 PartialContainer.HasStructLayout = true;
2553 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2554 PartialContainer.HasExplicitLayout = true;
2557 base.ApplyAttributeBuilder (a, cb);
2561 /// Defines the default constructors
2563 protected void DefineDefaultConstructor (bool is_static)
2565 // The default instance constructor is public
2566 // If the class is abstract, the default constructor is protected
2567 // The default static constructor is private
2571 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2573 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2576 Constructor c = new Constructor (this, MemberName.Name, mods,
2577 null, Parameters.EmptyReadOnlyParameters,
2578 new GeneratedBaseInitializer (Location),
2582 c.Block = new ToplevelBlock (null, Location);
2585 public override bool Define ()
2587 CheckProtectedModifier ();
2591 if (default_static_constructor != null)
2592 default_static_constructor.Define ();
2597 public override void Emit ()
2599 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2600 DefineDefaultConstructor (true);
2601 default_static_constructor.Define ();
2606 if (declarative_security != null) {
2607 foreach (DictionaryEntry de in declarative_security) {
2608 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2613 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2615 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2618 protected override TypeAttributes TypeAttr {
2620 if (default_static_constructor == null)
2621 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2623 return base.TypeAttr;
2629 // TODO: should be sealed
2630 public class Class : ClassOrStruct {
2631 const int AllowedModifiers =
2634 Modifiers.PROTECTED |
2635 Modifiers.INTERNAL |
2637 Modifiers.ABSTRACT |
2642 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2644 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2646 : base (ns, parent, name, attrs, Kind.Class)
2648 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2649 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2651 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2652 Report.FeatureIsNotAvailable (Location, "static classes");
2656 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2658 if (part.Name == "System.Object")
2659 Report.Error (537, part.Location,
2660 "The class System.Object cannot have a base class or implement an interface.");
2661 base.AddBasesForPart (part, bases);
2664 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2666 if (a.Type == TypeManager.attribute_usage_type) {
2667 if (!TypeManager.IsAttributeType (BaseType) &&
2668 TypeBuilder.FullName != "System.Attribute") {
2669 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2673 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2674 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2678 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2679 !attributes.Contains (TypeManager.guid_attr_type)) {
2680 a.Error_MissingGuidAttribute ();
2684 if (a.Type == TypeManager.extension_attribute_type) {
2685 a.Error_MisusedExtensionAttribute ();
2689 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2692 base.ApplyAttributeBuilder (a, cb);
2695 public override AttributeTargets AttributeTargets {
2697 return AttributeTargets.Class;
2701 protected override void DefineContainerMembers (MemberCoreArrayList list)
2707 base.DefineContainerMembers (list);
2711 foreach (MemberCore m in list) {
2712 if (m is Operator) {
2713 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2717 if (m is Destructor) {
2718 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2723 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2727 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2730 if (m is Constructor) {
2731 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2735 Method method = m as Method;
2736 if (method != null && method.Parameters.HasExtensionMethodType) {
2737 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2741 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2744 base.DefineContainerMembers (list);
2747 public override bool Define ()
2749 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2750 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2753 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2754 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2757 return base.Define ();
2760 protected override bool DoDefineMembers ()
2762 if (InstanceConstructors == null && !IsStatic)
2763 DefineDefaultConstructor (false);
2765 return base.DoDefineMembers ();
2768 public override void Emit ()
2773 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2774 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2778 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2780 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2782 if (base_class == null) {
2783 if (RootContext.StdLib)
2784 base_class = TypeManager.system_object_expr;
2785 else if (Name != "System.Object")
2786 base_class = TypeManager.system_object_expr;
2788 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2790 689, base_class.Location,
2791 "Cannot derive from `{0}' because it is a type parameter",
2792 base_class.GetSignatureForError ());
2796 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2797 Report.Error (698, base_class.Location,
2798 "A generic type cannot derive from `{0}' because it is an attribute class",
2799 base_class.GetSignatureForError ());
2802 if (base_class.IsSealed){
2803 Report.SymbolRelatedToPreviousError (base_class.Type);
2804 if (base_class.Type.IsAbstract) {
2805 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2806 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2808 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2809 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2814 if (!base_class.CanInheritFrom ()){
2815 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2816 GetSignatureForError (), base_class.GetSignatureForError ());
2820 if (!base_class.AsAccessible (this)) {
2821 Report.SymbolRelatedToPreviousError (base_class.Type);
2822 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2823 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2827 if (PartialContainer.IsStaticClass) {
2828 if (base_class.Type != TypeManager.object_type) {
2829 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2830 GetSignatureForError (), base_class.GetSignatureForError ());
2834 if (ifaces != null) {
2835 foreach (TypeExpr t in ifaces)
2836 Report.SymbolRelatedToPreviousError (t.Type);
2837 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2844 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2845 /// Valid only for attribute classes.
2846 public bool IsExcluded ()
2848 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2849 return (caching_flags & Flags.Excluded) != 0;
2851 caching_flags &= ~Flags.Excluded_Undetected;
2853 if (OptAttributes == null)
2856 if (TypeManager.conditional_attribute_type == null)
2859 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2864 foreach (Attribute a in attrs) {
2865 string condition = a.GetConditionalAttributeValue ();
2866 if (Location.CompilationUnit.IsConditionalDefined (condition))
2870 caching_flags |= Flags.Excluded;
2876 return (ModFlags & Modifiers.STATIC) != 0;
2881 // FIXME: How do we deal with the user specifying a different
2884 protected override TypeAttributes TypeAttr {
2886 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2888 ta |= StaticClassAttribute;
2894 public sealed class Struct : ClassOrStruct {
2896 // Modifiers allowed in a struct declaration
2898 const int AllowedModifiers =
2901 Modifiers.PROTECTED |
2902 Modifiers.INTERNAL |
2906 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2907 int mod, Attributes attrs)
2908 : base (ns, parent, name, attrs, Kind.Struct)
2912 if (parent.Parent == null)
2913 accmods = Modifiers.INTERNAL;
2915 accmods = Modifiers.PRIVATE;
2917 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2919 this.ModFlags |= Modifiers.SEALED;
2922 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2924 base.ApplyAttributeBuilder (a, cb);
2927 // When struct constains fixed fixed and struct layout has explicitly
2928 // set CharSet, its value has to be propagated to compiler generated
2929 // fixed field types
2931 if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
2932 for (int i = 0; i < Fields.Count; ++i) {
2933 FixedField ff = Fields [i] as FixedField;
2935 ff.SetCharSet (TypeBuilder.Attributes);
2940 public override AttributeTargets AttributeTargets {
2942 return AttributeTargets.Struct;
2946 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2948 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2950 // If we are compiling our runtime,
2951 // and we are defining ValueType, then our
2952 // base is `System.Object'.
2954 if (base_class == null) {
2955 if (!RootContext.StdLib && Name == "System.ValueType")
2956 base_class = TypeManager.system_object_expr;
2958 base_class = TypeManager.system_valuetype_expr;
2965 // FIXME: Allow the user to specify a different set of attributes
2966 // in some cases (Sealed for example is mandatory for a class,
2967 // but what SequentialLayout can be changed
2969 protected override TypeAttributes TypeAttr {
2971 const TypeAttributes DefaultTypeAttributes =
2972 TypeAttributes.SequentialLayout |
2973 TypeAttributes.Sealed |
2974 TypeAttributes.BeforeFieldInit;
2976 return base.TypeAttr | DefaultTypeAttributes;
2980 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2982 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2983 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2984 field.GetSignatureForError ());
2987 base.RegisterFieldForInitialization (field, expression);
2995 public sealed class Interface : TypeContainer, IMemberContainer {
2998 /// Modifiers allowed in a class declaration
3000 public const int AllowedModifiers =
3003 Modifiers.PROTECTED |
3004 Modifiers.INTERNAL |
3008 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3010 : base (ns, parent, name, attrs, Kind.Interface)
3014 if (parent.Parent == null)
3015 accmods = Modifiers.INTERNAL;
3017 accmods = Modifiers.PRIVATE;
3019 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3022 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3024 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3025 !attributes.Contains (TypeManager.guid_attr_type)) {
3026 a.Error_MissingGuidAttribute ();
3029 base.ApplyAttributeBuilder (a, cb);
3033 public override AttributeTargets AttributeTargets {
3035 return AttributeTargets.Interface;
3039 protected override TypeAttributes TypeAttr {
3041 const TypeAttributes DefaultTypeAttributes =
3042 TypeAttributes.AutoLayout |
3043 TypeAttributes.Abstract |
3044 TypeAttributes.Interface;
3046 return base.TypeAttr | DefaultTypeAttributes;
3050 protected override bool VerifyClsCompliance ()
3052 if (!base.VerifyClsCompliance ())
3055 if (ifaces != null) {
3056 foreach (Type t in ifaces) {
3057 if (AttributeTester.IsClsCompliant (t))
3060 Report.SymbolRelatedToPreviousError (t);
3061 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3062 GetSignatureForError (), TypeManager.CSharpName (t));
3070 // It is used as a base class for all property based members
3071 // This includes properties, indexers, and events
3072 public abstract class PropertyBasedMember : InterfaceMemberBase
3074 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3075 FullNamedExpression type, int mod, int allowed_mod,
3076 MemberName name, Attributes attrs)
3077 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3081 protected override bool VerifyClsCompliance ()
3083 if (!base.VerifyClsCompliance ())
3086 if (!AttributeTester.IsClsCompliant (MemberType)) {
3087 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3088 GetSignatureForError ());
3096 public abstract class MethodCore : InterfaceMemberBase
3098 public readonly Parameters Parameters;
3099 protected ToplevelBlock block;
3101 public MethodCore (DeclSpace parent, GenericMethod generic,
3102 FullNamedExpression type, int mod, int allowed_mod,
3103 MemberName name, Attributes attrs, Parameters parameters)
3104 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3106 Parameters = parameters;
3110 // Returns the System.Type array for the parameters of this method
3112 public Type [] ParameterTypes {
3114 return Parameters.Types;
3118 public Parameters ParameterInfo
3125 public ToplevelBlock Block {
3135 protected override bool CheckBase ()
3137 // Check whether arguments were correct.
3138 if (!DefineParameters (Parameters))
3141 return base.CheckBase ();
3145 // Returns a string that represents the signature for this
3146 // member which should be used in XML documentation.
3148 public override string GetDocCommentName (DeclSpace ds)
3150 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3154 // Raised (and passed an XmlElement that contains the comment)
3155 // when GenerateDocComment is writing documentation expectedly.
3157 // FIXME: with a few effort, it could be done with XmlReader,
3158 // that means removal of DOM use.
3160 internal override void OnGenerateDocComment (XmlElement el)
3162 DocUtil.OnMethodGenerateDocComment (this, el);
3166 // Represents header string for documentation comment.
3168 public override string DocCommentHeader
3170 get { return "M:"; }
3173 public override bool EnableOverloadChecks (MemberCore overload)
3175 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3176 caching_flags |= Flags.MethodOverloadsExist;
3180 return base.EnableOverloadChecks (overload);
3183 protected override bool VerifyClsCompliance ()
3185 if (!base.VerifyClsCompliance ())
3188 if (Parameters.HasArglist) {
3189 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3192 if (!AttributeTester.IsClsCompliant (MemberType)) {
3193 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3194 GetSignatureForError ());
3197 Parameters.VerifyClsCompliance ();
3203 public abstract class InterfaceMemberBase : MemberBase {
3205 // Whether this is an interface member.
3207 public bool IsInterface;
3210 // If true, this is an explicit interface implementation
3212 public bool IsExplicitImpl;
3214 protected bool is_external_implementation;
3217 // The interface type we are explicitly implementing
3219 public Type InterfaceType;
3222 // The method we're overriding if this is an override method.
3224 protected MethodInfo base_method;
3226 readonly int explicit_mod_flags;
3227 public MethodAttributes flags;
3229 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3230 FullNamedExpression type, int mod, int allowed_mod,
3231 MemberName name, Attributes attrs)
3232 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3235 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3236 IsExplicitImpl = (MemberName.Left != null);
3237 explicit_mod_flags = mod;
3240 protected override bool CheckBase ()
3242 if (!base.CheckBase ())
3245 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3246 CheckForDuplications ();
3251 // Is null for System.Object while compiling corlib and base interfaces
3252 if (Parent.PartialContainer.BaseCache == null) {
3253 if ((ModFlags & Modifiers.NEW) != 0) {
3254 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3259 Type base_ret_type = null;
3260 base_method = FindOutBaseMethod (ref base_ret_type);
3262 // method is override
3263 if (base_method != null) {
3264 if (!CheckMethodAgainstBase (base_ret_type))
3267 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3268 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3270 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3271 Report.SymbolRelatedToPreviousError (base_method);
3272 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3273 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3276 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3277 Report.SymbolRelatedToPreviousError (base_method);
3278 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3279 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3286 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3287 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3288 if (conflict_symbol != null) {
3289 Report.SymbolRelatedToPreviousError (conflict_symbol);
3291 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3292 else if (this is PropertyBase)
3293 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3295 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3297 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3298 GetSignatureForError (), SimpleName.GetMemberType (this));
3303 if (conflict_symbol == null) {
3304 if ((ModFlags & Modifiers.NEW) != 0) {
3305 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3310 if ((ModFlags & Modifiers.NEW) == 0) {
3311 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3314 Report.SymbolRelatedToPreviousError (conflict_symbol);
3315 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3316 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3322 protected virtual bool CheckForDuplications ()
3324 return Parent.MemberCache.CheckExistingMembersOverloads (
3325 this, GetFullName (MemberName), Parameters.EmptyReadOnlyParameters);
3329 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3330 // that have been defined.
3332 // `name' is the user visible name for reporting errors (this is used to
3333 // provide the right name regarding method names and properties)
3335 bool CheckMethodAgainstBase (Type base_method_type)
3339 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3340 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3341 Report.Error (506, Location,
3342 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3343 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3347 // Now we check that the overriden method is not final
3349 if (base_method.IsFinal) {
3350 Report.SymbolRelatedToPreviousError (base_method);
3351 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3352 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3356 // Check that the permissions are not being changed
3358 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3359 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3361 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3362 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3366 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3367 Report.SymbolRelatedToPreviousError (base_method);
3368 if (this is PropertyBasedMember) {
3369 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3370 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3373 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3374 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3380 if ((ModFlags & Modifiers.NEW) == 0) {
3381 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3382 ModFlags |= Modifiers.NEW;
3383 Report.SymbolRelatedToPreviousError (base_method);
3384 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3385 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",
3386 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3388 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3389 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3393 if (base_method.IsAbstract && !IsInterface) {
3394 Report.SymbolRelatedToPreviousError (base_method);
3395 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3396 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3404 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3406 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3408 // when overriding protected internal, the method can be declared
3409 // protected internal only within the same assembly or assembly
3410 // which has InternalsVisibleTo
3412 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3413 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3414 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3416 // if it's not "protected internal", it must be "protected"
3420 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3422 // protected within the same assembly - an error
3425 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3426 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3428 // protected ok, but other attributes differ - report an error
3434 return (thisp == base_classp);
3438 protected bool DefineParameters (Parameters parameters)
3440 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3442 if (!parameters.Resolve (rc))
3446 for (int i = 0; i < parameters.Count; ++i) {
3447 Parameter p = parameters [i];
3448 if (p.CheckAccessibility (this))
3451 Type t = parameters.Types [i];
3452 Report.SymbolRelatedToPreviousError (t);
3453 if (this is Indexer)
3454 Report.Error (55, Location,
3455 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3456 TypeManager.CSharpName (t), GetSignatureForError ());
3457 else if (this is Operator)
3458 Report.Error (57, Location,
3459 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3460 TypeManager.CSharpName (t), GetSignatureForError ());
3462 Report.Error (51, Location,
3463 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3464 TypeManager.CSharpName (t), GetSignatureForError ());
3470 protected bool DoDefineBase ()
3473 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3474 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3476 flags = MethodAttributes.Public |
3477 MethodAttributes.Abstract |
3478 MethodAttributes.HideBySig |
3479 MethodAttributes.NewSlot |
3480 MethodAttributes.Virtual;
3482 if (!Parent.PartialContainer.MethodModifiersValid (this))
3485 flags = Modifiers.MethodAttr (ModFlags);
3488 if (IsExplicitImpl) {
3489 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3490 if (iface_texpr == null)
3493 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3494 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3495 GetSignatureForError ());
3498 InterfaceType = iface_texpr.Type;
3500 if (!InterfaceType.IsInterface) {
3501 Report.SymbolRelatedToPreviousError (InterfaceType);
3502 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3503 TypeManager.CSharpName (InterfaceType));
3505 Parent.PartialContainer.VerifyImplements (this);
3508 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3514 public override void Emit()
3516 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3517 // We are more strict than Microsoft and report CS0626 as error
3518 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3519 Report.Error (626, Location,
3520 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3521 GetSignatureForError ());
3527 public override bool EnableOverloadChecks (MemberCore overload)
3530 // Two members can differ in their explicit interface
3531 // type parameter only
3533 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3534 if (imb != null && imb.IsExplicitImpl) {
3535 if (IsExplicitImpl) {
3536 caching_flags |= Flags.MethodOverloadsExist;
3541 return IsExplicitImpl;
3544 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3546 Report.SymbolRelatedToPreviousError (base_method);
3547 string base_name = TypeManager.GetFullNameSignature (base_method);
3548 string this_name = GetSignatureForError ();
3549 if (suffix != null) {
3550 base_name += suffix;
3551 this_name += suffix;
3554 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3555 this_name, Modifiers.GetDescription (ma), base_name);
3558 protected static string Error722 {
3560 return "`{0}': static types cannot be used as return types";
3565 /// Gets base method and its return type
3567 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3570 // The "short" name of this property / indexer / event. This is the
3571 // name without the explicit interface.
3573 public string ShortName
3575 get { return MemberName.Name; }
3576 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3580 // Returns full metadata method name
3582 public string GetFullName (MemberName name)
3584 if (!IsExplicitImpl)
3588 // When dealing with explicit members a full interface type
3589 // name is added to member name to avoid possible name conflicts
3591 // We use CSharpName which gets us full name with benefit of
3592 // replacing predefined names which saves some space and name
3595 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3598 protected override bool VerifyClsCompliance ()
3600 if (!base.VerifyClsCompliance ()) {
3601 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3602 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3605 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3606 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3611 if (GenericMethod != null)
3612 GenericMethod.VerifyClsCompliance ();
3617 public override bool IsUsed
3619 get { return IsExplicitImpl || base.IsUsed; }
3624 public abstract class MethodOrOperator : MethodCore, IMethodData
3626 public MethodBuilder MethodBuilder;
3627 ReturnParameter return_attributes;
3628 ListDictionary declarative_security;
3629 protected MethodData MethodData;
3631 static string[] attribute_targets = new string [] { "method", "return" };
3633 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3634 int allowed_mod, MemberName name,
3635 Attributes attrs, Parameters parameters)
3636 : base (parent, generic, type, mod, allowed_mod, name,
3641 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3643 if (a.Target == AttributeTargets.ReturnValue) {
3644 if (return_attributes == null)
3645 return_attributes = new ReturnParameter (MethodBuilder, Location);
3647 return_attributes.ApplyAttributeBuilder (a, cb);
3651 if (a.IsInternalMethodImplAttribute) {
3652 is_external_implementation = true;
3655 if (a.Type == TypeManager.dllimport_type) {
3656 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3657 if ((ModFlags & extern_static) != extern_static) {
3658 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3660 is_external_implementation = true;
3663 if (a.IsValidSecurityAttribute ()) {
3664 if (declarative_security == null)
3665 declarative_security = new ListDictionary ();
3666 a.ExtractSecurityPermissionSet (declarative_security);
3670 if (MethodBuilder != null)
3671 MethodBuilder.SetCustomAttribute (cb);
3674 public override AttributeTargets AttributeTargets {
3676 return AttributeTargets.Method;
3680 protected override bool CheckForDuplications ()
3682 string name = GetFullName (MemberName);
3683 if (MemberName.IsGeneric)
3684 name = MemberName.MakeName (name, MemberName.TypeArguments);
3686 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3689 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3691 return new EmitContext (
3692 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3695 public override bool Define ()
3697 if (!DoDefineBase ())
3701 if (GenericMethod != null) {
3702 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3703 if (!GenericMethod.Define (MethodBuilder))
3711 if (!CheckAbstractAndExtern (block != null))
3714 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3715 for (int i = 0; i < Parameters.Count; ++i ) {
3716 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
3717 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3718 GetSignatureForError ());
3727 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3729 // Current method is turned into automatically generated
3730 // wrapper which creates an instance of iterator
3732 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3733 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3736 if (IsPartialDefinition) {
3737 caching_flags &= ~Flags.Excluded_Undetected;
3738 caching_flags |= Flags.Excluded;
3739 // Add to member cache only when a partial method implementation is not there
3740 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3741 MethodBase mb = new PartialMethodDefinitionInfo (this);
3742 Parent.MemberCache.AddMember (mb, this);
3743 TypeManager.AddMethod (mb, this);
3749 MethodData = new MethodData (
3750 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3752 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3755 MethodBuilder = MethodData.MethodBuilder;
3758 if (MethodBuilder.IsGenericMethod)
3759 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3762 Parent.MemberCache.AddMember (MethodBuilder, this);
3764 if (!TypeManager.IsGenericParameter (MemberType)) {
3765 if (MemberType.IsAbstract && MemberType.IsSealed) {
3766 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3774 public override void Emit ()
3777 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3778 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3779 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3780 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3782 if (OptAttributes != null)
3783 OptAttributes.Emit ();
3785 if (declarative_security != null) {
3786 foreach (DictionaryEntry de in declarative_security) {
3787 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3794 protected void Error_ConditionalAttributeIsNotValid ()
3796 Report.Error (577, Location,
3797 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3798 GetSignatureForError ());
3801 public bool IsPartialDefinition {
3803 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3807 public bool IsPartialImplementation {
3809 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3813 public override string[] ValidAttributeTargets {
3815 return attribute_targets;
3819 #region IMethodData Members
3821 public CallingConventions CallingConventions {
3823 CallingConventions cc = Parameters.CallingConvention;
3825 if ((ModFlags & Modifiers.STATIC) == 0)
3826 cc |= CallingConventions.HasThis;
3828 // FIXME: How is `ExplicitThis' used in C#?
3834 public Type ReturnType {
3840 public MemberName MethodName {
3846 protected override bool CheckBase ()
3848 if (!base.CheckBase ())
3851 // TODO: Destructor should derive from MethodCore
3852 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3853 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3854 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3862 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3864 public bool IsExcluded () {
3865 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3866 return (caching_flags & Flags.Excluded) != 0;
3868 caching_flags &= ~Flags.Excluded_Undetected;
3870 if (base_method == null) {
3871 if (OptAttributes == null)
3874 if (TypeManager.conditional_attribute_type == null)
3877 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3882 foreach (Attribute a in attrs) {
3883 string condition = a.GetConditionalAttributeValue ();
3884 if (condition == null)
3887 if (Location.CompilationUnit.IsConditionalDefined (condition))
3891 caching_flags |= Flags.Excluded;
3895 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3897 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3898 caching_flags |= Flags.Excluded;
3904 if (md.IsExcluded ()) {
3905 caching_flags |= Flags.Excluded;
3911 GenericMethod IMethodData.GenericMethod {
3913 return GenericMethod;
3917 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3924 public class SourceMethod : IMethodDef
3927 SourceMethodBuilder builder;
3929 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3931 this.method = method;
3933 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3936 public string Name {
3937 get { return method.Name; }
3942 if (method is MethodBuilder)
3943 return ((MethodBuilder) method).GetToken ().Token;
3944 else if (method is ConstructorBuilder)
3945 return ((ConstructorBuilder) method).GetToken ().Token;
3947 throw new NotSupportedException ();
3951 public void CloseMethod ()
3953 SymbolWriter.CloseMethod ();
3956 public void SetRealMethodName (string name)
3958 if (builder != null)
3959 builder.SetRealMethodName (name);
3962 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
3964 if (!SymbolWriter.HasSymbolWriter)
3969 Location start_loc = block.StartLocation;
3970 if (start_loc.IsNull)
3973 ICompileUnit compile_unit = start_loc.CompilationUnit;
3974 if (compile_unit == null)
3977 return new SourceMethod (parent, method, compile_unit);
3981 public class Method : MethodOrOperator {
3984 /// Modifiers allowed in a class declaration
3986 const int AllowedModifiers =
3989 Modifiers.PROTECTED |
3990 Modifiers.INTERNAL |
3995 Modifiers.OVERRIDE |
3996 Modifiers.ABSTRACT |
4000 const int AllowedInterfaceModifiers =
4001 Modifiers.NEW | Modifiers.UNSAFE;
4003 public Method (DeclSpace parent, GenericMethod generic,
4004 FullNamedExpression return_type, int mod,
4005 MemberName name, Parameters parameters, Attributes attrs)
4006 : base (parent, generic, return_type, mod,
4007 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4008 name, attrs, parameters)
4012 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4013 MemberName name, Parameters parameters, Attributes attrs)
4014 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4018 public override string GetSignatureForError()
4020 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4023 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4025 Report.Error (17, location,
4026 "Program `{0}' has more than one entry point defined: `{1}'",
4027 CodeGen.FileName, TypeManager.CSharpSignature(b));
4030 bool IsEntryPoint ()
4032 if (ReturnType != TypeManager.void_type &&
4033 ReturnType != TypeManager.int32_type)
4036 if (Parameters.Count == 0)
4039 if (Parameters.Count > 1)
4042 Type t = Parameters.Types [0];
4043 return t.IsArray && t.GetArrayRank () == 1 &&
4044 TypeManager.GetElementType (t) == TypeManager.string_type &&
4045 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4048 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4050 if (a.Type == TypeManager.conditional_attribute_type) {
4051 if (IsExplicitImpl) {
4052 Error_ConditionalAttributeIsNotValid ();
4056 if (ReturnType != TypeManager.void_type) {
4057 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4061 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4062 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4067 Report.Error (582, Location, "Conditional not valid on interface members");
4071 if (MethodData.implementing != null) {
4072 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4073 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4074 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4078 for (int i = 0; i < Parameters.Count; ++i) {
4079 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4080 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4086 if (a.Type == TypeManager.extension_attribute_type) {
4087 a.Error_MisusedExtensionAttribute ();
4091 base.ApplyAttributeBuilder (a, cb);
4094 protected override bool CheckForDuplications ()
4096 if (!base.CheckForDuplications ())
4099 ArrayList ar = Parent.PartialContainer.Properties;
4101 for (int i = 0; i < ar.Count; ++i) {
4102 PropertyBase pb = (PropertyBase) ar [i];
4103 if (pb.AreAccessorsDuplicateImplementation (this))
4108 ar = Parent.PartialContainer.Indexers;
4110 for (int i = 0; i < ar.Count; ++i) {
4111 PropertyBase pb = (PropertyBase) ar [i];
4112 if (pb.AreAccessorsDuplicateImplementation (this))
4123 public override bool Define ()
4125 if (!base.Define ())
4128 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4129 Error1599 (Location, ReturnType);
4133 if (ReturnType == TypeManager.void_type && Parameters.Count == 0 &&
4134 Name == "Finalize" && !(this is Destructor)) {
4135 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4138 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4139 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4140 Parent.PartialContainer.Mark_HasEquals ();
4141 else if (Parameters.IsEmpty && Name == "GetHashCode")
4142 Parent.PartialContainer.Mark_HasGetHashCode ();
4145 if ((ModFlags & Modifiers.STATIC) == 0)
4148 if (Parameters.HasExtensionMethodType) {
4149 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4150 if (!Parent.IsTopLevel)
4151 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4152 GetSignatureForError ());
4154 if (TypeManager.extension_attribute_type == null) {
4155 Report.Error (1110, Location,
4156 "`{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",
4157 GetSignatureForError ());
4158 } else if (TypeManager.extension_attribute_attr == null) {
4159 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4160 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4163 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4166 ModFlags |= Modifiers.METHOD_EXTENSION;
4167 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4168 CodeGen.Assembly.HasExtensionMethods = true;
4170 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4171 GetSignatureForError ());
4176 // This is used to track the Entry Point,
4178 if (RootContext.NeedsEntryPoint &&
4180 (RootContext.MainClass == null ||
4181 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4182 if (IsEntryPoint ()) {
4184 if (RootContext.EntryPoint == null) {
4185 if (Parent.IsGeneric || MemberName.IsGeneric) {
4186 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4187 GetSignatureForError ());
4189 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4190 md.SetMemberIsUsed ();
4192 RootContext.EntryPoint = MethodBuilder;
4193 RootContext.EntryPointLocation = Location;
4196 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4197 Error_DuplicateEntryPoint (MethodBuilder, Location);
4200 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4201 GetSignatureForError ());
4211 public override void Emit ()
4214 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4215 if (IsPartialDefinition) {
4217 // Do attribute checks only when partial implementation does not exist
4219 if (MethodBuilder == null)
4225 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4226 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4227 GetSignatureForError ());
4229 MethodData.Emit (Parent);
4233 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4234 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4240 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4241 Location, MethodBuilder);
4246 public override bool EnableOverloadChecks (MemberCore overload)
4248 // TODO: It can be deleted when members will be defined in correct order
4249 if (overload is Operator)
4250 return overload.EnableOverloadChecks (this);
4252 if (overload is Indexer)
4255 return base.EnableOverloadChecks (overload);
4258 public static void Error1599 (Location loc, Type t)
4260 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4263 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4265 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4266 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4271 if (mi.IsSpecialName)
4274 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4278 public void SetPartialDefinition (Method methodDefinition)
4280 caching_flags |= Flags.PartialDefinitionExists;
4281 methodDefinition.MethodBuilder = MethodBuilder;
4282 if (methodDefinition.attributes == null)
4285 if (attributes == null) {
4286 attributes = methodDefinition.attributes;
4288 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4292 protected override bool VerifyClsCompliance ()
4294 if (!base.VerifyClsCompliance ())
4297 if (ParameterInfo.Count > 0) {
4298 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4300 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4307 public abstract class ConstructorInitializer : ExpressionStatement
4309 ArrayList argument_list;
4310 MethodGroupExpr base_constructor_group;
4312 public ConstructorInitializer (ArrayList argument_list, Location loc)
4314 this.argument_list = argument_list;
4318 public ArrayList Arguments {
4320 return argument_list;
4324 public override Expression CreateExpressionTree (EmitContext ec)
4326 throw new NotSupportedException ("ET");
4329 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4331 if (argument_list != null){
4332 foreach (Argument a in argument_list){
4333 if (!a.Resolve (ec, loc))
4338 if (this is ConstructorBaseInitializer) {
4339 if (ec.ContainerType.BaseType == null)
4342 type = ec.ContainerType.BaseType;
4343 if (ec.ContainerType.IsValueType) {
4344 Report.Error (522, loc,
4345 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4350 // It is legal to have "this" initializers that take no arguments
4351 // in structs, they are just no-ops.
4353 // struct D { public D (int a) : this () {}
4355 if (ec.ContainerType.IsValueType && argument_list == null)
4358 type = ec.ContainerType;
4361 base_constructor_group = MemberLookupFinal (
4362 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4363 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4364 loc) as MethodGroupExpr;
4366 if (base_constructor_group == null)
4369 base_constructor_group = base_constructor_group.OverloadResolve (
4370 ec, ref argument_list, false, loc);
4372 if (base_constructor_group == null)
4375 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4377 if (base_ctor == caller_builder){
4378 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4384 public override Expression DoResolve (EmitContext ec)
4386 throw new NotSupportedException ();
4389 public override void Emit (EmitContext ec)
4391 // It can be null for static initializers
4392 if (base_constructor_group == null)
4397 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4399 base_constructor_group.EmitCall (ec, argument_list);
4402 public override void EmitStatement (EmitContext ec)
4408 public class ConstructorBaseInitializer : ConstructorInitializer {
4409 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4410 base (argument_list, l)
4415 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4416 public GeneratedBaseInitializer (Location loc):
4422 public class ConstructorThisInitializer : ConstructorInitializer {
4423 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4424 base (argument_list, l)
4429 public class Constructor : MethodCore, IMethodData {
4430 public ConstructorBuilder ConstructorBuilder;
4431 public ConstructorInitializer Initializer;
4432 ListDictionary declarative_security;
4433 bool has_compliant_args;
4436 // Modifiers allowed for a constructor.
4438 public const int AllowedModifiers =
4440 Modifiers.PROTECTED |
4441 Modifiers.INTERNAL |
4447 static readonly string[] attribute_targets = new string [] { "method" };
4450 // The spec claims that static is not permitted, but
4451 // my very own code has static constructors.
4453 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, Parameters args,
4454 ConstructorInitializer init, Location loc)
4455 : base (parent, null, null, mod, AllowedModifiers,
4456 new MemberName (name, loc), attrs, args)
4461 public bool HasCompliantArgs {
4462 get { return has_compliant_args; }
4465 public override AttributeTargets AttributeTargets {
4466 get { return AttributeTargets.Constructor; }
4470 // Returns true if this is a default constructor
4472 public bool IsDefault ()
4474 if ((ModFlags & Modifiers.STATIC) != 0)
4475 return Parameters.IsEmpty;
4477 return Parameters.IsEmpty &&
4478 (Initializer is ConstructorBaseInitializer) &&
4479 (Initializer.Arguments == null);
4482 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4484 if (a.IsValidSecurityAttribute ()) {
4485 if (declarative_security == null) {
4486 declarative_security = new ListDictionary ();
4488 a.ExtractSecurityPermissionSet (declarative_security);
4492 if (a.IsInternalMethodImplAttribute) {
4493 is_external_implementation = true;
4496 ConstructorBuilder.SetCustomAttribute (cb);
4499 protected override bool CheckBase ()
4501 if ((ModFlags & Modifiers.STATIC) != 0) {
4502 if (!Parameters.IsEmpty) {
4503 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4504 GetSignatureForError ());
4508 // the rest can be ignored
4512 // Check whether arguments were correct.
4513 if (!DefineParameters (Parameters))
4516 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4517 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4520 if (Parent.PartialContainer.Kind == Kind.Struct) {
4521 if (Parameters.Count == 0) {
4522 Report.Error (568, Location,
4523 "Structs cannot contain explicit parameterless constructors");
4528 CheckProtectedModifier ();
4534 // Creates the ConstructorBuilder
4536 public override bool Define ()
4538 if (ConstructorBuilder != null)
4541 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4542 MethodAttributes.SpecialName);
4544 if ((ModFlags & Modifiers.STATIC) != 0) {
4545 ca |= MethodAttributes.Static | MethodAttributes.Private;
4547 ca |= MethodAttributes.HideBySig;
4549 if ((ModFlags & Modifiers.PUBLIC) != 0)
4550 ca |= MethodAttributes.Public;
4551 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4552 if ((ModFlags & Modifiers.INTERNAL) != 0)
4553 ca |= MethodAttributes.FamORAssem;
4555 ca |= MethodAttributes.Family;
4556 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4557 ca |= MethodAttributes.Assembly;
4559 ca |= MethodAttributes.Private;
4562 if (!CheckAbstractAndExtern (block != null))
4565 // Check if arguments were correct.
4569 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4570 ca, CallingConventions,
4571 Parameters.GetEmitTypes ());
4573 if (Parent.PartialContainer.IsComImport) {
4574 if (!IsDefault ()) {
4575 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4576 Parent.GetSignatureForError ());
4579 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4582 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4583 TypeManager.AddMethod (ConstructorBuilder, this);
4585 // It's here only to report an error
4586 if (block != null && block.IsIterator) {
4587 member_type = TypeManager.void_type;
4588 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4597 public override void Emit ()
4599 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4600 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4602 if (OptAttributes != null)
4603 OptAttributes.Emit ();
4607 EmitContext ec = CreateEmitContext (null, null);
4610 // If we use a "this (...)" constructor initializer, then
4611 // do not emit field initializers, they are initialized in the other constructor
4613 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4614 !(Initializer is ConstructorThisInitializer);
4616 if (emit_field_initializers)
4617 Parent.PartialContainer.ResolveFieldInitializers (ec);
4619 if (block != null) {
4620 // If this is a non-static `struct' constructor and doesn't have any
4621 // initializer, it must initialize all of the struct's fields.
4622 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4623 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4624 block.AddThisVariable (Parent, Location);
4626 if (!block.ResolveMeta (ec, ParameterInfo))
4629 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4630 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4631 Initializer = new GeneratedBaseInitializer (Location);
4634 // Spec mandates that Initializers will not have `this' access
4636 if (Initializer != null) {
4638 Initializer.Resolve (ConstructorBuilder, ec);
4639 ec.IsStatic = false;
4640 block.AddScopeStatement (new StatementExpression (Initializer));
4645 Parameters.ApplyAttributes (ConstructorBuilder);
4647 SourceMethod source = null;
4649 ec.OmitDebuggingInfo = true;
4651 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4653 bool unreachable = false;
4654 if (block != null) {
4655 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4658 ec.EmitMeta (block);
4660 if (Report.Errors > 0)
4663 ec.EmitResolvedTopBlock (block, unreachable);
4667 source.CloseMethod ();
4669 if (declarative_security != null) {
4670 foreach (DictionaryEntry de in declarative_security) {
4671 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4678 // Is never override
4679 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4684 public override string GetSignatureForError()
4686 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4689 public override string[] ValidAttributeTargets {
4691 return attribute_targets;
4695 protected override bool VerifyClsCompliance ()
4697 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4701 if (ParameterInfo.Count > 0) {
4702 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4704 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4706 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4707 foreach (Type param in Parameters.Types) {
4708 if (param.IsArray) {
4714 has_compliant_args = true;
4718 #region IMethodData Members
4720 public System.Reflection.CallingConventions CallingConventions {
4722 CallingConventions cc = Parameters.CallingConvention;
4724 if (Parent.PartialContainer.Kind == Kind.Class)
4725 if ((ModFlags & Modifiers.STATIC) == 0)
4726 cc |= CallingConventions.HasThis;
4728 // FIXME: How is `ExplicitThis' used in C#?
4734 public MemberName MethodName {
4740 public Type ReturnType {
4746 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4748 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4749 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4750 ec.CurrentBlock = block;
4754 public bool IsExcluded()
4759 GenericMethod IMethodData.GenericMethod {
4765 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4772 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4774 public interface IMethodData
4776 CallingConventions CallingConventions { get; }
4777 Location Location { get; }
4778 MemberName MethodName { get; }
4779 Type ReturnType { get; }
4780 GenericMethod GenericMethod { get; }
4781 Parameters ParameterInfo { get; }
4783 Attributes OptAttributes { get; }
4784 ToplevelBlock Block { get; set; }
4786 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4787 ObsoleteAttribute GetObsoleteAttribute ();
4788 string GetSignatureForError ();
4790 bool IsClsComplianceRequired ();
4791 void SetMemberIsUsed ();
4792 void EmitExtraSymbolInfo (SourceMethod source);
4796 // Encapsulates most of the Method's state
4798 public class MethodData {
4800 static FieldInfo methodbuilder_attrs_field;
4802 public readonly IMethodData method;
4804 public readonly GenericMethod GenericMethod;
4807 // Are we implementing an interface ?
4809 public MethodInfo implementing;
4814 protected InterfaceMemberBase member;
4815 protected int modifiers;
4816 protected MethodAttributes flags;
4817 protected Type declaring_type;
4818 protected MethodInfo parent_method;
4820 MethodBuilder builder = null;
4821 public MethodBuilder MethodBuilder {
4827 public Type DeclaringType {
4829 return declaring_type;
4833 public MethodData (InterfaceMemberBase member,
4834 int modifiers, MethodAttributes flags, IMethodData method)
4836 this.member = member;
4837 this.modifiers = modifiers;
4840 this.method = method;
4843 public MethodData (InterfaceMemberBase member,
4844 int modifiers, MethodAttributes flags,
4845 IMethodData method, MethodBuilder builder,
4846 GenericMethod generic, MethodInfo parent_method)
4847 : this (member, modifiers, flags, method)
4849 this.builder = builder;
4850 this.GenericMethod = generic;
4851 this.parent_method = parent_method;
4854 public bool Define (DeclSpace parent, string method_full_name)
4856 string name = method.MethodName.Basename;
4858 TypeContainer container = parent.PartialContainer;
4860 PendingImplementation pending = container.PendingImplementations;
4861 if (pending != null){
4862 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4864 if (member.InterfaceType != null){
4865 if (implementing == null){
4866 if (member is PropertyBase) {
4867 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4868 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4869 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4872 Report.Error (539, method.Location,
4873 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4874 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4878 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4879 Report.SymbolRelatedToPreviousError (implementing);
4880 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4881 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4885 if (implementing != null) {
4886 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4887 if (prop_method == null) {
4888 if (TypeManager.IsSpecialMethod (implementing)) {
4889 Report.SymbolRelatedToPreviousError (implementing);
4890 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4891 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4892 implementing.Name.StartsWith ("get_") ? "get" : "set");
4894 } else if (implementing.DeclaringType.IsInterface) {
4895 if (!implementing.IsSpecialName) {
4896 Report.SymbolRelatedToPreviousError (implementing);
4897 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4898 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4901 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4902 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4903 Report.SymbolRelatedToPreviousError (implementing);
4904 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4905 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4914 // For implicit implementations, make sure we are public, for
4915 // explicit implementations, make sure we are private.
4917 if (implementing != null){
4919 // Setting null inside this block will trigger a more
4920 // verbose error reporting for missing interface implementations
4922 // The "candidate" function has been flagged already
4923 // but it wont get cleared
4925 if (member.IsExplicitImpl){
4926 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4927 Report.SymbolRelatedToPreviousError (implementing);
4928 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4929 method.GetSignatureForError ());
4933 if (implementing.DeclaringType.IsInterface) {
4935 // If this is an interface method implementation,
4936 // check for public accessibility
4938 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4940 implementing = null;
4942 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4943 // We may never be private.
4944 implementing = null;
4946 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4948 // We may be protected if we're overriding something.
4950 implementing = null;
4955 // Static is not allowed
4957 if ((modifiers & Modifiers.STATIC) != 0){
4958 implementing = null;
4963 // If implementing is still valid, set flags
4965 if (implementing != null){
4967 // When implementing interface methods, set NewSlot
4968 // unless, we are overwriting a method.
4970 if (implementing.DeclaringType.IsInterface){
4971 if ((modifiers & Modifiers.OVERRIDE) == 0)
4972 flags |= MethodAttributes.NewSlot;
4975 MethodAttributes.Virtual |
4976 MethodAttributes.HideBySig;
4978 // Set Final unless we're virtual, abstract or already overriding a method.
4979 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4980 flags |= MethodAttributes.Final;
4983 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
4985 if (builder == null)
4988 if (container.CurrentType != null)
4989 declaring_type = container.CurrentType;
4991 declaring_type = container.TypeBuilder;
4993 if (implementing != null && member.IsExplicitImpl) {
4994 container.TypeBuilder.DefineMethodOverride (builder, implementing);
4997 TypeManager.AddMethod (builder, method);
4999 if (GenericMethod != null) {
5000 bool is_override = member.IsExplicitImpl |
5001 ((modifiers & Modifiers.OVERRIDE) != 0);
5003 if (implementing != null)
5004 parent_method = implementing;
5006 EmitContext ec = method.CreateEmitContext (container, null);
5007 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5016 /// Create the MethodBuilder for the method
5018 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5020 if (builder == null) {
5021 builder = container.TypeBuilder.DefineMethod (
5022 method_name, flags, method.CallingConventions,
5023 method.ReturnType, param.GetEmitTypes ());
5029 // Generic method has been already defined to resolve method parameters
5030 // correctly when they use type parameters
5032 builder.SetParameters (param.GetEmitTypes ());
5033 builder.SetReturnType (method.ReturnType);
5035 if (builder.Attributes != flags) {
5037 if (methodbuilder_attrs_field == null)
5038 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5039 methodbuilder_attrs_field.SetValue (builder, flags);
5041 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5045 throw new InternalErrorException ();
5052 public void Emit (DeclSpace parent)
5054 ToplevelBlock block = method.Block;
5058 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5060 ec = method.CreateEmitContext (parent, null);
5062 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5064 if (GenericMethod != null)
5065 GenericMethod.EmitAttributes ();
5068 // clear the pending implementation flag
5070 if (implementing != null)
5071 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5072 member.InterfaceType, this, member.IsExplicitImpl);
5074 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5077 // Handle destructors specially
5079 // FIXME: This code generates buggy code
5081 if (member is Destructor)
5082 EmitDestructor (ec, block);
5084 ec.EmitTopBlock (method, block);
5086 if (source != null) {
5087 method.EmitExtraSymbolInfo (source);
5088 source.CloseMethod ();
5092 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5094 ILGenerator ig = ec.ig;
5096 Label finish = ig.DefineLabel ();
5098 block.SetDestructor ();
5100 ig.BeginExceptionBlock ();
5101 ec.ReturnLabel = finish;
5102 ec.HasReturnLabel = true;
5103 ec.EmitTopBlock (method, block);
5105 // ig.MarkLabel (finish);
5106 ig.BeginFinallyBlock ();
5108 if (ec.ContainerType.BaseType != null) {
5109 Expression member_lookup = Expression.MemberLookup (
5110 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5111 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5113 if (member_lookup != null){
5114 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5116 ig.Emit (OpCodes.Ldarg_0);
5117 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5121 ig.EndExceptionBlock ();
5122 //ig.MarkLabel (ec.ReturnLabel);
5123 ig.Emit (OpCodes.Ret);
5127 // TODO: Should derive from MethodCore
5128 public class Destructor : Method
5130 const int AllowedModifiers =
5134 static string[] attribute_targets = new string [] { "method" };
5136 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5137 string name, Parameters parameters, Attributes attrs,
5139 : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
5142 ModFlags &= ~Modifiers.PRIVATE;
5143 if (!RootContext.StdLib && parent.Name == "System.Object")
5144 ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
5146 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
5149 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5151 if (a.Type == TypeManager.conditional_attribute_type) {
5152 Error_ConditionalAttributeIsNotValid ();
5156 base.ApplyAttributeBuilder (a, cb);
5159 public override string GetSignatureForError ()
5161 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5164 public override string[] ValidAttributeTargets {
5166 return attribute_targets;
5171 abstract public class MemberBase : MemberCore {
5172 protected FullNamedExpression type_name;
5173 public readonly DeclSpace ds;
5174 public readonly GenericMethod GenericMethod;
5177 // The type of this property / indexer / event
5179 protected Type member_type;
5180 public Type MemberType {
5182 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5183 if (member_type == null && type_name != null) {
5184 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5185 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5186 if (type_name != null) {
5187 member_type = type_name.Type;
5195 // The constructor is only exposed to our children
5197 protected MemberBase (DeclSpace parent, GenericMethod generic,
5198 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5199 MemberName name, Attributes attrs)
5200 : base (parent, name, attrs)
5202 this.ds = generic != null ? generic : (DeclSpace) parent;
5203 this.type_name = type;
5204 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5205 GenericMethod = generic;
5206 if (GenericMethod != null)
5207 GenericMethod.ModFlags = ModFlags;
5210 protected virtual bool CheckBase ()
5212 CheckProtectedModifier ();
5217 protected virtual bool DoDefine ()
5219 if (MemberType == null)
5222 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5223 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5224 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5225 GetSignatureForError (), Parent.GetSignatureForError ());
5229 // verify accessibility
5230 if (!IsAccessibleAs (MemberType)) {
5231 Report.SymbolRelatedToPreviousError (MemberType);
5232 if (this is Property)
5233 Report.Error (53, Location,
5234 "Inconsistent accessibility: property type `" +
5235 TypeManager.CSharpName (MemberType) + "' is less " +
5236 "accessible than property `" + GetSignatureForError () + "'");
5237 else if (this is Indexer)
5238 Report.Error (54, Location,
5239 "Inconsistent accessibility: indexer return type `" +
5240 TypeManager.CSharpName (MemberType) + "' is less " +
5241 "accessible than indexer `" + GetSignatureForError () + "'");
5242 else if (this is MethodCore) {
5243 if (this is Operator)
5244 Report.Error (56, Location,
5245 "Inconsistent accessibility: return type `" +
5246 TypeManager.CSharpName (MemberType) + "' is less " +
5247 "accessible than operator `" + GetSignatureForError () + "'");
5249 Report.Error (50, Location,
5250 "Inconsistent accessibility: return type `" +
5251 TypeManager.CSharpName (MemberType) + "' is less " +
5252 "accessible than method `" + GetSignatureForError () + "'");
5254 Report.Error (52, Location,
5255 "Inconsistent accessibility: field type `" +
5256 TypeManager.CSharpName (MemberType) + "' is less " +
5257 "accessible than field `" + GetSignatureForError () + "'");
5265 protected bool IsTypePermitted ()
5267 if (TypeManager.IsSpecialType (MemberType)) {
5268 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5276 // Abstract class for all fields
5278 abstract public class FieldBase : MemberBase {
5279 public FieldBuilder FieldBuilder;
5280 public Status status;
5281 protected Expression initializer;
5284 public enum Status : byte {
5285 HAS_OFFSET = 4 // Used by FieldMember.
5288 static readonly string[] attribute_targets = new string [] { "field" };
5290 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5291 int allowed_mod, MemberName name, Attributes attrs)
5292 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5295 if ((mod & Modifiers.ABSTRACT) != 0)
5296 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5299 public override AttributeTargets AttributeTargets {
5301 return AttributeTargets.Field;
5305 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5307 if (a.Type == TypeManager.field_offset_attribute_type) {
5308 status |= Status.HAS_OFFSET;
5310 if (!Parent.PartialContainer.HasExplicitLayout) {
5311 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5315 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5316 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5322 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5323 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5329 if (a.Type == TypeManager.marshal_as_attr_type) {
5330 UnmanagedMarshal marshal = a.GetMarshal (this);
5331 if (marshal != null) {
5332 FieldBuilder.SetMarshal (marshal);
5337 if ((a.HasSecurityAttribute)) {
5338 a.Error_InvalidSecurityParent ();
5342 FieldBuilder.SetCustomAttribute (cb);
5345 protected override bool CheckBase ()
5347 if (!base.CheckBase ())
5350 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5351 if (conflict_symbol == null) {
5352 if ((ModFlags & Modifiers.NEW) != 0) {
5353 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5358 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5359 Report.SymbolRelatedToPreviousError (conflict_symbol);
5360 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5361 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5367 public override bool Define()
5369 if (MemberType == null || member_type == null)
5372 if (TypeManager.IsGenericParameter (MemberType))
5375 if (MemberType.IsSealed && MemberType.IsAbstract) {
5376 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5386 if (!IsTypePermitted ())
5393 // Represents header string for documentation comment.
5395 public override string DocCommentHeader {
5396 get { return "F:"; }
5399 public override void Emit ()
5402 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5403 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5406 if (OptAttributes != null) {
5407 OptAttributes.Emit ();
5410 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5411 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5417 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5419 Report.SymbolRelatedToPreviousError (static_class);
5420 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5424 public Expression Initializer {
5426 if (value != null) {
5427 this.initializer = value;
5432 protected virtual bool IsFieldClsCompliant {
5434 if (FieldBuilder == null)
5437 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5441 public override string[] ValidAttributeTargets
5444 return attribute_targets;
5448 protected override bool VerifyClsCompliance ()
5450 if (!base.VerifyClsCompliance ())
5453 if (!IsFieldClsCompliant) {
5454 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5455 GetSignatureForError ());
5460 public void SetAssigned ()
5462 caching_flags |= Flags.IsAssigned;
5466 interface IFixedBuffer
5468 FieldInfo Element { get; }
5469 Type ElementType { get; }
5472 public class FixedFieldExternal: IFixedBuffer
5474 FieldInfo element_field;
5476 public FixedFieldExternal (FieldInfo fi)
5478 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5481 #region IFixedField Members
5483 public FieldInfo Element {
5485 return element_field;
5489 public Type ElementType {
5491 return element_field.FieldType;
5499 /// Fixed buffer implementation
5501 public class FixedField : FieldBase, IFixedBuffer
5503 public const string FixedElementName = "FixedElementField";
5504 static int GlobalCounter = 0;
5505 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5506 static FieldInfo[] fi;
5508 TypeBuilder fixed_buffer_type;
5509 FieldBuilder element;
5510 Expression size_expr;
5512 const int AllowedModifiers =
5515 Modifiers.PROTECTED |
5516 Modifiers.INTERNAL |
5519 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5520 Expression size_expr, Attributes attrs, Location loc):
5521 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5523 if (RootContext.Version < LanguageVersion.ISO_2)
5524 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5526 this.size_expr = size_expr;
5529 public override bool Define()
5531 if (!Parent.IsInUnsafeScope)
5532 Expression.UnsafeError (Location);
5534 if (!base.Define ())
5537 if (!TypeManager.IsPrimitiveType (MemberType)) {
5538 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",
5539 GetSignatureForError ());
5542 // Create nested fixed buffer container
5543 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5544 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5545 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5547 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5548 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5550 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5551 Parent.MemberCache.AddMember (FieldBuilder, this);
5552 TypeManager.RegisterFieldBase (FieldBuilder, this);
5557 public override void Emit()
5559 if (Parent.PartialContainer.Kind != Kind.Struct) {
5560 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5561 GetSignatureForError ());
5564 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5565 Constant c = size_expr.ResolveAsConstant (ec, this);
5569 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5570 if (buffer_size_const == null)
5573 int buffer_size = buffer_size_const.Value;
5575 if (buffer_size <= 0) {
5576 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5580 int type_size = Expression.GetTypeSize (MemberType);
5582 if (buffer_size > int.MaxValue / type_size) {
5583 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5584 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5588 buffer_size *= type_size;
5589 EmitFieldSize (buffer_size);
5593 // Emit compiler generated fixed buffer type attribute
5595 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5597 Type attr_type = TypeManager.CoreLookupType (
5598 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5600 if (attr_type != null) {
5601 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5603 cab = new CustomAttributeBuilder (ci, new object [0]);
5604 TypeManager.unsafe_value_type_attr = cab;
5610 fixed_buffer_type.SetCustomAttribute (cab);
5615 void EmitFieldSize (int buffer_size)
5617 if (TypeManager.struct_layout_attribute_type == null) {
5618 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5619 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5621 if (TypeManager.struct_layout_attribute_type == null)
5626 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5628 object [] fi_val = new object [] { buffer_size };
5630 if (TypeManager.struct_layout_attribute_ctor == null) {
5631 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5632 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5633 if (TypeManager.struct_layout_attribute_ctor == null)
5637 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5638 ctor_args, fi, fi_val);
5639 fixed_buffer_type.SetCustomAttribute (cab);
5642 // Don't emit FixedBufferAttribute attribute for private types
5644 if ((ModFlags & Modifiers.PRIVATE) != 0)
5647 if (TypeManager.fixed_buffer_attr_ctor == null) {
5648 if (TypeManager.fixed_buffer_attr_type == null) {
5649 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5650 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5652 if (TypeManager.fixed_buffer_attr_type == null)
5656 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5657 Location, TypeManager.type_type, TypeManager.int32_type);
5659 if (TypeManager.fixed_buffer_attr_ctor == null)
5663 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5664 FieldBuilder.SetCustomAttribute (cab);
5667 protected override bool IsFieldClsCompliant {
5673 public void SetCharSet (TypeAttributes ta)
5675 TypeAttributes cta = fixed_buffer_type.Attributes;
5676 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5677 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5678 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5679 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5680 else if (cta == 0 && ta != 0)
5681 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5684 void SetTypeBuilderCharSet (TypeAttributes ta)
5686 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5688 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5690 mi.Invoke (fixed_buffer_type, new object [] { ta });
5694 #region IFixedField Members
5696 public FieldInfo Element {
5702 public Type ElementType {
5712 // The Field class is used to represents class/struct fields during parsing.
5714 public class Field : FieldBase {
5716 // Modifiers allowed in a class declaration
5718 const int AllowedModifiers =
5721 Modifiers.PROTECTED |
5722 Modifiers.INTERNAL |
5725 Modifiers.VOLATILE |
5729 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5731 : base (parent, type, mod, AllowedModifiers, name, attrs)
5735 bool CanBeVolatile ()
5737 if (TypeManager.IsReferenceType (MemberType))
5740 if (MemberType.IsEnum)
5743 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5744 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5745 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5746 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5747 MemberType == TypeManager.float_type)
5753 bool CheckStructLayout (Type type, bool isStatic)
5755 if (TypeManager.IsBuiltinType (type))
5759 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5763 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5764 if (!TypeManager.IsGenericType (type))
5767 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5768 if (!CheckStructLayout (t, false))
5774 Report.Error (523, Location,
5775 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5776 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5780 public override bool Define ()
5782 if (!base.Define ())
5785 if ((ModFlags & Modifiers.VOLATILE) != 0){
5786 if (!CanBeVolatile ()) {
5787 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5788 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5791 if ((ModFlags & Modifiers.READONLY) != 0){
5792 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5793 GetSignatureForError ());
5799 Type[] required_modifier = null;
5800 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5801 if (TypeManager.isvolatile_type == null)
5802 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5803 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5805 if (TypeManager.isvolatile_type != null)
5806 required_modifier = new Type [] { TypeManager.isvolatile_type };
5809 FieldBuilder = Parent.TypeBuilder.DefineField (
5810 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5812 FieldBuilder = Parent.TypeBuilder.DefineField (
5813 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5815 Parent.MemberCache.AddMember (FieldBuilder, this);
5816 TypeManager.RegisterFieldBase (FieldBuilder, this);
5818 catch (ArgumentException) {
5819 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5823 if (initializer != null) {
5824 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5825 new FieldInitializer (FieldBuilder, initializer, this));
5827 if (Parent.PartialContainer.Kind == Kind.Struct)
5828 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5834 public override string GetSignatureForError ()
5836 string s = base.GetSignatureForError ();
5837 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5840 // Undecorate name mangling
5841 int l = s.LastIndexOf ('>');
5842 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5845 protected override bool VerifyClsCompliance ()
5847 if (!base.VerifyClsCompliance ())
5850 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5851 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5859 // `set' and `get' accessors are represented with an Accessor.
5861 public class Accessor {
5863 // Null if the accessor is empty, or a Block if not
5865 public const int AllowedModifiers =
5867 Modifiers.PROTECTED |
5868 Modifiers.INTERNAL |
5871 public ToplevelBlock Block;
5872 public Attributes Attributes;
5873 public Location Location;
5874 public int ModFlags;
5875 public Parameters Parameters;
5877 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5883 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5887 // Ooouh Martin, templates are missing here.
5888 // When it will be possible move here a lot of child code and template method type.
5889 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5890 protected MethodData method_data;
5891 protected ToplevelBlock block;
5892 protected ListDictionary declarative_security;
5894 // The accessor are created event if they are not wanted.
5895 // But we need them because their names are reserved.
5896 // Field says whether accessor will be emited or not
5897 public readonly bool IsDummy;
5899 protected readonly string prefix;
5901 ReturnParameter return_attributes;
5903 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5904 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5906 this.prefix = prefix;
5910 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5912 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5913 accessor.Attributes)
5915 this.prefix = prefix;
5916 this.block = accessor.Block;
5919 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5921 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5924 public void UpdateName (InterfaceMemberBase member)
5926 SetMemberName (SetupName (prefix, member, Location));
5929 #region IMethodData Members
5931 public ToplevelBlock Block {
5941 public CallingConventions CallingConventions {
5943 return CallingConventions.Standard;
5947 public bool IsExcluded ()
5952 GenericMethod IMethodData.GenericMethod {
5958 public MemberName MethodName {
5964 public Type[] ParameterTypes {
5966 return ParameterInfo.Types;
5970 public abstract Parameters ParameterInfo { get ; }
5971 public abstract Type ReturnType { get; }
5972 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5976 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5978 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5979 a.Type == TypeManager.conditional_attribute_type) {
5980 Report.Error (1667, a.Location,
5981 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5982 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5986 if (a.IsValidSecurityAttribute ()) {
5987 if (declarative_security == null)
5988 declarative_security = new ListDictionary ();
5989 a.ExtractSecurityPermissionSet (declarative_security);
5993 if (a.Target == AttributeTargets.Method) {
5994 method_data.MethodBuilder.SetCustomAttribute (cb);
5998 if (a.Target == AttributeTargets.ReturnValue) {
5999 if (return_attributes == null)
6000 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6002 return_attributes.ApplyAttributeBuilder (a, cb);
6006 ApplyToExtraTarget (a, cb);
6009 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6011 throw new NotSupportedException ("You forgot to define special attribute target handling");
6014 // It is not supported for the accessors
6015 public sealed override bool Define()
6017 throw new NotSupportedException ();
6020 public void Emit (DeclSpace parent)
6022 EmitMethod (parent);
6025 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6026 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6027 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6028 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6030 if (OptAttributes != null)
6031 OptAttributes.Emit ();
6033 if (declarative_security != null) {
6034 foreach (DictionaryEntry de in declarative_security) {
6035 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6042 protected virtual void EmitMethod (DeclSpace parent)
6044 method_data.Emit (parent);
6047 public override bool EnableOverloadChecks (MemberCore overload)
6049 // This can only happen with indexers and it will
6050 // be catched as indexer difference
6051 if (overload is AbstractPropertyEventMethod)
6054 if (overload is MethodCore) {
6055 caching_flags |= Flags.MethodOverloadsExist;
6061 public override bool IsClsComplianceRequired()
6066 public bool IsDuplicateImplementation (MethodCore method)
6068 if (!MemberName.Equals (method.MemberName))
6071 Type[] param_types = method.ParameterTypes;
6073 if (param_types == null || param_types.Length != ParameterTypes.Length)
6076 for (int i = 0; i < param_types.Length; i++)
6077 if (param_types [i] != ParameterTypes [i])
6080 Report.SymbolRelatedToPreviousError (method);
6081 Report.Error (82, Location, "A member `{0}' is already reserved",
6082 method.GetSignatureForError ());
6086 public override bool IsUsed
6097 // Represents header string for documentation comment.
6099 public override string DocCommentHeader {
6100 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6103 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6108 // Properties and Indexers both generate PropertyBuilders, we use this to share
6109 // their common bits.
6111 abstract public class PropertyBase : PropertyBasedMember {
6113 public class GetMethod : PropertyMethod
6115 static string[] attribute_targets = new string [] { "method", "return" };
6117 public GetMethod (PropertyBase method):
6118 base (method, "get_")
6122 public GetMethod (PropertyBase method, Accessor accessor):
6123 base (method, accessor, "get_")
6127 public override MethodBuilder Define (DeclSpace parent)
6129 base.Define (parent);
6134 method_data = new MethodData (method, ModFlags, flags, this);
6136 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6139 return method_data.MethodBuilder;
6142 public override Type ReturnType {
6144 return method.MemberType;
6148 public override Parameters ParameterInfo {
6150 return Parameters.EmptyReadOnlyParameters;
6154 public override string[] ValidAttributeTargets {
6156 return attribute_targets;
6161 public class SetMethod : PropertyMethod {
6163 static string[] attribute_targets = new string [] { "method", "param", "return" };
6164 ImplicitParameter param_attr;
6165 protected Parameters parameters;
6167 public SetMethod (PropertyBase method) :
6168 base (method, "set_")
6170 parameters = new Parameters (
6171 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6174 public SetMethod (PropertyBase method, Accessor accessor):
6175 base (method, accessor, "set_")
6177 this.parameters = accessor.Parameters;
6180 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6182 if (a.Target == AttributeTargets.Parameter) {
6183 if (param_attr == null)
6184 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6186 param_attr.ApplyAttributeBuilder (a, cb);
6190 base.ApplyAttributeBuilder (a, cb);
6193 public override Parameters ParameterInfo {
6199 public override MethodBuilder Define (DeclSpace parent)
6201 parameters.Resolve (ResolveContext);
6202 base.Define (parent);
6207 method_data = new MethodData (method, ModFlags, flags, this);
6209 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6212 return method_data.MethodBuilder;
6215 public override Type ReturnType {
6217 return TypeManager.void_type;
6221 public override string[] ValidAttributeTargets {
6223 return attribute_targets;
6228 static string[] attribute_targets = new string [] { "property" };
6230 public abstract class PropertyMethod : AbstractPropertyEventMethod
6232 protected readonly PropertyBase method;
6233 protected MethodAttributes flags;
6235 public PropertyMethod (PropertyBase method, string prefix)
6236 : base (method, prefix)
6238 this.method = method;
6239 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6242 public PropertyMethod (PropertyBase method, Accessor accessor,
6244 : base (method, accessor, prefix)
6246 this.method = method;
6247 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6249 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6250 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6254 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6256 if (a.IsInternalMethodImplAttribute) {
6257 method.is_external_implementation = true;
6260 base.ApplyAttributeBuilder (a, cb);
6263 public override AttributeTargets AttributeTargets {
6265 return AttributeTargets.Method;
6269 public override bool IsClsComplianceRequired ()
6271 return method.IsClsComplianceRequired ();
6274 public virtual MethodBuilder Define (DeclSpace parent)
6276 CheckForDuplications ();
6279 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6280 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6281 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6283 Report.SymbolRelatedToPreviousError (mi);
6284 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6285 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6291 TypeContainer container = parent.PartialContainer;
6294 // Check for custom access modifier
6296 if ((ModFlags & Modifiers.Accessibility) == 0) {
6297 ModFlags |= method.ModFlags;
6298 flags = method.flags;
6300 if (container.Kind == Kind.Interface)
6301 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6302 GetSignatureForError ());
6304 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6305 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6308 CheckModifiers (ModFlags);
6309 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6310 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6311 flags = Modifiers.MethodAttr (ModFlags);
6312 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6315 CheckAbstractAndExtern (block != null);
6317 if (block != null && block.IsIterator)
6318 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6323 public bool HasCustomAccessModifier
6326 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6330 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6332 return new EmitContext (this,
6333 ds, method.ds, method.Location, ig, ReturnType,
6334 method.ModFlags, false);
6337 public override ObsoleteAttribute GetObsoleteAttribute ()
6339 return method.GetObsoleteAttribute ();
6342 public override string GetSignatureForError()
6344 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6347 void CheckModifiers (int modflags)
6349 modflags &= Modifiers.Accessibility;
6351 int mflags = method.ModFlags & Modifiers.Accessibility;
6353 if ((mflags & Modifiers.PUBLIC) != 0) {
6354 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6356 else if ((mflags & Modifiers.PROTECTED) != 0) {
6357 if ((mflags & Modifiers.INTERNAL) != 0)
6358 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6360 flags |= Modifiers.PRIVATE;
6362 else if ((mflags & Modifiers.INTERNAL) != 0)
6363 flags |= Modifiers.PRIVATE;
6365 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6366 Report.Error (273, Location,
6367 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6368 GetSignatureForError (), method.GetSignatureForError ());
6372 protected bool CheckForDuplications ()
6374 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6377 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6381 public PropertyMethod Get, Set;
6382 public PropertyBuilder PropertyBuilder;
6383 public MethodBuilder GetBuilder, SetBuilder;
6385 protected bool define_set_first = false;
6387 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6388 int allowed_mod, MemberName name,
6389 Attributes attrs, bool define_set_first)
6390 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6392 this.define_set_first = define_set_first;
6395 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6397 if (a.HasSecurityAttribute) {
6398 a.Error_InvalidSecurityParent ();
6402 PropertyBuilder.SetCustomAttribute (cb);
6405 public override AttributeTargets AttributeTargets {
6407 return AttributeTargets.Property;
6411 public override bool Define ()
6416 if (!IsTypePermitted ())
6422 protected override bool DoDefine ()
6424 if (!base.DoDefine ())
6428 // Accessors modifiers check
6430 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6431 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6432 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6433 GetSignatureForError ());
6437 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6438 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6439 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6440 Report.Error (276, Location,
6441 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6442 GetSignatureForError ());
6447 if (MemberType.IsGenericParameter)
6451 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6452 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6461 GetBuilder = Get.Define (Parent);
6462 return (Get.IsDummy) ? true : GetBuilder != null;
6465 bool DefineSet (bool define)
6470 SetBuilder = Set.Define (Parent);
6471 return (Set.IsDummy) ? true : SetBuilder != null;
6474 protected bool DefineAccessors ()
6476 return DefineSet (define_set_first) &&
6478 DefineSet (!define_set_first);
6481 protected abstract PropertyInfo ResolveBaseProperty ();
6483 // TODO: rename to Resolve......
6484 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6486 PropertyInfo base_property = ResolveBaseProperty ();
6487 if (base_property == null)
6490 base_ret_type = base_property.PropertyType;
6491 MethodInfo get_accessor = base_property.GetGetMethod (true);
6492 MethodInfo set_accessor = base_property.GetSetMethod (true);
6493 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6496 // Check base property accessors conflict
6498 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6499 if (get_accessor == null) {
6500 if (Get != null && !Get.IsDummy) {
6501 Report.SymbolRelatedToPreviousError (base_property);
6502 Report.Error (545, Location,
6503 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6504 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6507 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6509 if (!Get.IsDummy && !CheckAccessModifiers (
6510 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6511 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6514 if (set_accessor == null) {
6515 if (Set != null && !Set.IsDummy) {
6516 Report.SymbolRelatedToPreviousError (base_property);
6517 Report.Error (546, Location,
6518 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6519 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6522 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6524 if (!Set.IsDummy && !CheckAccessModifiers (
6525 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6526 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6530 // When one accessor does not exist and property hides base one
6531 // we need to propagate this upwards
6532 if (set_accessor == null)
6533 set_accessor = get_accessor;
6536 // Get the less restrictive access
6538 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6541 public override void Emit ()
6544 // The PropertyBuilder can be null for explicit implementations, in that
6545 // case, we do not actually emit the ".property", so there is nowhere to
6546 // put the attribute
6548 if (PropertyBuilder != null && OptAttributes != null)
6549 OptAttributes.Emit ();
6561 /// Tests whether accessors are not in collision with some method (CS0111)
6563 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6565 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6568 public override bool IsUsed
6574 return Get.IsUsed | Set.IsUsed;
6578 protected override void SetMemberName (MemberName new_name)
6580 base.SetMemberName (new_name);
6582 Get.UpdateName (this);
6583 Set.UpdateName (this);
6586 public override string[] ValidAttributeTargets {
6588 return attribute_targets;
6593 // Represents header string for documentation comment.
6595 public override string DocCommentHeader {
6596 get { return "P:"; }
6600 public class Property : PropertyBase {
6601 const int AllowedModifiers =
6604 Modifiers.PROTECTED |
6605 Modifiers.INTERNAL |
6609 Modifiers.OVERRIDE |
6610 Modifiers.ABSTRACT |
6615 const int AllowedInterfaceModifiers =
6618 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6621 Field field = new Field (
6623 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6624 new MemberName ("<" + Name + ">k__BackingField", Location), null);
6625 ((TypeContainer)Parent).PartialContainer.AddField (field);
6628 get_block.Block = new ToplevelBlock (block, null, Location);
6629 Return r = new Return (new SimpleName(field.Name, Location), Location);
6630 get_block.Block.AddStatement (r);
6631 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6634 set_block.Block = new ToplevelBlock (block, set_block.Parameters, Location);
6635 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6636 set_block.Block.AddStatement (new StatementExpression(a));
6637 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6640 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6641 MemberName name, Attributes attrs, Accessor get_block,
6642 Accessor set_block, bool define_set_first)
6643 : this (parent, type, mod, name, attrs, get_block, set_block,
6644 define_set_first, null)
6648 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6649 MemberName name, Attributes attrs, Accessor get_block,
6650 Accessor set_block, bool define_set_first, Block current_block)
6651 : base (parent, type, mod,
6652 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6653 name, attrs, define_set_first)
6655 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6656 get_block != null && get_block.Block == null &&
6657 set_block != null && set_block.Block == null) {
6658 if (RootContext.Version <= LanguageVersion.ISO_2)
6659 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6661 CreateAutomaticProperty (current_block, get_block, set_block);
6664 if (get_block == null)
6665 Get = new GetMethod (this);
6667 Get = new GetMethod (this, get_block);
6669 if (set_block == null)
6670 Set = new SetMethod (this);
6672 Set = new SetMethod (this, set_block);
6675 public override bool Define ()
6677 if (!DoDefineBase ())
6680 if (!base.Define ())
6683 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6685 if (!DefineAccessors ())
6691 // FIXME - PropertyAttributes.HasDefault ?
6693 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6694 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6697 PropertyBuilder.SetGetMethod (GetBuilder);
6698 Parent.MemberCache.AddMember (GetBuilder, Get);
6702 PropertyBuilder.SetSetMethod (SetBuilder);
6703 Parent.MemberCache.AddMember (SetBuilder, Set);
6706 TypeManager.RegisterProperty (PropertyBuilder, this);
6707 Parent.MemberCache.AddMember (PropertyBuilder, this);
6711 public override void Emit ()
6713 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6714 Report.Error (842, Location,
6715 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6716 GetSignatureForError ());
6722 protected override PropertyInfo ResolveBaseProperty ()
6724 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6725 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6730 /// Gigantic workaround for lameness in SRE follows :
6731 /// This class derives from EventInfo and attempts to basically
6732 /// wrap around the EventBuilder so that FindMembers can quickly
6733 /// return this in it search for members
6735 public class MyEventBuilder : EventInfo {
6738 // We use this to "point" to our Builder which is
6739 // not really a MemberInfo
6741 EventBuilder MyBuilder;
6744 // We "catch" and wrap these methods
6746 MethodInfo raise, remove, add;
6748 EventAttributes attributes;
6749 Type declaring_type, reflected_type, event_type;
6754 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6756 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6758 // And now store the values in our own fields.
6760 declaring_type = type_builder;
6762 reflected_type = type_builder;
6764 attributes = event_attr;
6767 this.event_type = event_type;
6771 // Methods that you have to override. Note that you only need
6772 // to "implement" the variants that take the argument (those are
6773 // the "abstract" methods, the others (GetAddMethod()) are
6776 public override MethodInfo GetAddMethod (bool nonPublic)
6781 public override MethodInfo GetRemoveMethod (bool nonPublic)
6786 public override MethodInfo GetRaiseMethod (bool nonPublic)
6792 // These methods make "MyEventInfo" look like a Builder
6794 public void SetRaiseMethod (MethodBuilder raiseMethod)
6796 raise = raiseMethod;
6797 MyBuilder.SetRaiseMethod (raiseMethod);
6800 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6802 remove = removeMethod;
6803 MyBuilder.SetRemoveOnMethod (removeMethod);
6806 public void SetAddOnMethod (MethodBuilder addMethod)
6809 MyBuilder.SetAddOnMethod (addMethod);
6812 public void SetCustomAttribute (CustomAttributeBuilder cb)
6814 MyBuilder.SetCustomAttribute (cb);
6817 public override object [] GetCustomAttributes (bool inherit)
6819 // FIXME : There's nothing which can be seemingly done here because
6820 // we have no way of getting at the custom attribute objects of the
6825 public override object [] GetCustomAttributes (Type t, bool inherit)
6827 // FIXME : Same here !
6831 public override bool IsDefined (Type t, bool b)
6836 public override EventAttributes Attributes {
6842 public override string Name {
6848 public override Type DeclaringType {
6850 return declaring_type;
6854 public override Type ReflectedType {
6856 return reflected_type;
6860 public Type EventType {
6866 public void SetUsed ()
6868 if (my_event != null) {
6869 // my_event.SetAssigned ();
6870 my_event.SetMemberIsUsed ();
6876 /// For case when event is declared like property (with add and remove accessors).
6878 public class EventProperty: Event {
6879 abstract class AEventPropertyAccessor : AEventAccessor
6881 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6882 base (method, accessor, prefix)
6886 public override MethodBuilder Define (DeclSpace ds)
6888 CheckAbstractAndExtern (block != null);
6889 return base.Define (ds);
6892 public override string GetSignatureForError ()
6894 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6898 sealed class AddDelegateMethod: AEventPropertyAccessor
6900 public AddDelegateMethod (Event method, Accessor accessor):
6901 base (method, accessor, "add_")
6905 protected override MethodInfo DelegateMethodInfo {
6907 return TypeManager.delegate_combine_delegate_delegate;
6912 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6914 public RemoveDelegateMethod (Event method, Accessor accessor):
6915 base (method, accessor, "remove_")
6919 protected override MethodInfo DelegateMethodInfo {
6921 return TypeManager.delegate_remove_delegate_delegate;
6927 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6929 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6931 Attributes attrs, Accessor add, Accessor remove)
6932 : base (parent, type, mod_flags, name, attrs)
6934 Add = new AddDelegateMethod (this, add);
6935 Remove = new RemoveDelegateMethod (this, remove);
6938 public override bool Define()
6940 if (!base.Define ())
6947 public override string[] ValidAttributeTargets {
6949 return attribute_targets;
6955 /// Event is declared like field.
6957 public class EventField : Event {
6958 abstract class EventFieldAccessor : AEventAccessor
6960 protected EventFieldAccessor (Event method, string prefix)
6961 : base (method, prefix)
6965 protected override void EmitMethod(DeclSpace parent)
6967 if (method_data.implementing != null)
6968 parent.PartialContainer.PendingImplementations.ImplementMethod (
6969 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
6971 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6974 MethodBuilder mb = method_data.MethodBuilder;
6975 ILGenerator ig = mb.GetILGenerator ();
6977 // TODO: because we cannot use generics yet
6978 FieldInfo field_info = ((EventField)method).FieldBuilder;
6980 if (parent is Class) {
6981 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
6984 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6985 ig.Emit (OpCodes.Ldsfld, field_info);
6986 ig.Emit (OpCodes.Ldarg_0);
6987 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6988 ig.Emit (OpCodes.Castclass, method.MemberType);
6989 ig.Emit (OpCodes.Stsfld, field_info);
6991 ig.Emit (OpCodes.Ldarg_0);
6992 ig.Emit (OpCodes.Ldarg_0);
6993 ig.Emit (OpCodes.Ldfld, field_info);
6994 ig.Emit (OpCodes.Ldarg_1);
6995 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6996 ig.Emit (OpCodes.Castclass, method.MemberType);
6997 ig.Emit (OpCodes.Stfld, field_info);
6999 ig.Emit (OpCodes.Ret);
7003 sealed class AddDelegateMethod: EventFieldAccessor
7005 public AddDelegateMethod (Event method):
7006 base (method, "add_")
7010 protected override MethodInfo DelegateMethodInfo {
7012 return TypeManager.delegate_combine_delegate_delegate;
7017 sealed class RemoveDelegateMethod: EventFieldAccessor
7019 public RemoveDelegateMethod (Event method):
7020 base (method, "remove_")
7024 protected override MethodInfo DelegateMethodInfo {
7026 return TypeManager.delegate_remove_delegate_delegate;
7032 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7033 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7035 public FieldBuilder FieldBuilder;
7036 public Expression Initializer;
7038 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7039 : base (parent, type, mod_flags, name, attrs)
7041 Add = new AddDelegateMethod (this);
7042 Remove = new RemoveDelegateMethod (this);
7045 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7047 if (a.Target == AttributeTargets.Field) {
7048 FieldBuilder.SetCustomAttribute (cb);
7052 if (a.Target == AttributeTargets.Method) {
7053 int errors = Report.Errors;
7054 Add.ApplyAttributeBuilder (a, cb);
7055 if (errors == Report.Errors)
7056 Remove.ApplyAttributeBuilder (a, cb);
7060 base.ApplyAttributeBuilder (a, cb);
7063 public override bool Define()
7065 if (!base.Define ())
7071 // FIXME: We are unable to detect whether generic event is used because
7072 // we are using FieldExpr instead of EventExpr for event access in that
7073 // case. When this issue will be fixed this hack can be removed.
7074 if (TypeManager.IsGenericType (MemberType))
7077 if (Add.IsInterfaceImplementation)
7080 FieldBuilder = Parent.TypeBuilder.DefineField (
7082 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7083 TypeManager.RegisterEventField (EventBuilder, this);
7085 if (Initializer != null) {
7086 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7087 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7088 GetSignatureForError ());
7092 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7093 new FieldInitializer (FieldBuilder, Initializer, this));
7099 public override string[] ValidAttributeTargets
7102 return IsInterface ? attribute_targets_interface : attribute_targets;
7107 public abstract class Event : PropertyBasedMember {
7108 public abstract class AEventAccessor : AbstractPropertyEventMethod
7110 protected readonly Event method;
7111 ImplicitParameter param_attr;
7113 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7115 protected AEventAccessor (Event method, string prefix)
7116 : base (method, prefix)
7118 this.method = method;
7119 this.ModFlags = method.ModFlags;
7122 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7123 : base (method, accessor, prefix)
7125 this.method = method;
7126 this.ModFlags = method.ModFlags;
7129 public bool IsInterfaceImplementation {
7130 get { return method_data.implementing != null; }
7133 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7135 if (a.IsInternalMethodImplAttribute) {
7136 method.is_external_implementation = true;
7139 base.ApplyAttributeBuilder (a, cb);
7142 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7144 if (a.Target == AttributeTargets.Parameter) {
7145 if (param_attr == null)
7146 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7148 param_attr.ApplyAttributeBuilder (a, cb);
7152 base.ApplyAttributeBuilder (a, cb);
7155 public override AttributeTargets AttributeTargets {
7157 return AttributeTargets.Method;
7161 public override bool IsClsComplianceRequired ()
7163 return method.IsClsComplianceRequired ();
7166 public virtual MethodBuilder Define (DeclSpace parent)
7168 method_data = new MethodData (method, method.ModFlags,
7169 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7171 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7174 MethodBuilder mb = method_data.MethodBuilder;
7175 ParameterInfo.ApplyAttributes (mb);
7179 protected abstract MethodInfo DelegateMethodInfo { get; }
7181 public override Type ReturnType {
7183 return TypeManager.void_type;
7187 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7189 return new EmitContext (
7190 this, method.Parent, Location, ig, ReturnType,
7191 method.ModFlags, false);
7194 public override ObsoleteAttribute GetObsoleteAttribute ()
7196 return method.GetObsoleteAttribute ();
7199 public override string[] ValidAttributeTargets {
7201 return attribute_targets;
7205 public override Parameters ParameterInfo {
7207 return method.parameters;
7213 const int AllowedModifiers =
7216 Modifiers.PROTECTED |
7217 Modifiers.INTERNAL |
7222 Modifiers.OVERRIDE |
7224 Modifiers.ABSTRACT |
7227 const int AllowedInterfaceModifiers =
7230 public AEventAccessor Add, Remove;
7231 public MyEventBuilder EventBuilder;
7232 public MethodBuilder AddBuilder, RemoveBuilder;
7234 Parameters parameters;
7236 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7237 : base (parent, null, type, mod_flags,
7238 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7243 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7245 if ((a.HasSecurityAttribute)) {
7246 a.Error_InvalidSecurityParent ();
7250 EventBuilder.SetCustomAttribute (cb);
7253 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7255 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7258 public override AttributeTargets AttributeTargets {
7260 return AttributeTargets.Event;
7264 public override bool Define ()
7266 if (!DoDefineBase ())
7272 if (!TypeManager.IsDelegateType (MemberType)) {
7273 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7277 parameters = Parameters.CreateFullyResolved (
7278 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7283 if (TypeManager.delegate_combine_delegate_delegate == null) {
7284 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7285 TypeManager.delegate_type, "Combine", Location,
7286 TypeManager.delegate_type, TypeManager.delegate_type);
7288 if (TypeManager.delegate_remove_delegate_delegate == null) {
7289 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7290 TypeManager.delegate_type, "Remove", Location,
7291 TypeManager.delegate_type, TypeManager.delegate_type);
7295 // Now define the accessors
7298 AddBuilder = Add.Define (Parent);
7299 if (AddBuilder == null)
7302 RemoveBuilder = Remove.Define (Parent);
7303 if (RemoveBuilder == null)
7306 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7307 EventBuilder.SetAddOnMethod (AddBuilder);
7308 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7310 Parent.MemberCache.AddMember (EventBuilder, this);
7311 Parent.MemberCache.AddMember (AddBuilder, Add);
7312 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7317 public override void Emit ()
7319 if (OptAttributes != null) {
7320 OptAttributes.Emit ();
7324 Remove.Emit (Parent);
7329 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7331 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7332 Parent.TypeBuilder, Name);
7337 AParametersCollection pd = TypeManager.GetParameterData (mi);
7338 base_ret_type = pd.Types [0];
7343 // Represents header string for documentation comment.
7345 public override string DocCommentHeader {
7346 get { return "E:"; }
7351 public class Indexer : PropertyBase
7353 public class GetIndexerMethod : GetMethod
7355 Parameters parameters;
7357 public GetIndexerMethod (Indexer method):
7360 this.parameters = method.parameters;
7363 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7364 base (method, accessor)
7366 parameters = accessor.Parameters;
7369 public override MethodBuilder Define (DeclSpace parent)
7371 parameters.Resolve (ResolveContext);
7372 return base.Define (parent);
7375 public override bool EnableOverloadChecks (MemberCore overload)
7377 if (base.EnableOverloadChecks (overload)) {
7378 overload.caching_flags |= Flags.MethodOverloadsExist;
7385 public override Parameters ParameterInfo {
7392 public class SetIndexerMethod: SetMethod
7394 public SetIndexerMethod (Indexer method):
7397 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7400 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7401 base (method, accessor)
7403 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7406 public override bool EnableOverloadChecks (MemberCore overload)
7408 if (base.EnableOverloadChecks (overload)) {
7409 overload.caching_flags |= Flags.MethodOverloadsExist;
7417 const int AllowedModifiers =
7420 Modifiers.PROTECTED |
7421 Modifiers.INTERNAL |
7425 Modifiers.OVERRIDE |
7430 const int AllowedInterfaceModifiers =
7433 public readonly Parameters parameters;
7435 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7436 Parameters parameters, Attributes attrs,
7437 Accessor get_block, Accessor set_block, bool define_set_first)
7438 : base (parent, type, mod,
7439 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7440 name, attrs, define_set_first)
7442 this.parameters = parameters;
7444 if (get_block == null)
7445 Get = new GetIndexerMethod (this);
7447 Get = new GetIndexerMethod (this, get_block);
7449 if (set_block == null)
7450 Set = new SetIndexerMethod (this);
7452 Set = new SetIndexerMethod (this, set_block);
7455 protected override bool CheckForDuplications ()
7457 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7460 public override bool Define ()
7462 if (!DoDefineBase ())
7465 if (!base.Define ())
7468 if (!DefineParameters (parameters))
7471 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7472 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7473 if (indexer_attr != null) {
7474 // Remove the attribute from the list because it is not emitted
7475 OptAttributes.Attrs.Remove (indexer_attr);
7477 string name = indexer_attr.GetIndexerAttributeValue ();
7483 if (IsExplicitImpl) {
7484 Report.Error (415, indexer_attr.Location,
7485 "The `IndexerName' attribute is valid only on an " +
7486 "indexer that is not an explicit interface member declaration");
7490 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7491 Report.Error (609, indexer_attr.Location,
7492 "Cannot set the `IndexerName' attribute on an indexer marked override");
7498 if (InterfaceType != null) {
7499 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7500 if (base_IndexerName != Name)
7501 ShortName = base_IndexerName;
7504 if (!Parent.PartialContainer.AddMember (this) ||
7505 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7508 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7510 if (!DefineAccessors ())
7517 // Now name the parameters
7519 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7520 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7523 PropertyBuilder.SetGetMethod (GetBuilder);
7524 Parent.MemberCache.AddMember (GetBuilder, Get);
7528 PropertyBuilder.SetSetMethod (SetBuilder);
7529 Parent.MemberCache.AddMember (SetBuilder, Set);
7532 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7533 Parent.MemberCache.AddMember (PropertyBuilder, this);
7537 public override bool EnableOverloadChecks (MemberCore overload)
7539 if (overload is Indexer) {
7540 caching_flags |= Flags.MethodOverloadsExist;
7544 return base.EnableOverloadChecks (overload);
7547 public override string GetDocCommentName (DeclSpace ds)
7549 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7552 public override string GetSignatureForError ()
7554 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7555 if (MemberName.Left != null) {
7557 sb.Append (MemberName.Left.GetSignatureForError ());
7560 sb.Append (".this");
7561 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7562 return sb.ToString ();
7565 protected override PropertyInfo ResolveBaseProperty ()
7567 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7568 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7571 protected override bool VerifyClsCompliance ()
7573 if (!base.VerifyClsCompliance ())
7576 parameters.VerifyClsCompliance ();
7581 public class Operator : MethodOrOperator {
7583 const int AllowedModifiers =
7589 public enum OpType : byte {
7599 // Unary and Binary operators
7622 // Implicit and Explicit
7626 // Just because of enum
7630 public readonly OpType OperatorType;
7632 static readonly string [] [] names;
7636 names = new string[(int)OpType.TOP][];
7637 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7638 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7639 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7640 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7641 names [(int) OpType.True] = new string [] { "true", "op_True" };
7642 names [(int) OpType.False] = new string [] { "false", "op_False" };
7643 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7644 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7645 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7646 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7647 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7648 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7649 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7650 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7651 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7652 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7653 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7654 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7655 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7656 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7657 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7658 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7659 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7660 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7661 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7662 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7665 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7666 int mod_flags, Parameters parameters,
7667 ToplevelBlock block, Attributes attrs, Location loc)
7668 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7669 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7671 OperatorType = type;
7675 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7677 if (a.Type == TypeManager.conditional_attribute_type) {
7678 Error_ConditionalAttributeIsNotValid ();
7682 base.ApplyAttributeBuilder (a, cb);
7685 public override bool Define ()
7687 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7688 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7689 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7693 if (!base.Define ())
7696 // imlicit and explicit operator of same types are not allowed
7697 if (OperatorType == OpType.Explicit)
7698 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7699 else if (OperatorType == OpType.Implicit)
7700 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7702 Type declaring_type = MethodData.DeclaringType;
7703 Type return_type = MemberType;
7704 Type first_arg_type = ParameterTypes [0];
7706 Type first_arg_type_unwrap = first_arg_type;
7707 if (TypeManager.IsNullableType (first_arg_type))
7708 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7710 Type return_type_unwrap = return_type;
7711 if (TypeManager.IsNullableType (return_type))
7712 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7715 // Rules for conversion operators
7717 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7718 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7719 Report.Error (555, Location,
7720 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7725 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7726 conv_type = first_arg_type;
7727 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7728 conv_type = return_type;
7730 Report.Error (556, Location,
7731 "User-defined conversion must convert to or from the enclosing type");
7736 // Because IsInterface and IsClass are not supported
7738 if (!TypeManager.IsGenericParameter (conv_type)) {
7739 if (conv_type.IsInterface) {
7740 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7741 GetSignatureForError ());
7745 if (conv_type.IsClass) {
7746 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7747 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7748 GetSignatureForError ());
7752 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7753 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7754 GetSignatureForError ());
7759 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7760 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7761 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");
7764 } else if (Parameters.Count == 1) {
7765 // Checks for Unary operators
7767 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7768 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7769 Report.Error (448, Location,
7770 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7773 if (first_arg_type != declaring_type) {
7775 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7780 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7781 Report.Error (562, Location,
7782 "The parameter type of a unary operator must be the containing type");
7786 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7787 if (return_type != TypeManager.bool_type){
7790 "The return type of operator True or False " +
7797 // Checks for Binary operators
7799 if (first_arg_type != declaring_type &&
7800 Parameters.Types [1] != declaring_type){
7803 "One of the parameters of a binary operator must " +
7804 "be the containing type");
7812 protected override bool DoDefine ()
7814 if (!base.DoDefine ())
7817 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7821 public override void Emit ()
7825 Parameters.ApplyAttributes (MethodBuilder);
7828 // abstract or extern methods have no bodies
7830 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7834 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7835 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7837 ec = CreateEmitContext (Parent, null);
7839 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7840 ec.EmitTopBlock (this, Block);
7843 source.CloseMethod ();
7848 // Operator cannot be override
7849 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7854 public static string GetName (OpType ot)
7856 return names [(int) ot] [0];
7859 public static string GetName (string metadata_name)
7861 for (int i = 0; i < names.Length; ++i) {
7862 if (names [i] [1] == metadata_name)
7863 return names [i] [0];
7868 public static string GetMetadataName (OpType ot)
7870 return names [(int) ot] [1];
7873 public static string GetMetadataName (string name)
7875 for (int i = 0; i < names.Length; ++i) {
7876 if (names [i] [0] == name)
7877 return names [i] [1];
7882 public OpType GetMatchingOperator ()
7884 switch (OperatorType) {
7885 case OpType.Equality:
7886 return OpType.Inequality;
7887 case OpType.Inequality:
7888 return OpType.Equality;
7890 return OpType.False;
7893 case OpType.GreaterThan:
7894 return OpType.LessThan;
7895 case OpType.LessThan:
7896 return OpType.GreaterThan;
7897 case OpType.GreaterThanOrEqual:
7898 return OpType.LessThanOrEqual;
7899 case OpType.LessThanOrEqual:
7900 return OpType.GreaterThanOrEqual;
7906 public override string GetSignatureForError ()
7908 StringBuilder sb = new StringBuilder ();
7909 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7910 sb.AppendFormat ("{0}.{1} operator {2}",
7911 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7914 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7917 sb.Append (Parameters.GetSignatureForError ());
7918 return sb.ToString ();
7923 // This is used to compare method signatures
7925 struct MethodSignature {
7927 public Type RetType;
7928 public Type [] Parameters;
7931 /// This delegate is used to extract methods which have the
7932 /// same signature as the argument
7934 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7936 public MethodSignature (string name, Type ret_type, Type [] parameters)
7941 if (parameters == null)
7942 Parameters = Type.EmptyTypes;
7944 Parameters = parameters;
7947 public override string ToString ()
7950 if (Parameters.Length != 0){
7951 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7952 for (int i = 0; i < Parameters.Length; i++){
7953 sb.Append (Parameters [i]);
7954 if (i+1 < Parameters.Length)
7957 pars = sb.ToString ();
7960 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7963 public override int GetHashCode ()
7965 return Name.GetHashCode ();
7968 public override bool Equals (Object o)
7970 MethodSignature other = (MethodSignature) o;
7972 if (other.Name != Name)
7975 if (other.RetType != RetType)
7978 if (Parameters == null){
7979 if (other.Parameters == null)
7984 if (other.Parameters == null)
7987 int c = Parameters.Length;
7988 if (other.Parameters.Length != c)
7991 for (int i = 0; i < c; i++)
7992 if (other.Parameters [i] != Parameters [i])
7998 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8000 MethodSignature sig = (MethodSignature) filter_criteria;
8002 if (m.Name != sig.Name)
8006 MethodInfo mi = m as MethodInfo;
8007 PropertyInfo pi = m as PropertyInfo;
8010 ReturnType = mi.ReturnType;
8011 else if (pi != null)
8012 ReturnType = pi.PropertyType;
8017 // we use sig.RetType == null to mean `do not check the
8018 // method return value.
8020 if (sig.RetType != null) {
8021 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8027 args = TypeManager.GetParameterData (mi).Types;
8029 args = TypeManager.GetParameterData (pi).Types;
8030 Type [] sigp = sig.Parameters;
8032 if (args.Length != sigp.Length)
8035 for (int i = args.Length - 1; i >= 0; i--)
8036 if (!TypeManager.IsEqual (args [i], sigp [i]))