2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.CompilerServices;
20 using System.Runtime.InteropServices;
21 using System.Security;
22 using System.Security.Permissions;
25 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
26 using XmlElement = System.Object;
31 using Mono.CompilerServices.SymbolWriter;
33 namespace Mono.CSharp {
45 /// This is the base class for structs and classes.
47 public abstract class TypeContainer : DeclSpace, IMemberContainer {
49 public class MemberCoreArrayList: ArrayList
52 /// Defines the MemberCore objects that are in this array
54 public virtual void DefineContainerMembers ()
56 foreach (MemberCore mc in this) {
59 } catch (Exception e) {
60 throw new InternalErrorException (mc, e);
65 public virtual void Emit ()
67 foreach (MemberCore mc in this)
72 public class OperatorArrayList: MemberCoreArrayList
74 TypeContainer container;
76 public OperatorArrayList (TypeContainer container)
78 this.container = container;
82 // Checks that some operators come in pairs:
88 // They are matched based on the return type and the argument types
90 void CheckPairedOperators ()
92 bool has_equality_or_inequality = false;
93 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
94 bool [] has_pair = new bool [operators.Length];
96 for (int i = 0; i < Count; ++i) {
97 if (operators [i] == null)
100 Operator o_a = operators [i];
101 Operator.OpType o_type = o_a.OperatorType;
102 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
103 has_equality_or_inequality = true;
105 Operator.OpType matching_type = o_a.GetMatchingOperator ();
106 if (matching_type == Operator.OpType.TOP) {
107 operators [i] = null;
111 for (int ii = 0; ii < Count; ++ii) {
112 Operator o_b = operators [ii];
113 if (o_b == null || o_b.OperatorType != matching_type)
116 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
119 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
122 operators [i] = null;
125 // Used to ignore duplicate user conversions
127 has_pair [ii] = true;
131 for (int i = 0; i < Count; ++i) {
132 if (operators [i] == null || has_pair [i])
135 Operator o = operators [i];
136 Report.Error (216, o.Location,
137 "The operator `{0}' requires a matching operator `{1}' to also be defined",
138 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
141 if (has_equality_or_inequality && Report.WarningLevel > 2) {
142 if (container.Methods == null || !container.HasEquals)
143 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
145 if (container.Methods == null || !container.HasGetHashCode)
146 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
150 public override void DefineContainerMembers ()
152 base.DefineContainerMembers ();
153 CheckPairedOperators ();
161 GetHashCode = 1 << 1,
162 HasStaticFieldInitializer = 1 << 2
166 // Whether this is a struct, class or interface
167 public readonly Kind Kind;
169 // Holds a list of classes and structures
170 protected ArrayList types;
172 MemberCoreArrayList ordered_explicit_member_list;
173 MemberCoreArrayList ordered_member_list;
175 // Holds the list of properties
176 MemberCoreArrayList properties;
178 // Holds the list of delegates
179 MemberCoreArrayList delegates;
181 // Holds the list of constructors
182 protected MemberCoreArrayList instance_constructors;
184 // Holds the list of fields
185 protected MemberCoreArrayList fields;
187 // Holds a list of fields that have initializers
188 protected ArrayList initialized_fields;
190 // Holds a list of static fields that have initializers
191 protected ArrayList initialized_static_fields;
193 // Holds the list of constants
194 protected MemberCoreArrayList constants;
196 // Holds the methods.
197 MemberCoreArrayList methods;
200 protected MemberCoreArrayList events;
202 // Holds the indexers
205 // Holds the operators
206 MemberCoreArrayList operators;
208 // Holds the compiler generated classes
209 ArrayList compiler_generated;
212 // Pointers to the default constructor and the default static constructor
214 protected Constructor default_constructor;
215 protected Constructor default_static_constructor;
218 // Points to the first non-static field added to the container.
220 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
221 // and the first one's as good as any.
223 FieldBase first_nonstatic_field = null;
226 // This one is computed after we can distinguish interfaces
227 // from classes from the arraylist `type_bases'
230 TypeExpr[] iface_exprs;
233 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;
249 protected bool requires_delayed_unmanagedtype_check;
251 private CachedMethods cached_method;
253 ArrayList partial_parts;
256 /// The pending methods that need to be implemented
257 // (interfaces or abstract methods)
259 PendingImplementation pending;
261 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
262 Attributes attrs, Kind kind)
263 : base (ns, parent, name, attrs)
265 if (parent != null && parent.NamespaceEntry != ns)
266 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
269 this.PartialContainer = this;
272 public bool AddMember (MemberCore symbol)
274 return AddToContainer (symbol, symbol.MemberName.Basename);
277 protected virtual bool AddMemberType (DeclSpace ds)
279 return AddToContainer (ds, ds.Basename);
282 protected virtual void RemoveMemberType (DeclSpace ds)
284 RemoveFromContainer (ds.Basename);
287 public void AddConstant (Const constant)
289 if (!AddMember (constant))
292 if (constants == null)
293 constants = new MemberCoreArrayList ();
295 constants.Add (constant);
298 public TypeContainer AddTypeContainer (TypeContainer tc)
300 if (!AddMemberType (tc))
304 types = new MemberCoreArrayList ();
310 public virtual TypeContainer AddPartial (TypeContainer next_part)
312 return AddPartial (next_part, next_part.Basename);
315 protected TypeContainer AddPartial (TypeContainer next_part, string name)
317 next_part.ModFlags |= Modifiers.PARTIAL;
318 TypeContainer tc = defined_names [name] as TypeContainer;
321 return AddTypeContainer (next_part);
323 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
324 Report.SymbolRelatedToPreviousError (next_part);
325 Error_MissingPartialModifier (tc);
328 if (tc.Kind != next_part.Kind) {
329 Report.SymbolRelatedToPreviousError (tc);
330 Report.Error (261, next_part.Location,
331 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
332 next_part.GetSignatureForError ());
335 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
336 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
337 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
338 Report.SymbolRelatedToPreviousError (tc);
339 Report.Error (262, next_part.Location,
340 "Partial declarations of `{0}' have conflicting accessibility modifiers",
341 next_part.GetSignatureForError ());
344 if (tc.partial_parts == null)
345 tc.partial_parts = new ArrayList (1);
347 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
348 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
349 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
350 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
351 tc.ModFlags |= next_part.ModFlags;
353 tc.ModFlags |= next_part.ModFlags;
356 if (next_part.attributes != null) {
357 if (tc.attributes == null)
358 tc.attributes = next_part.attributes;
360 tc.attributes.AddAttributes (next_part.attributes.Attrs);
363 next_part.PartialContainer = tc;
364 tc.partial_parts.Add (next_part);
368 public virtual void RemoveTypeContainer (TypeContainer next_part)
371 types.Remove (next_part);
372 RemoveMemberType (next_part);
375 public void AddDelegate (Delegate d)
377 if (!AddMemberType (d))
380 if (delegates == null)
381 delegates = new MemberCoreArrayList ();
386 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
388 if (ordered_explicit_member_list == null) {
389 ordered_explicit_member_list = new MemberCoreArrayList ();
390 ordered_member_list = new MemberCoreArrayList ();
394 if (Kind == Kind.Interface) {
395 Report.Error (541, mc.Location,
396 "`{0}': explicit interface declaration can only be declared in a class or struct",
397 mc.GetSignatureForError ());
400 ordered_explicit_member_list.Add (mc);
401 alist.Insert (0, mc);
403 ordered_member_list.Add (mc);
409 public void AddMethod (Method method)
411 if (!AddToContainer (method, method.MemberName.Basename))
415 methods = new MemberCoreArrayList ();
417 if (method.MemberName.Left != null)
418 AddMemberToList (method, methods, true);
420 AddMemberToList (method, methods, false);
423 public void AddConstructor (Constructor c)
425 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
426 if (!AddToContainer (c, is_static ?
427 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
430 if (is_static && c.Parameters.IsEmpty){
431 if (default_static_constructor != null) {
432 Report.SymbolRelatedToPreviousError (default_static_constructor);
433 Report.Error (111, c.Location,
434 "A member `{0}' is already defined. Rename this member or use different parameter types",
435 c.GetSignatureForError ());
439 default_static_constructor = c;
441 if (c.Parameters.IsEmpty)
442 default_constructor = c;
444 if (instance_constructors == null)
445 instance_constructors = new MemberCoreArrayList ();
447 instance_constructors.Add (c);
451 public bool AddField (FieldBase field)
453 if (!AddMember (field))
457 fields = new MemberCoreArrayList ();
461 if ((field.ModFlags & Modifiers.STATIC) != 0)
464 if (first_nonstatic_field == null) {
465 first_nonstatic_field = field;
469 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
470 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
471 Report.Warning (282, 3, field.Location,
472 "struct instance field `{0}' found in different declaration from instance field `{1}'",
473 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
478 public void AddProperty (Property prop)
480 if (!AddMember (prop) ||
481 !AddMember (prop.Get) || !AddMember (prop.Set))
484 if (properties == null)
485 properties = new MemberCoreArrayList ();
487 if (prop.MemberName.Left != null)
488 AddMemberToList (prop, properties, true);
490 AddMemberToList (prop, properties, false);
493 public void AddEvent (Event e)
498 if (e is EventProperty) {
499 if (!AddMember (e.Add))
502 if (!AddMember (e.Remove))
507 events = new MemberCoreArrayList ();
513 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
515 public void AddIndexer (Indexer i)
517 if (indexers == null)
518 indexers = new ArrayList ();
520 if (i.IsExplicitImpl)
521 AddMemberToList (i, indexers, true);
523 AddMemberToList (i, indexers, false);
526 public void AddOperator (Operator op)
531 if (operators == null)
532 operators = new OperatorArrayList (this);
537 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
539 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
541 if (compiler_generated == null)
542 compiler_generated = new ArrayList ();
544 compiler_generated.Add (c);
547 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
549 if (a.Type == TypeManager.default_member_type) {
550 if (Indexers != null) {
551 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
556 base.ApplyAttributeBuilder (a, cb);
559 public override AttributeTargets AttributeTargets {
561 throw new NotSupportedException ();
565 public ArrayList Types {
571 public MemberCoreArrayList Methods {
577 public ArrayList Constants {
583 protected Type BaseType {
585 return TypeBuilder.BaseType;
589 public ArrayList Fields {
595 public ArrayList InstanceConstructors {
597 return instance_constructors;
601 public ArrayList Properties {
607 public ArrayList Events {
613 public ArrayList Indexers {
619 public ArrayList Operators {
625 public ArrayList Delegates {
631 protected override TypeAttributes TypeAttr {
633 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
637 public string IndexerName {
639 return indexers == null ? DefaultIndexerName : indexer_name;
643 public bool IsComImport {
645 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
648 return OptAttributes.Contains (TypeManager.comimport_attr_type);
652 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
654 if ((field.ModFlags & Modifiers.STATIC) != 0){
655 if (initialized_static_fields == null) {
656 PartialContainer.HasStaticFieldInitializer = true;
657 initialized_static_fields = new ArrayList (4);
660 initialized_static_fields.Add (expression);
662 if (initialized_fields == null)
663 initialized_fields = new ArrayList (4);
665 initialized_fields.Add (expression);
669 public void ResolveFieldInitializers (EmitContext ec)
671 if (partial_parts != null) {
672 foreach (TypeContainer part in partial_parts) {
673 part.DoResolveFieldInitializers (ec);
676 DoResolveFieldInitializers (ec);
679 void DoResolveFieldInitializers (EmitContext ec)
682 if (initialized_static_fields == null)
685 bool has_complex_initializer = !RootContext.Optimize;
687 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
688 for (i = 0; i < initialized_static_fields.Count; ++i) {
689 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
690 ExpressionStatement s = fi.ResolveStatement (ec);
692 s = EmptyExpressionStatement.Instance;
693 } else if (fi.IsComplexInitializer) {
694 has_complex_initializer |= true;
700 for (i = 0; i < initialized_static_fields.Count; ++i) {
701 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
703 // Need special check to not optimize code like this
704 // static int a = b = 5;
707 if (!has_complex_initializer && fi.IsDefaultInitializer)
710 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
716 if (initialized_fields == null)
719 for (int i = 0; i < initialized_fields.Count; ++i) {
720 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
721 ExpressionStatement s = fi.ResolveStatement (ec);
726 // Field is re-initialized to its default value => removed
728 if (fi.IsDefaultInitializer && RootContext.Optimize)
731 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
736 // Emits the instance field initializers
738 public bool EmitFieldInitializers (EmitContext ec)
740 if (partial_parts != null) {
741 foreach (TypeContainer part in partial_parts)
742 part.EmitFieldInitializers (ec);
748 fields = initialized_static_fields;
750 fields = initialized_fields;
756 foreach (FieldInitializer f in fields) {
757 f.EmitStatement (ec);
762 public override string DocComment {
774 public PendingImplementation PendingImplementations {
775 get { return pending; }
778 public override bool GetClsCompliantAttributeValue ()
780 if (PartialContainer != this)
781 return PartialContainer.GetClsCompliantAttributeValue ();
783 return base.GetClsCompliantAttributeValue ();
786 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
788 // FIXME: get rid of partial_parts and store lists of bases of each part here
789 // assumed, not verified: 'part' is in 'partial_parts'
790 ((TypeContainer) part).type_bases = bases;
794 /// This function computes the Base class and also the
795 /// list of interfaces that the class or struct @c implements.
797 /// The return value is an array (might be null) of
798 /// interfaces implemented (as Types).
800 /// The @base_class argument is set to the base object or null
801 /// if this is `System.Object'.
803 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
806 if (type_bases == null)
809 int count = type_bases.Count;
810 TypeExpr [] ifaces = null;
811 for (int i = 0, j = 0; i < count; i++){
812 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
815 // Standard ResolveAsTypeTerminal cannot be used in this case because
816 // it does ObsoleteAttribute and constraint checks which require
817 // base type to be set
819 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
820 if (fne_resolved == null)
823 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
824 base_class = fne_resolved;
829 ifaces = new TypeExpr [count - i];
831 if (fne_resolved.Type.IsInterface) {
832 for (int ii = 0; ii < j; ++ii) {
833 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
834 Report.Error (528, Location, "`{0}' is already listed in interface list",
835 fne_resolved.GetSignatureForError ());
840 if (Kind == Kind.Interface && !fne_resolved.AsAccessible (this)) {
841 Report.Error (61, fne.Location,
842 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
843 fne_resolved.GetSignatureForError (), GetSignatureForError ());
846 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
847 if (Kind != Kind.Class) {
848 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
849 } else if (base_class != null)
850 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
851 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
853 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
854 GetSignatureForError (), fne_resolved.GetSignatureForError ());
858 ifaces [j++] = fne_resolved;
864 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
866 ArrayList ifaces = new ArrayList (0);
867 if (iface_exprs != null)
868 ifaces.AddRange (iface_exprs);
870 foreach (TypeContainer part in partial_parts) {
871 TypeExpr new_base_class;
872 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
873 if (new_base_class != TypeManager.system_object_expr) {
874 if (base_class == TypeManager.system_object_expr)
875 base_class = new_base_class;
877 if (new_base_class != null && !new_base_class.Equals (base_class)) {
878 Report.SymbolRelatedToPreviousError (base_class.Location, "");
879 Report.Error (263, part.Location,
880 "Partial declarations of `{0}' must not specify different base classes",
881 part.GetSignatureForError ());
888 if (new_ifaces == null)
891 foreach (TypeExpr iface in new_ifaces) {
892 if (ifaces.Contains (iface))
899 if (ifaces.Count == 0)
902 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
905 bool CheckGenericInterfaces (Type[] ifaces)
908 ArrayList already_checked = new ArrayList ();
910 for (int i = 0; i < ifaces.Length; i++) {
911 Type iface = ifaces [i];
912 foreach (Type t in already_checked) {
916 Type[] inferred = new Type [CountTypeParameters];
917 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
920 Report.Error (695, Location,
921 "`{0}' cannot implement both `{1}' and `{2}' " +
922 "because they may unify for some type parameter substitutions",
923 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
924 TypeManager.CSharpName (t));
928 already_checked.Add (iface);
937 bool CreateTypeBuilder ()
940 Type default_parent = null;
941 if (Kind == Kind.Struct)
942 default_parent = TypeManager.value_type;
943 else if (Kind == Kind.Enum)
944 default_parent = TypeManager.enum_type;
947 // Sets .size to 1 for structs with no instance fields
949 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
952 if (TypeManager.NamespaceClash (Name, Location)) {
956 ModuleBuilder builder = CodeGen.Module.Builder;
957 TypeBuilder = builder.DefineType (
958 Name, TypeAttr, default_parent, type_size);
960 TypeBuilder builder = Parent.TypeBuilder;
962 TypeBuilder = builder.DefineNestedType (
963 Basename, TypeAttr, default_parent, type_size);
965 } catch (ArgumentException) {
966 Report.RuntimeMissingSupport (Location, "static classes");
970 TypeManager.AddUserType (this);
974 string[] param_names = new string [TypeParameters.Length];
975 for (int i = 0; i < TypeParameters.Length; i++)
976 param_names [i] = TypeParameters [i].Name;
978 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
980 int offset = CountTypeParameters - CurrentTypeParameters.Length;
981 for (int i = offset; i < gen_params.Length; i++)
982 CurrentTypeParameters [i - offset].Define (gen_params [i]);
989 bool DefineBaseTypes ()
991 iface_exprs = ResolveBaseTypes (out base_type);
992 if (partial_parts != null) {
993 iface_exprs = GetNormalPartialBases (ref base_type);
997 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
998 // which in turn should have called DefineType()s on base types if necessary.
1000 // None of the code below should trigger DefineType()s on classes that we depend on.
1001 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1003 // Let's do it as soon as possible, since code below can call DefineType() on classes
1004 // that depend on us to be populated before they are.
1006 if (!(this is CompilerGeneratedClass))
1007 RootContext.RegisterOrder (this);
1009 if (!CheckRecursiveDefinition (this))
1012 if (base_type != null && base_type.Type != null) {
1013 TypeBuilder.SetParent (base_type.Type);
1016 // add interfaces that were not added at type creation
1017 if (iface_exprs != null) {
1018 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1022 foreach (Type itype in ifaces)
1023 TypeBuilder.AddInterfaceImplementation (itype);
1025 if (!CheckGenericInterfaces (ifaces))
1028 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1035 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1037 public TypeBuilder CreateType ()
1039 if (TypeBuilder != null)
1045 if (!CreateTypeBuilder ()) {
1050 if (partial_parts != null) {
1051 foreach (TypeContainer part in partial_parts)
1052 part.TypeBuilder = TypeBuilder;
1055 if (Types != null) {
1056 foreach (TypeContainer tc in Types) {
1057 if (tc.CreateType () == null) {
1069 public override TypeBuilder DefineType ()
1076 type_defined = true;
1078 if (CreateType () == null) {
1083 if (!DefineBaseTypes ()) {
1088 if (!DefineNestedTypes ()) {
1096 public override void SetParameterInfo (ArrayList constraints_list)
1098 base.SetParameterInfo (constraints_list);
1100 if (!is_generic || PartialContainer == this)
1103 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1104 for (int i = 0; i < tc_names.Length; ++i) {
1105 if (tc_names [i].Name != type_params [i].Name) {
1106 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1107 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1108 GetSignatureForError ());
1114 void UpdateTypeParameterConstraints (TypeContainer part)
1116 TypeParameter[] current_params = CurrentTypeParameters;
1117 for (int i = 0; i < current_params.Length; i++) {
1118 Constraints c = part.CurrentTypeParameters [i].Constraints;
1122 if (current_params [i].UpdateConstraints (part, c))
1125 Report.SymbolRelatedToPreviousError (Location, "");
1126 Report.Error (265, part.Location,
1127 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1128 GetSignatureForError (), current_params [i].GetSignatureForError ());
1132 public bool ResolveType ()
1134 if (!DoResolveType ())
1137 if (compiler_generated != null) {
1138 foreach (CompilerGeneratedClass c in compiler_generated)
1139 if (!c.ResolveType ())
1146 protected virtual bool DoResolveType ()
1148 if ((base_type != null) &&
1149 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1157 if (PartialContainer != this)
1158 throw new InternalErrorException ();
1160 TypeExpr current_type = null;
1162 foreach (TypeParameter type_param in CurrentTypeParameters) {
1163 if (!type_param.Resolve (this)) {
1169 if (partial_parts != null && is_generic) {
1170 foreach (TypeContainer part in partial_parts)
1171 UpdateTypeParameterConstraints (part);
1174 foreach (TypeParameter type_param in TypeParameters) {
1175 if (!type_param.DefineType (this)) {
1181 // TODO: Very strange, why not simple make generic type from
1182 // current type parameters
1183 current_type = new GenericTypeExpr (this, Location);
1184 current_type = current_type.ResolveAsTypeTerminal (this, false);
1185 if (current_type == null) {
1190 CurrentType = current_type.Type;
1194 protected virtual bool DefineNestedTypes ()
1196 if (Types != null) {
1197 foreach (TypeContainer tc in Types)
1198 if (tc.DefineType () == null)
1202 if (Delegates != null) {
1203 foreach (Delegate d in Delegates)
1204 if (d.DefineType () == null)
1211 TypeContainer InTransit;
1213 protected bool CheckRecursiveDefinition (TypeContainer tc)
1215 if (InTransit != null) {
1216 Report.SymbolRelatedToPreviousError (this);
1217 if (this is Interface)
1219 529, tc.Location, "Inherited interface `{0}' causes a " +
1220 "cycle in the interface hierarchy of `{1}'",
1221 GetSignatureForError (), tc.GetSignatureForError ());
1224 146, tc.Location, "Circular base class dependency " +
1225 "involving `{0}' and `{1}'",
1226 tc.GetSignatureForError (), GetSignatureForError ());
1232 if (base_type != null && base_type.Type != null) {
1233 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1234 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1235 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1239 if (iface_exprs != null) {
1240 foreach (TypeExpr iface in iface_exprs) {
1241 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1242 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1243 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1248 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1256 /// Populates our TypeBuilder with fields and methods
1258 public override bool Define ()
1260 if (members_defined)
1261 return members_defined_ok;
1263 members_defined_ok = DoDefineMembers ();
1264 members_defined = true;
1266 return members_defined_ok;
1269 protected virtual bool DoDefineMembers ()
1271 if (iface_exprs != null) {
1272 foreach (TypeExpr iface in iface_exprs) {
1273 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1274 if ((oa != null) && !IsInObsoleteScope)
1275 AttributeTester.Report_ObsoleteMessage (
1276 oa, iface.GetSignatureForError (), Location);
1278 GenericTypeExpr ct = iface as GenericTypeExpr;
1279 if ((ct != null) && !ct.CheckConstraints (this))
1284 if (base_type != null) {
1285 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1286 if (obsolete_attr != null && !IsInObsoleteScope)
1287 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1289 GenericTypeExpr ct = base_type as GenericTypeExpr;
1290 if ((ct != null) && !ct.CheckConstraints (this))
1293 member_cache = new MemberCache (base_type.Type, this);
1294 } else if (Kind == Kind.Interface) {
1295 member_cache = new MemberCache (null, this);
1296 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1297 for (int i = 0; i < ifaces.Length; ++i)
1298 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1300 member_cache = new MemberCache (null, this);
1304 foreach (TypeContainer tc in types)
1305 member_cache.AddNestedType (tc);
1307 if (delegates != null)
1308 foreach (Delegate d in delegates)
1309 member_cache.AddNestedType (d);
1311 if (partial_parts != null) {
1312 foreach (TypeContainer part in partial_parts)
1313 part.member_cache = member_cache;
1317 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1318 if (conflict_symbol == null) {
1319 if ((ModFlags & Modifiers.NEW) != 0)
1320 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1322 if ((ModFlags & Modifiers.NEW) == 0) {
1323 Report.SymbolRelatedToPreviousError (conflict_symbol);
1324 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1325 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1330 DefineContainerMembers (constants);
1331 DefineContainerMembers (fields);
1333 if (Kind == Kind.Struct || Kind == Kind.Class) {
1334 pending = PendingImplementation.GetPendingImplementations (this);
1336 if (requires_delayed_unmanagedtype_check) {
1337 requires_delayed_unmanagedtype_check = false;
1338 foreach (Field f in fields) {
1339 if (f.MemberType != null && f.MemberType.IsPointer)
1340 TypeManager.VerifyUnManaged (f.MemberType, f.Location);
1346 // Constructors are not in the defined_names array
1348 DefineContainerMembers (instance_constructors);
1350 DefineContainerMembers (events);
1351 DefineContainerMembers (ordered_explicit_member_list);
1352 DefineContainerMembers (ordered_member_list);
1354 DefineContainerMembers (operators);
1355 DefineContainerMembers (delegates);
1357 ComputeIndexerName();
1358 CheckEqualsAndGetHashCode();
1360 if (CurrentType != null) {
1361 GenericType = CurrentType;
1366 // FIXME: This hack is needed because member cache does not work
1367 // with generic types, we rely on runtime to inflate dynamic types.
1368 // TODO: This hack requires member cache refactoring to be removed
1370 if (TypeBuilder.IsGenericType)
1371 member_cache = new MemberCache (this);
1377 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1380 mcal.DefineContainerMembers ();
1383 protected virtual void ComputeIndexerName ()
1385 if (indexers == null)
1388 string class_indexer_name = null;
1391 // If there's both an explicit and an implicit interface implementation, the
1392 // explicit one actually implements the interface while the other one is just
1393 // a normal indexer. See bug #37714.
1396 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1397 foreach (Indexer i in indexers) {
1398 if (i.InterfaceType != null) {
1399 if (seen_normal_indexers)
1400 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1404 seen_normal_indexers = true;
1406 if (class_indexer_name == null) {
1407 class_indexer_name = i.ShortName;
1411 if (i.ShortName != class_indexer_name)
1412 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");
1415 if (class_indexer_name != null)
1416 indexer_name = class_indexer_name;
1419 protected virtual void EmitIndexerName ()
1421 if (!seen_normal_indexers)
1424 if (TypeManager.default_member_ctor == null) {
1425 if (TypeManager.default_member_type == null) {
1426 TypeManager.default_member_type = TypeManager.CoreLookupType (
1427 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1429 if (TypeManager.default_member_type == null)
1433 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1434 TypeManager.default_member_type, Location, TypeManager.string_type);
1436 if (TypeManager.default_member_ctor == null)
1440 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1441 TypeBuilder.SetCustomAttribute (cb);
1444 protected virtual void CheckEqualsAndGetHashCode ()
1446 if (methods == null)
1449 if (HasEquals && !HasGetHashCode) {
1450 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1454 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1456 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1460 /// This function is based by a delegate to the FindMembers routine
1462 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1468 /// This filter is used by FindMembers, and we just keep
1469 /// a global for the filter to `AlwaysAccept'
1471 static MemberFilter accepting_filter;
1474 static TypeContainer ()
1476 accepting_filter = new MemberFilter (AlwaysAccept);
1479 public MethodInfo[] GetMethods ()
1481 ArrayList members = new ArrayList ();
1485 if (methods != null) {
1486 int len = methods.Count;
1487 for (int i = 0; i < len; i++) {
1488 Method m = (Method) methods [i];
1490 members.Add (m.MethodBuilder);
1494 if (operators != null) {
1495 int len = operators.Count;
1496 for (int i = 0; i < len; i++) {
1497 Operator o = (Operator) operators [i];
1499 members.Add (o.MethodBuilder);
1503 if (properties != null) {
1504 int len = properties.Count;
1505 for (int i = 0; i < len; i++) {
1506 Property p = (Property) properties [i];
1508 if (p.GetBuilder != null)
1509 members.Add (p.GetBuilder);
1510 if (p.SetBuilder != null)
1511 members.Add (p.SetBuilder);
1515 if (indexers != null) {
1516 int len = indexers.Count;
1517 for (int i = 0; i < len; i++) {
1518 Indexer ix = (Indexer) indexers [i];
1520 if (ix.GetBuilder != null)
1521 members.Add (ix.GetBuilder);
1522 if (ix.SetBuilder != null)
1523 members.Add (ix.SetBuilder);
1527 if (events != null) {
1528 int len = events.Count;
1529 for (int i = 0; i < len; i++) {
1530 Event e = (Event) events [i];
1532 if (e.AddBuilder != null)
1533 members.Add (e.AddBuilder);
1534 if (e.RemoveBuilder != null)
1535 members.Add (e.RemoveBuilder);
1539 MethodInfo[] retMethods = new MethodInfo [members.Count];
1540 members.CopyTo (retMethods, 0);
1544 // Indicated whether container has StructLayout attribute set Explicit
1545 public bool HasExplicitLayout {
1546 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1547 set { caching_flags |= Flags.HasExplicitLayout; }
1550 public bool HasStructLayout {
1551 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1552 set { caching_flags |= Flags.HasStructLayout; }
1556 // Return the nested type with name @name. Ensures that the nested type
1557 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1559 public Type FindNestedType (string name)
1561 if (PartialContainer != this)
1562 throw new InternalErrorException ("should not happen");
1564 ArrayList [] lists = { types, delegates };
1566 for (int j = 0; j < lists.Length; ++j) {
1567 ArrayList list = lists [j];
1571 int len = list.Count;
1572 for (int i = 0; i < len; ++i) {
1573 DeclSpace ds = (DeclSpace) list [i];
1574 if (ds.Basename == name) {
1575 return ds.DefineType ();
1583 private void FindMembers_NestedTypes (int modflags,
1584 BindingFlags bf, MemberFilter filter, object criteria,
1585 ref ArrayList members)
1587 ArrayList [] lists = { types, delegates };
1589 for (int j = 0; j < lists.Length; ++j) {
1590 ArrayList list = lists [j];
1594 int len = list.Count;
1595 for (int i = 0; i < len; i++) {
1596 DeclSpace ds = (DeclSpace) list [i];
1598 if ((ds.ModFlags & modflags) == 0)
1601 TypeBuilder tb = ds.TypeBuilder;
1603 if (!(criteria is string) || ds.Basename.Equals (criteria))
1604 tb = ds.DefineType ();
1607 if (tb != null && (filter (tb, criteria) == true)) {
1608 if (members == null)
1609 members = new ArrayList ();
1618 /// This method returns the members of this type just like Type.FindMembers would
1619 /// Only, we need to use this for types which are _being_ defined because MS'
1620 /// implementation can't take care of that.
1623 // FIXME: return an empty static array instead of null, that cleans up
1624 // some code and is consistent with some coding conventions I just found
1628 // Notice that in various cases we check if our field is non-null,
1629 // something that would normally mean that there was a bug elsewhere.
1631 // The problem happens while we are defining p-invoke methods, as those
1632 // will trigger a FindMembers, but this happens before things are defined
1634 // Since the whole process is a no-op, it is fine to check for null here.
1636 // TODO: This approach will be one day completely removed, it's already
1637 // used at few places only
1640 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1641 MemberFilter filter, object criteria)
1643 ArrayList members = null;
1646 if ((bf & BindingFlags.Public) != 0)
1647 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1649 if ((bf & BindingFlags.NonPublic) != 0)
1650 modflags |= Modifiers.PRIVATE;
1652 int static_mask = 0, static_flags = 0;
1653 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1654 case BindingFlags.Static:
1655 static_mask = static_flags = Modifiers.STATIC;
1658 case BindingFlags.Instance:
1659 static_mask = Modifiers.STATIC;
1664 static_mask = static_flags = 0;
1668 Timer.StartTimer (TimerType.TcFindMembers);
1671 filter = accepting_filter;
1673 if ((mt & MemberTypes.Field) != 0) {
1674 if (fields != null) {
1675 int len = fields.Count;
1676 for (int i = 0; i < len; i++) {
1677 FieldBase f = (FieldBase) fields [i];
1679 if ((f.ModFlags & modflags) == 0)
1681 if ((f.ModFlags & static_mask) != static_flags)
1684 FieldBuilder fb = f.FieldBuilder;
1685 if (fb != null && filter (fb, criteria) == true) {
1686 if (members == null)
1687 members = new ArrayList ();
1694 if (constants != null) {
1695 int len = constants.Count;
1696 for (int i = 0; i < len; i++) {
1697 Const con = (Const) constants [i];
1699 if ((con.ModFlags & modflags) == 0)
1701 if ((con.ModFlags & static_mask) != static_flags)
1704 FieldBuilder fb = con.FieldBuilder;
1707 fb = con.FieldBuilder;
1709 if (fb != null && filter (fb, criteria) == true) {
1710 if (members == null)
1711 members = new ArrayList ();
1719 if ((mt & MemberTypes.Method) != 0) {
1720 if (methods != null) {
1721 int len = methods.Count;
1722 for (int i = 0; i < len; i++) {
1723 Method m = (Method) methods [i];
1725 if ((m.ModFlags & modflags) == 0)
1727 if ((m.ModFlags & static_mask) != static_flags)
1730 MethodBuilder mb = m.MethodBuilder;
1732 if (mb != null && filter (mb, criteria) == true) {
1733 if (members == null)
1734 members = new ArrayList ();
1741 if (operators != null) {
1742 int len = operators.Count;
1743 for (int i = 0; i < len; i++) {
1744 Operator o = (Operator) operators [i];
1746 if ((o.ModFlags & modflags) == 0)
1748 if ((o.ModFlags & static_mask) != static_flags)
1751 MethodBuilder ob = o.MethodBuilder;
1752 if (ob != null && filter (ob, criteria) == true) {
1753 if (members == null)
1754 members = new ArrayList ();
1761 if (events != null) {
1762 foreach (Event e in events) {
1763 if ((e.ModFlags & modflags) == 0)
1765 if ((e.ModFlags & static_mask) != static_flags)
1768 MethodBuilder b = e.AddBuilder;
1769 if (b != null && filter (b, criteria)) {
1770 if (members == null)
1771 members = new ArrayList (4);
1776 b = e.RemoveBuilder;
1777 if (b != null && filter (b, criteria)) {
1778 if (members == null)
1779 members = new ArrayList (4);
1786 if (properties != null) {
1787 int len = properties.Count;
1788 for (int i = 0; i < len; i++) {
1789 Property p = (Property) properties [i];
1791 if ((p.ModFlags & modflags) == 0)
1793 if ((p.ModFlags & static_mask) != static_flags)
1799 if (b != null && filter (b, criteria) == true) {
1800 if (members == null)
1801 members = new ArrayList ();
1807 if (b != null && filter (b, criteria) == true) {
1808 if (members == null)
1809 members = new ArrayList ();
1816 if (indexers != null) {
1817 int len = indexers.Count;
1818 for (int i = 0; i < len; i++) {
1819 Indexer ix = (Indexer) indexers [i];
1821 if ((ix.ModFlags & modflags) == 0)
1823 if ((ix.ModFlags & static_mask) != static_flags)
1829 if (b != null && filter (b, criteria) == true) {
1830 if (members == null)
1831 members = new ArrayList ();
1837 if (b != null && filter (b, criteria) == true) {
1838 if (members == null)
1839 members = new ArrayList ();
1847 if ((mt & MemberTypes.Event) != 0) {
1848 if (events != null) {
1849 int len = events.Count;
1850 for (int i = 0; i < len; i++) {
1851 Event e = (Event) events [i];
1853 if ((e.ModFlags & modflags) == 0)
1855 if ((e.ModFlags & static_mask) != static_flags)
1858 MemberInfo eb = e.EventBuilder;
1859 if (eb != null && filter (eb, criteria) == true) {
1860 if (members == null)
1861 members = new ArrayList ();
1863 members.Add (e.EventBuilder);
1869 if ((mt & MemberTypes.Property) != 0){
1870 if (properties != null) {
1871 int len = properties.Count;
1872 for (int i = 0; i < len; i++) {
1873 Property p = (Property) properties [i];
1875 if ((p.ModFlags & modflags) == 0)
1877 if ((p.ModFlags & static_mask) != static_flags)
1880 MemberInfo pb = p.PropertyBuilder;
1881 if (pb != null && filter (pb, criteria) == true) {
1882 if (members == null)
1883 members = new ArrayList ();
1885 members.Add (p.PropertyBuilder);
1890 if (indexers != null) {
1891 int len = indexers.Count;
1892 for (int i = 0; i < len; i++) {
1893 Indexer ix = (Indexer) indexers [i];
1895 if ((ix.ModFlags & modflags) == 0)
1897 if ((ix.ModFlags & static_mask) != static_flags)
1900 MemberInfo ib = ix.PropertyBuilder;
1901 if (ib != null && filter (ib, criteria) == true) {
1902 if (members == null)
1903 members = new ArrayList ();
1905 members.Add (ix.PropertyBuilder);
1911 if ((mt & MemberTypes.NestedType) != 0)
1912 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1914 if ((mt & MemberTypes.Constructor) != 0){
1915 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1916 int len = instance_constructors.Count;
1917 for (int i = 0; i < len; i++) {
1918 Constructor c = (Constructor) instance_constructors [i];
1920 ConstructorBuilder cb = c.ConstructorBuilder;
1921 if (cb != null && filter (cb, criteria) == true) {
1922 if (members == null)
1923 members = new ArrayList ();
1930 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1931 ConstructorBuilder cb =
1932 default_static_constructor.ConstructorBuilder;
1934 if (cb != null && filter (cb, criteria) == true) {
1935 if (members == null)
1936 members = new ArrayList ();
1944 // Lookup members in base if requested.
1946 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1947 if (TypeBuilder.BaseType != null) {
1948 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1949 if (list.Count > 0) {
1950 if (members == null)
1951 members = new ArrayList ();
1953 members.AddRange (list);
1958 Timer.StopTimer (TimerType.TcFindMembers);
1960 if (members == null)
1961 return MemberList.Empty;
1963 return new MemberList (members);
1966 public override MemberCache MemberCache {
1968 return member_cache;
1972 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1973 MemberFilter filter, object criteria)
1975 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1978 return ds.FindMembers (mt, bf, filter, criteria);
1980 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1984 /// Emits the values for the constants
1986 public void EmitConstants ()
1988 if (constants != null)
1989 foreach (Const con in constants)
1994 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1999 foreach (MemberCore mc in al) {
2000 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2003 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2004 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2009 public virtual void VerifyMembers ()
2012 // Check for internal or private fields that were never assigned
2014 if (Report.WarningLevel >= 3) {
2015 CheckMemberUsage (properties, "property");
2016 CheckMemberUsage (methods, "method");
2017 CheckMemberUsage (constants, "constant");
2019 if (fields != null){
2020 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2021 foreach (FieldBase f in fields) {
2022 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2023 if (is_type_exposed)
2026 f.SetMemberIsUsed ();
2030 if ((f.caching_flags & Flags.IsAssigned) == 0)
2031 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2034 const int error_code = 414;
2036 const int error_code = 169;
2038 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2039 f.GetSignatureForError ());
2045 // Only report 649 on level 4
2047 if (Report.WarningLevel < 4)
2050 if ((f.caching_flags & Flags.IsAssigned) != 0)
2054 // Don't be pendatic over serializable attributes
2056 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2059 Constant c = New.Constantify (f.MemberType);
2060 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2061 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2067 // TODO: move to ClassOrStruct
2068 void EmitConstructors ()
2070 if (instance_constructors == null)
2073 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2074 bool has_compliant_args = false;
2076 foreach (Constructor c in instance_constructors) {
2080 catch (Exception e) {
2081 throw new InternalErrorException (c, e);
2084 if (has_compliant_args)
2087 has_compliant_args = c.HasCompliantArgs;
2089 if (!has_compliant_args)
2090 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2092 foreach (Constructor c in instance_constructors) {
2096 catch (Exception e) {
2097 throw new InternalErrorException (c, e);
2104 /// Emits the code, this step is performed after all
2105 /// the types, enumerations, constructors
2107 public virtual void EmitType ()
2109 if (OptAttributes != null)
2110 OptAttributes.Emit ();
2114 EmitConstructors ();
2116 // Can not continue if constants are broken
2118 if (Report.Errors > 0)
2121 if (default_static_constructor != null)
2122 default_static_constructor.Emit ();
2124 if (operators != null)
2125 foreach (Operator o in operators)
2128 if (properties != null)
2129 foreach (Property p in properties)
2132 if (indexers != null) {
2133 foreach (Indexer indx in indexers)
2138 if (events != null){
2139 foreach (Event e in Events)
2143 if (methods != null) {
2144 for (int i = 0; i < methods.Count; ++i)
2145 ((Method) methods [i]).Emit ();
2149 foreach (FieldBase f in fields)
2152 if (delegates != null) {
2153 foreach (Delegate d in Delegates) {
2158 if (pending != null)
2159 pending.VerifyPendingMethods ();
2161 if (Report.Errors > 0)
2164 if (compiler_generated != null) {
2165 for (int i = 0; i < compiler_generated.Count; ++i)
2166 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2170 public override void CloseType ()
2172 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2176 caching_flags |= Flags.CloseTypeCreated;
2177 TypeBuilder.CreateType ();
2178 } catch (TypeLoadException){
2180 // This is fine, the code still created the type
2182 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2183 // Console.WriteLine (e.Message);
2184 } catch (Exception e) {
2185 throw new InternalErrorException (this, e);
2189 foreach (TypeContainer tc in Types)
2190 if (tc.Kind == Kind.Struct)
2193 foreach (TypeContainer tc in Types)
2194 if (tc.Kind != Kind.Struct)
2198 if (Delegates != null)
2199 foreach (Delegate d in Delegates)
2202 if (compiler_generated != null)
2203 foreach (CompilerGeneratedClass c in compiler_generated)
2210 initialized_fields = null;
2211 initialized_static_fields = null;
2213 ordered_explicit_member_list = null;
2214 ordered_member_list = null;
2219 compiler_generated = null;
2220 default_constructor = null;
2221 default_static_constructor = null;
2223 OptAttributes = null;
2226 member_cache = null;
2230 // Performs the validation on a Method's modifiers (properties have
2231 // the same properties).
2233 public bool MethodModifiersValid (MemberCore mc)
2235 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2236 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2237 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2239 int flags = mc.ModFlags;
2242 // At most one of static, virtual or override
2244 if ((flags & Modifiers.STATIC) != 0){
2245 if ((flags & vao) != 0){
2246 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2247 mc.GetSignatureForError ());
2252 if (Kind == Kind.Struct){
2253 if ((flags & va) != 0){
2254 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2259 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2260 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2261 mc.GetSignatureForError ());
2266 // If the declaration includes the abstract modifier, then the
2267 // declaration does not include static, virtual or extern
2269 if ((flags & Modifiers.ABSTRACT) != 0){
2270 if ((flags & Modifiers.EXTERN) != 0){
2272 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2276 if ((flags & Modifiers.SEALED) != 0) {
2277 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2281 if ((flags & Modifiers.VIRTUAL) != 0){
2282 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2286 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2287 Report.SymbolRelatedToPreviousError (this);
2288 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2289 mc.GetSignatureForError (), GetSignatureForError ());
2294 if ((flags & Modifiers.PRIVATE) != 0){
2295 if ((flags & vao) != 0){
2296 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2301 if ((flags & Modifiers.SEALED) != 0){
2302 if ((flags & Modifiers.OVERRIDE) == 0){
2303 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2311 public Constructor DefaultStaticConstructor {
2312 get { return default_static_constructor; }
2315 protected override bool VerifyClsCompliance ()
2317 if (!base.VerifyClsCompliance ())
2322 Type base_type = TypeBuilder.BaseType;
2323 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2324 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2331 /// Checks whether container name is CLS Compliant
2333 void VerifyClsName ()
2335 Hashtable base_members = base_cache == null ?
2337 base_cache.GetPublicMembers ();
2338 Hashtable this_members = new Hashtable ();
2340 foreach (DictionaryEntry entry in defined_names) {
2341 MemberCore mc = (MemberCore)entry.Value;
2342 if (!mc.IsClsComplianceRequired ())
2345 string name = (string) entry.Key;
2346 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2348 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2349 object found = base_members [lcase];
2350 if (found == null) {
2351 found = this_members [lcase];
2352 if (found == null) {
2353 this_members.Add (lcase, mc);
2358 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2361 if (found is MemberInfo) {
2362 if (basename == ((MemberInfo) found).Name)
2364 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2366 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2369 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2375 /// Performs checks for an explicit interface implementation. First it
2376 /// checks whether the `interface_type' is a base inteface implementation.
2377 /// Then it checks whether `name' exists in the interface type.
2379 public bool VerifyImplements (InterfaceMemberBase mb)
2381 if (ifaces != null) {
2382 foreach (Type t in ifaces){
2383 if (TypeManager.IsEqual (t, mb.InterfaceType))
2388 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2389 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2390 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2394 public override Type LookupAnyGeneric (string typeName)
2396 if (types != null) {
2397 foreach (TypeContainer tc in types) {
2401 int pos = tc.Basename.LastIndexOf ('`');
2402 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2403 return tc.TypeBuilder;
2407 return base.LookupAnyGeneric (typeName);
2410 public void Mark_HasEquals ()
2412 cached_method |= CachedMethods.Equals;
2415 public void Mark_HasGetHashCode ()
2417 cached_method |= CachedMethods.GetHashCode;
2421 /// Method container contains Equals method
2423 public bool HasEquals {
2425 return (cached_method & CachedMethods.Equals) != 0;
2430 /// Method container contains GetHashCode method
2432 public bool HasGetHashCode {
2434 return (cached_method & CachedMethods.GetHashCode) != 0;
2438 public bool HasStaticFieldInitializer {
2440 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2444 cached_method |= CachedMethods.HasStaticFieldInitializer;
2446 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2454 string IMemberContainer.Name {
2460 Type IMemberContainer.Type {
2466 bool IMemberContainer.IsInterface {
2468 return Kind == Kind.Interface;
2472 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2474 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2476 if (GenericType != null)
2477 return TypeManager.FindMembers (GenericType, mt, new_bf,
2480 return FindMembers (mt, new_bf, null, null);
2484 // Generates xml doc comments (if any), and if required,
2485 // handle warning report.
2487 internal override void GenerateDocComment (DeclSpace ds)
2489 DocUtil.GenerateTypeDocComment (this, ds);
2492 public override string DocCommentHeader {
2493 get { return "T:"; }
2496 public MemberCache BaseCache {
2498 if (base_cache != null)
2500 if (TypeBuilder.BaseType != null)
2501 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2502 if (TypeBuilder.IsInterface)
2503 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2509 public abstract class ClassOrStruct : TypeContainer {
2510 ListDictionary declarative_security;
2512 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2513 MemberName name, Attributes attrs, Kind kind)
2514 : base (ns, parent, name, attrs, kind)
2518 protected override bool AddToContainer (MemberCore symbol, string name)
2520 if (name == MemberName.Name && symbol.MemberName.Left == null) {
2521 if (symbol is TypeParameter) {
2522 Report.Error (694, symbol.Location,
2523 "Type parameter `{0}' has same name as containing type, or method",
2524 symbol.GetSignatureForError ());
2528 Report.SymbolRelatedToPreviousError (this);
2529 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2530 symbol.GetSignatureForError ());
2534 return base.AddToContainer (symbol, name);
2537 public override void VerifyMembers ()
2539 base.VerifyMembers ();
2541 if ((events != null) && Report.WarningLevel >= 3) {
2542 foreach (Event e in events){
2543 // Note: The event can be assigned from same class only, so we can report
2544 // this warning for all accessibility modes
2545 if ((e.caching_flags & Flags.IsUsed) == 0)
2546 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2551 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2553 if (a.IsValidSecurityAttribute ()) {
2554 if (declarative_security == null)
2555 declarative_security = new ListDictionary ();
2557 a.ExtractSecurityPermissionSet (declarative_security);
2561 if (a.Type == TypeManager.struct_layout_attribute_type) {
2562 PartialContainer.HasStructLayout = true;
2564 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2565 PartialContainer.HasExplicitLayout = true;
2568 base.ApplyAttributeBuilder (a, cb);
2572 /// Defines the default constructors
2574 protected void DefineDefaultConstructor (bool is_static)
2576 // The default instance constructor is public
2577 // If the class is abstract, the default constructor is protected
2578 // The default static constructor is private
2582 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2584 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2587 Constructor c = new Constructor (this, MemberName.Name, mods,
2588 null, Parameters.EmptyReadOnlyParameters,
2589 new GeneratedBaseInitializer (Location),
2593 c.Block = new ToplevelBlock (Parameters.EmptyReadOnlyParameters, Location);
2596 public override bool Define ()
2598 CheckProtectedModifier ();
2602 if (default_static_constructor != null)
2603 default_static_constructor.Define ();
2608 public override void Emit ()
2610 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2611 DefineDefaultConstructor (true);
2612 default_static_constructor.Define ();
2617 if (declarative_security != null) {
2618 foreach (DictionaryEntry de in declarative_security) {
2619 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2624 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2626 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2629 protected override TypeAttributes TypeAttr {
2631 if (default_static_constructor == null)
2632 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2634 return base.TypeAttr;
2640 // TODO: should be sealed
2641 public class Class : ClassOrStruct {
2642 const int AllowedModifiers =
2645 Modifiers.PROTECTED |
2646 Modifiers.INTERNAL |
2648 Modifiers.ABSTRACT |
2653 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2655 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2657 : base (ns, parent, name, attrs, Kind.Class)
2659 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2660 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2662 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2663 Report.FeatureIsNotAvailable (Location, "static classes");
2667 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2669 if (part.Name == "System.Object")
2670 Report.Error (537, part.Location,
2671 "The class System.Object cannot have a base class or implement an interface.");
2672 base.AddBasesForPart (part, bases);
2675 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2677 if (a.Type == TypeManager.attribute_usage_type) {
2678 if (!TypeManager.IsAttributeType (BaseType) &&
2679 TypeBuilder.FullName != "System.Attribute") {
2680 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2684 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2685 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2689 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2690 !attributes.Contains (TypeManager.guid_attr_type)) {
2691 a.Error_MissingGuidAttribute ();
2695 if (a.Type == TypeManager.extension_attribute_type) {
2696 a.Error_MisusedExtensionAttribute ();
2700 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2703 base.ApplyAttributeBuilder (a, cb);
2706 public override AttributeTargets AttributeTargets {
2708 return AttributeTargets.Class;
2712 protected override void DefineContainerMembers (MemberCoreArrayList list)
2718 base.DefineContainerMembers (list);
2722 foreach (MemberCore m in list) {
2723 if (m is Operator) {
2724 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2728 if (m is Destructor) {
2729 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2734 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2738 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2741 if (m is Constructor) {
2742 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2746 Method method = m as Method;
2747 if (method != null && method.Parameters.HasExtensionMethodType) {
2748 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2752 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2755 base.DefineContainerMembers (list);
2758 public override bool Define ()
2760 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2761 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2764 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2765 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2768 return base.Define ();
2771 protected override bool DoDefineMembers ()
2773 if (InstanceConstructors == null && !IsStatic)
2774 DefineDefaultConstructor (false);
2776 return base.DoDefineMembers ();
2779 public override void Emit ()
2784 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2785 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2789 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2791 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2793 if (base_class == null) {
2794 if (RootContext.StdLib)
2795 base_class = TypeManager.system_object_expr;
2796 else if (Name != "System.Object")
2797 base_class = TypeManager.system_object_expr;
2799 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2801 689, base_class.Location,
2802 "Cannot derive from `{0}' because it is a type parameter",
2803 base_class.GetSignatureForError ());
2807 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2808 Report.Error (698, base_class.Location,
2809 "A generic type cannot derive from `{0}' because it is an attribute class",
2810 base_class.GetSignatureForError ());
2813 if (base_class.IsSealed){
2814 Report.SymbolRelatedToPreviousError (base_class.Type);
2815 if (base_class.Type.IsAbstract) {
2816 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2817 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2819 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2820 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2825 if (!base_class.CanInheritFrom ()){
2826 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2827 GetSignatureForError (), base_class.GetSignatureForError ());
2831 if (!base_class.AsAccessible (this)) {
2832 Report.SymbolRelatedToPreviousError (base_class.Type);
2833 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2834 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2838 if (PartialContainer.IsStaticClass) {
2839 if (base_class.Type != TypeManager.object_type) {
2840 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2841 GetSignatureForError (), base_class.GetSignatureForError ());
2845 if (ifaces != null) {
2846 foreach (TypeExpr t in ifaces)
2847 Report.SymbolRelatedToPreviousError (t.Type);
2848 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2855 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2856 /// Valid only for attribute classes.
2857 public bool IsExcluded ()
2859 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2860 return (caching_flags & Flags.Excluded) != 0;
2862 caching_flags &= ~Flags.Excluded_Undetected;
2864 if (OptAttributes == null)
2867 if (TypeManager.conditional_attribute_type == null)
2870 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2875 foreach (Attribute a in attrs) {
2876 string condition = a.GetConditionalAttributeValue ();
2877 if (Location.CompilationUnit.IsConditionalDefined (condition))
2881 caching_flags |= Flags.Excluded;
2887 return (ModFlags & Modifiers.STATIC) != 0;
2892 // FIXME: How do we deal with the user specifying a different
2895 protected override TypeAttributes TypeAttr {
2897 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2899 ta |= StaticClassAttribute;
2905 public sealed class Struct : ClassOrStruct {
2907 // Modifiers allowed in a struct declaration
2909 const int AllowedModifiers =
2912 Modifiers.PROTECTED |
2913 Modifiers.INTERNAL |
2917 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2918 int mod, Attributes attrs)
2919 : base (ns, parent, name, attrs, Kind.Struct)
2923 if (parent.Parent == null)
2924 accmods = Modifiers.INTERNAL;
2926 accmods = Modifiers.PRIVATE;
2928 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2930 this.ModFlags |= Modifiers.SEALED;
2933 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2935 base.ApplyAttributeBuilder (a, cb);
2938 // When struct constains fixed fixed and struct layout has explicitly
2939 // set CharSet, its value has to be propagated to compiler generated
2940 // fixed field types
2942 if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
2943 for (int i = 0; i < Fields.Count; ++i) {
2944 FixedField ff = Fields [i] as FixedField;
2946 ff.SetCharSet (TypeBuilder.Attributes);
2951 public override AttributeTargets AttributeTargets {
2953 return AttributeTargets.Struct;
2957 public override bool IsUnmanagedType ()
2962 if (requires_delayed_unmanagedtype_check)
2965 foreach (FieldBase f in fields) {
2966 if ((f.ModFlags & Modifiers.STATIC) != 0)
2969 // It can happen when recursive unmanaged types are defined
2970 // struct S { S* s; }
2971 Type mt = f.MemberType;
2973 requires_delayed_unmanagedtype_check = true;
2977 // TODO: Remove when pointer types are under mcs control
2978 while (mt.IsPointer)
2979 mt = TypeManager.GetElementType (mt);
2980 if (TypeManager.IsEqual (mt, TypeBuilder))
2983 if (TypeManager.IsUnmanagedType (mt))
2992 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2994 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2996 // If we are compiling our runtime,
2997 // and we are defining ValueType, then our
2998 // base is `System.Object'.
3000 if (base_class == null) {
3001 if (!RootContext.StdLib && Name == "System.ValueType")
3002 base_class = TypeManager.system_object_expr;
3004 base_class = TypeManager.system_valuetype_expr;
3011 // FIXME: Allow the user to specify a different set of attributes
3012 // in some cases (Sealed for example is mandatory for a class,
3013 // but what SequentialLayout can be changed
3015 protected override TypeAttributes TypeAttr {
3017 const TypeAttributes DefaultTypeAttributes =
3018 TypeAttributes.SequentialLayout |
3019 TypeAttributes.Sealed |
3020 TypeAttributes.BeforeFieldInit;
3022 return base.TypeAttr | DefaultTypeAttributes;
3026 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3028 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3029 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3030 field.GetSignatureForError ());
3033 base.RegisterFieldForInitialization (field, expression);
3041 public sealed class Interface : TypeContainer, IMemberContainer {
3044 /// Modifiers allowed in a class declaration
3046 public const int AllowedModifiers =
3049 Modifiers.PROTECTED |
3050 Modifiers.INTERNAL |
3054 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3056 : base (ns, parent, name, attrs, Kind.Interface)
3060 if (parent.Parent == null)
3061 accmods = Modifiers.INTERNAL;
3063 accmods = Modifiers.PRIVATE;
3065 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3068 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3070 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3071 !attributes.Contains (TypeManager.guid_attr_type)) {
3072 a.Error_MissingGuidAttribute ();
3075 base.ApplyAttributeBuilder (a, cb);
3079 public override AttributeTargets AttributeTargets {
3081 return AttributeTargets.Interface;
3085 protected override TypeAttributes TypeAttr {
3087 const TypeAttributes DefaultTypeAttributes =
3088 TypeAttributes.AutoLayout |
3089 TypeAttributes.Abstract |
3090 TypeAttributes.Interface;
3092 return base.TypeAttr | DefaultTypeAttributes;
3096 protected override bool VerifyClsCompliance ()
3098 if (!base.VerifyClsCompliance ())
3101 if (ifaces != null) {
3102 foreach (Type t in ifaces) {
3103 if (AttributeTester.IsClsCompliant (t))
3106 Report.SymbolRelatedToPreviousError (t);
3107 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3108 GetSignatureForError (), TypeManager.CSharpName (t));
3116 // It is used as a base class for all property based members
3117 // This includes properties, indexers, and events
3118 public abstract class PropertyBasedMember : InterfaceMemberBase
3120 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3121 FullNamedExpression type, int mod, int allowed_mod,
3122 MemberName name, Attributes attrs)
3123 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3127 protected override bool VerifyClsCompliance ()
3129 if (!base.VerifyClsCompliance ())
3132 if (!AttributeTester.IsClsCompliant (MemberType)) {
3133 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3134 GetSignatureForError ());
3142 public abstract class MethodCore : InterfaceMemberBase
3144 public readonly Parameters Parameters;
3145 protected ToplevelBlock block;
3147 public MethodCore (DeclSpace parent, GenericMethod generic,
3148 FullNamedExpression type, int mod, int allowed_mod,
3149 MemberName name, Attributes attrs, Parameters parameters)
3150 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3152 Parameters = parameters;
3156 // Returns the System.Type array for the parameters of this method
3158 public Type [] ParameterTypes {
3160 return Parameters.Types;
3164 public Parameters ParameterInfo
3171 public ToplevelBlock Block {
3181 protected override bool CheckBase ()
3183 // Check whether arguments were correct.
3184 if (!DefineParameters (Parameters))
3187 return base.CheckBase ();
3191 // Returns a string that represents the signature for this
3192 // member which should be used in XML documentation.
3194 public override string GetDocCommentName (DeclSpace ds)
3196 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3200 // Raised (and passed an XmlElement that contains the comment)
3201 // when GenerateDocComment is writing documentation expectedly.
3203 // FIXME: with a few effort, it could be done with XmlReader,
3204 // that means removal of DOM use.
3206 internal override void OnGenerateDocComment (XmlElement el)
3208 DocUtil.OnMethodGenerateDocComment (this, el);
3212 // Represents header string for documentation comment.
3214 public override string DocCommentHeader
3216 get { return "M:"; }
3219 public override bool EnableOverloadChecks (MemberCore overload)
3221 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3222 caching_flags |= Flags.MethodOverloadsExist;
3226 return base.EnableOverloadChecks (overload);
3229 protected override bool VerifyClsCompliance ()
3231 if (!base.VerifyClsCompliance ())
3234 if (Parameters.HasArglist) {
3235 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3238 if (!AttributeTester.IsClsCompliant (MemberType)) {
3239 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3240 GetSignatureForError ());
3243 Parameters.VerifyClsCompliance ();
3249 public abstract class InterfaceMemberBase : MemberBase {
3251 // Whether this is an interface member.
3253 public bool IsInterface;
3256 // If true, this is an explicit interface implementation
3258 public bool IsExplicitImpl;
3260 protected bool is_external_implementation;
3263 // The interface type we are explicitly implementing
3265 public Type InterfaceType;
3268 // The method we're overriding if this is an override method.
3270 protected MethodInfo base_method;
3272 readonly int explicit_mod_flags;
3273 public MethodAttributes flags;
3275 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3276 FullNamedExpression type, int mod, int allowed_mod,
3277 MemberName name, Attributes attrs)
3278 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3281 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3282 IsExplicitImpl = (MemberName.Left != null);
3283 explicit_mod_flags = mod;
3286 protected override bool CheckBase ()
3288 if (!base.CheckBase ())
3291 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3292 CheckForDuplications ();
3297 // Is null for System.Object while compiling corlib and base interfaces
3298 if (Parent.PartialContainer.BaseCache == null) {
3299 if ((ModFlags & Modifiers.NEW) != 0) {
3300 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3305 Type base_ret_type = null;
3306 base_method = FindOutBaseMethod (ref base_ret_type);
3308 // method is override
3309 if (base_method != null) {
3310 if (!CheckMethodAgainstBase (base_ret_type))
3313 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3314 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3316 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3317 Report.SymbolRelatedToPreviousError (base_method);
3318 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3319 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3322 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3323 Report.SymbolRelatedToPreviousError (base_method);
3324 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3325 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3332 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3333 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3334 if (conflict_symbol != null) {
3335 Report.SymbolRelatedToPreviousError (conflict_symbol);
3337 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3338 else if (this is PropertyBase)
3339 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3341 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3343 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3344 GetSignatureForError (), SimpleName.GetMemberType (this));
3349 if (conflict_symbol == null) {
3350 if ((ModFlags & Modifiers.NEW) != 0) {
3351 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3356 if ((ModFlags & Modifiers.NEW) == 0) {
3357 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3360 Report.SymbolRelatedToPreviousError (conflict_symbol);
3361 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3362 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3368 protected virtual bool CheckForDuplications ()
3370 return Parent.MemberCache.CheckExistingMembersOverloads (
3371 this, GetFullName (MemberName), Parameters.EmptyReadOnlyParameters);
3375 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3376 // that have been defined.
3378 // `name' is the user visible name for reporting errors (this is used to
3379 // provide the right name regarding method names and properties)
3381 bool CheckMethodAgainstBase (Type base_method_type)
3385 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3386 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3387 Report.SymbolRelatedToPreviousError (base_method);
3388 Report.Error (506, Location,
3389 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3390 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3394 // Now we check that the overriden method is not final
3396 if (base_method.IsFinal) {
3397 Report.SymbolRelatedToPreviousError (base_method);
3398 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3399 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3403 // Check that the permissions are not being changed
3405 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3406 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3408 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3409 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3413 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3414 Report.SymbolRelatedToPreviousError (base_method);
3415 if (this is PropertyBasedMember) {
3416 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3417 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3420 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3421 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3427 if ((ModFlags & Modifiers.NEW) == 0) {
3428 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3429 ModFlags |= Modifiers.NEW;
3430 Report.SymbolRelatedToPreviousError (base_method);
3431 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3432 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",
3433 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3435 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3436 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3440 if (base_method.IsAbstract && !IsInterface) {
3441 Report.SymbolRelatedToPreviousError (base_method);
3442 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3443 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3451 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3453 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3455 // when overriding protected internal, the method can be declared
3456 // protected internal only within the same assembly or assembly
3457 // which has InternalsVisibleTo
3459 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3460 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3461 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3463 // if it's not "protected internal", it must be "protected"
3467 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3469 // protected within the same assembly - an error
3472 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3473 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3475 // protected ok, but other attributes differ - report an error
3481 return (thisp == base_classp);
3485 public override bool Define ()
3488 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3489 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3491 flags = MethodAttributes.Public |
3492 MethodAttributes.Abstract |
3493 MethodAttributes.HideBySig |
3494 MethodAttributes.NewSlot |
3495 MethodAttributes.Virtual;
3497 Parent.PartialContainer.MethodModifiersValid (this);
3499 flags = Modifiers.MethodAttr (ModFlags);
3502 if (IsExplicitImpl) {
3503 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3504 if (iface_texpr == null)
3507 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3508 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3509 GetSignatureForError ());
3512 InterfaceType = iface_texpr.Type;
3514 if (!InterfaceType.IsInterface) {
3515 Report.SymbolRelatedToPreviousError (InterfaceType);
3516 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3517 TypeManager.CSharpName (InterfaceType));
3519 Parent.PartialContainer.VerifyImplements (this);
3522 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3525 return base.Define ();
3528 protected bool DefineParameters (Parameters parameters)
3530 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3532 if (!parameters.Resolve (rc))
3536 for (int i = 0; i < parameters.Count; ++i) {
3537 Parameter p = parameters [i];
3538 if (p.CheckAccessibility (this))
3541 Type t = parameters.Types [i];
3542 Report.SymbolRelatedToPreviousError (t);
3543 if (this is Indexer)
3544 Report.Error (55, Location,
3545 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3546 TypeManager.CSharpName (t), GetSignatureForError ());
3547 else if (this is Operator)
3548 Report.Error (57, Location,
3549 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3550 TypeManager.CSharpName (t), GetSignatureForError ());
3552 Report.Error (51, Location,
3553 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3554 TypeManager.CSharpName (t), GetSignatureForError ());
3560 public override void Emit()
3562 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3563 // We are more strict than Microsoft and report CS0626 as error
3564 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3565 Report.Error (626, Location,
3566 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3567 GetSignatureForError ());
3573 public override bool EnableOverloadChecks (MemberCore overload)
3576 // Two members can differ in their explicit interface
3577 // type parameter only
3579 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3580 if (imb != null && imb.IsExplicitImpl) {
3581 if (IsExplicitImpl) {
3582 caching_flags |= Flags.MethodOverloadsExist;
3587 return IsExplicitImpl;
3590 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3592 Report.SymbolRelatedToPreviousError (base_method);
3593 string base_name = TypeManager.GetFullNameSignature (base_method);
3594 string this_name = GetSignatureForError ();
3595 if (suffix != null) {
3596 base_name += suffix;
3597 this_name += suffix;
3600 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3601 this_name, Modifiers.GetDescription (ma), base_name);
3604 protected static string Error722 {
3606 return "`{0}': static types cannot be used as return types";
3611 /// Gets base method and its return type
3613 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3616 // The "short" name of this property / indexer / event. This is the
3617 // name without the explicit interface.
3619 public string ShortName
3621 get { return MemberName.Name; }
3622 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3626 // Returns full metadata method name
3628 public string GetFullName (MemberName name)
3630 if (!IsExplicitImpl)
3634 // When dealing with explicit members a full interface type
3635 // name is added to member name to avoid possible name conflicts
3637 // We use CSharpName which gets us full name with benefit of
3638 // replacing predefined names which saves some space and name
3641 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3644 protected override bool VerifyClsCompliance ()
3646 if (!base.VerifyClsCompliance ()) {
3647 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3648 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3651 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3652 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3657 if (GenericMethod != null)
3658 GenericMethod.VerifyClsCompliance ();
3663 public override bool IsUsed
3665 get { return IsExplicitImpl || base.IsUsed; }
3670 public abstract class MethodOrOperator : MethodCore, IMethodData
3672 public MethodBuilder MethodBuilder;
3673 ReturnParameter return_attributes;
3674 ListDictionary declarative_security;
3675 protected MethodData MethodData;
3677 static string[] attribute_targets = new string [] { "method", "return" };
3679 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3680 int allowed_mod, MemberName name,
3681 Attributes attrs, Parameters parameters)
3682 : base (parent, generic, type, mod, allowed_mod, name,
3687 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3689 if (a.Target == AttributeTargets.ReturnValue) {
3690 if (return_attributes == null)
3691 return_attributes = new ReturnParameter (MethodBuilder, Location);
3693 return_attributes.ApplyAttributeBuilder (a, cb);
3697 if (a.IsInternalMethodImplAttribute) {
3698 is_external_implementation = true;
3701 if (a.Type == TypeManager.dllimport_type) {
3702 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3703 if ((ModFlags & extern_static) != extern_static) {
3704 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3706 is_external_implementation = true;
3709 if (a.IsValidSecurityAttribute ()) {
3710 if (declarative_security == null)
3711 declarative_security = new ListDictionary ();
3712 a.ExtractSecurityPermissionSet (declarative_security);
3716 if (MethodBuilder != null)
3717 MethodBuilder.SetCustomAttribute (cb);
3720 public override AttributeTargets AttributeTargets {
3722 return AttributeTargets.Method;
3726 protected override bool CheckForDuplications ()
3728 string name = GetFullName (MemberName);
3729 if (MemberName.IsGeneric)
3730 name = MemberName.MakeName (name, MemberName.TypeArguments);
3732 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3735 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3737 return new EmitContext (
3738 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3741 protected override bool ResolveMemberType ()
3744 if (GenericMethod != null) {
3745 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3746 if (!GenericMethod.Define (this))
3751 return base.ResolveMemberType ();
3754 public override bool Define ()
3756 if (!base.Define ())
3762 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3764 // Current method is turned into automatically generated
3765 // wrapper which creates an instance of iterator
3767 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3768 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3771 if (IsPartialDefinition) {
3772 caching_flags &= ~Flags.Excluded_Undetected;
3773 caching_flags |= Flags.Excluded;
3774 // Add to member cache only when a partial method implementation is not there
3775 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3776 MethodBase mb = new PartialMethodDefinitionInfo (this);
3777 Parent.MemberCache.AddMember (mb, this);
3778 TypeManager.AddMethod (mb, this);
3784 MethodData = new MethodData (
3785 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3787 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3790 MethodBuilder = MethodData.MethodBuilder;
3793 if (MethodBuilder.IsGenericMethod)
3794 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3797 Parent.MemberCache.AddMember (MethodBuilder, this);
3802 protected override void DoMemberTypeIndependentChecks ()
3804 base.DoMemberTypeIndependentChecks ();
3806 CheckAbstractAndExtern (block != null);
3808 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3809 for (int i = 0; i < Parameters.Count; ++i) {
3810 if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3811 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3812 GetSignatureForError ());
3819 protected override void DoMemberTypeDependentChecks ()
3821 base.DoMemberTypeDependentChecks ();
3823 if (!TypeManager.IsGenericParameter (MemberType)) {
3824 if (MemberType.IsAbstract && MemberType.IsSealed) {
3825 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3830 public override void Emit ()
3833 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3834 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3835 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3836 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3838 if (OptAttributes != null)
3839 OptAttributes.Emit ();
3841 if (declarative_security != null) {
3842 foreach (DictionaryEntry de in declarative_security) {
3843 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3850 protected void Error_ConditionalAttributeIsNotValid ()
3852 Report.Error (577, Location,
3853 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3854 GetSignatureForError ());
3857 public bool IsPartialDefinition {
3859 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3863 public bool IsPartialImplementation {
3865 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3869 public override string[] ValidAttributeTargets {
3871 return attribute_targets;
3875 #region IMethodData Members
3877 public CallingConventions CallingConventions {
3879 CallingConventions cc = Parameters.CallingConvention;
3881 if ((ModFlags & Modifiers.STATIC) == 0)
3882 cc |= CallingConventions.HasThis;
3884 // FIXME: How is `ExplicitThis' used in C#?
3890 public Type ReturnType {
3896 public MemberName MethodName {
3902 protected override bool CheckBase ()
3904 if (!base.CheckBase ())
3907 // TODO: Destructor should derive from MethodCore
3908 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3909 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3910 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3918 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3920 public bool IsExcluded () {
3921 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3922 return (caching_flags & Flags.Excluded) != 0;
3924 caching_flags &= ~Flags.Excluded_Undetected;
3926 if (base_method == null) {
3927 if (OptAttributes == null)
3930 if (TypeManager.conditional_attribute_type == null)
3933 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3938 foreach (Attribute a in attrs) {
3939 string condition = a.GetConditionalAttributeValue ();
3940 if (condition == null)
3943 if (Location.CompilationUnit.IsConditionalDefined (condition))
3947 caching_flags |= Flags.Excluded;
3951 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3953 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3954 caching_flags |= Flags.Excluded;
3960 if (md.IsExcluded ()) {
3961 caching_flags |= Flags.Excluded;
3967 GenericMethod IMethodData.GenericMethod {
3969 return GenericMethod;
3973 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3980 public class SourceMethod : IMethodDef
3983 SourceMethodBuilder builder;
3985 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3987 this.method = method;
3989 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3992 public string Name {
3993 get { return method.Name; }
3998 if (method is MethodBuilder)
3999 return ((MethodBuilder) method).GetToken ().Token;
4000 else if (method is ConstructorBuilder)
4001 return ((ConstructorBuilder) method).GetToken ().Token;
4003 throw new NotSupportedException ();
4007 public void CloseMethod ()
4009 SymbolWriter.CloseMethod ();
4012 public void SetRealMethodName (string name)
4014 if (builder != null)
4015 builder.SetRealMethodName (name);
4018 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4020 if (!SymbolWriter.HasSymbolWriter)
4025 Location start_loc = block.StartLocation;
4026 if (start_loc.IsNull)
4029 ICompileUnit compile_unit = start_loc.CompilationUnit;
4030 if (compile_unit == null)
4033 return new SourceMethod (parent, method, compile_unit);
4037 public class Method : MethodOrOperator {
4040 /// Modifiers allowed in a class declaration
4042 const int AllowedModifiers =
4045 Modifiers.PROTECTED |
4046 Modifiers.INTERNAL |
4051 Modifiers.OVERRIDE |
4052 Modifiers.ABSTRACT |
4056 const int AllowedInterfaceModifiers =
4057 Modifiers.NEW | Modifiers.UNSAFE;
4059 public Method (DeclSpace parent, GenericMethod generic,
4060 FullNamedExpression return_type, int mod,
4061 MemberName name, Parameters parameters, Attributes attrs)
4062 : base (parent, generic, return_type, mod,
4063 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4064 name, attrs, parameters)
4068 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4069 MemberName name, Parameters parameters, Attributes attrs)
4070 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4074 public override string GetSignatureForError()
4076 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4079 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4081 Report.Error (17, location,
4082 "Program `{0}' has more than one entry point defined: `{1}'",
4083 CodeGen.FileName, TypeManager.CSharpSignature(b));
4086 bool IsEntryPoint ()
4088 if (ReturnType != TypeManager.void_type &&
4089 ReturnType != TypeManager.int32_type)
4092 if (Parameters.Count == 0)
4095 if (Parameters.Count > 1)
4098 Type t = Parameters.Types [0];
4099 return t.IsArray && t.GetArrayRank () == 1 &&
4100 TypeManager.GetElementType (t) == TypeManager.string_type &&
4101 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4104 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4106 if (a.Type == TypeManager.conditional_attribute_type) {
4107 if (IsExplicitImpl) {
4108 Error_ConditionalAttributeIsNotValid ();
4112 if (ReturnType != TypeManager.void_type) {
4113 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4117 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4118 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4123 Report.Error (582, Location, "Conditional not valid on interface members");
4127 if (MethodData.implementing != null) {
4128 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4129 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4130 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4134 for (int i = 0; i < Parameters.Count; ++i) {
4135 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4136 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4142 if (a.Type == TypeManager.extension_attribute_type) {
4143 a.Error_MisusedExtensionAttribute ();
4147 base.ApplyAttributeBuilder (a, cb);
4150 protected override bool CheckForDuplications ()
4152 if (!base.CheckForDuplications ())
4155 ArrayList ar = Parent.PartialContainer.Properties;
4157 for (int i = 0; i < ar.Count; ++i) {
4158 PropertyBase pb = (PropertyBase) ar [i];
4159 if (pb.AreAccessorsDuplicateImplementation (this))
4164 ar = Parent.PartialContainer.Indexers;
4166 for (int i = 0; i < ar.Count; ++i) {
4167 PropertyBase pb = (PropertyBase) ar [i];
4168 if (pb.AreAccessorsDuplicateImplementation (this))
4179 public override bool Define ()
4181 if (!base.Define ())
4184 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4185 Error1599 (Location, ReturnType);
4189 if (ReturnType == TypeManager.void_type && Parameters.Count == 0 &&
4190 Name == "Finalize" && !(this is Destructor)) {
4191 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4194 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4195 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4196 Parent.PartialContainer.Mark_HasEquals ();
4197 else if (Parameters.IsEmpty && Name == "GetHashCode")
4198 Parent.PartialContainer.Mark_HasGetHashCode ();
4201 if ((ModFlags & Modifiers.STATIC) == 0)
4204 if (Parameters.HasExtensionMethodType) {
4205 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4206 if (!Parent.IsTopLevel)
4207 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4208 GetSignatureForError ());
4210 if (TypeManager.extension_attribute_type == null) {
4211 Report.Error (1110, Location,
4212 "`{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",
4213 GetSignatureForError ());
4214 } else if (TypeManager.extension_attribute_attr == null) {
4215 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4216 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4219 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4222 ModFlags |= Modifiers.METHOD_EXTENSION;
4223 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4224 CodeGen.Assembly.HasExtensionMethods = true;
4226 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4227 GetSignatureForError ());
4232 // This is used to track the Entry Point,
4234 if (RootContext.NeedsEntryPoint &&
4236 (RootContext.MainClass == null ||
4237 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4238 if (IsEntryPoint ()) {
4240 if (RootContext.EntryPoint == null) {
4241 if (Parent.IsGeneric || MemberName.IsGeneric) {
4242 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4243 GetSignatureForError ());
4245 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4246 md.SetMemberIsUsed ();
4248 RootContext.EntryPoint = MethodBuilder;
4249 RootContext.EntryPointLocation = Location;
4252 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4253 Error_DuplicateEntryPoint (MethodBuilder, Location);
4256 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4257 GetSignatureForError ());
4267 public override void Emit ()
4270 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4271 if (IsPartialDefinition) {
4273 // Do attribute checks only when partial implementation does not exist
4275 if (MethodBuilder == null)
4281 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4282 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4283 GetSignatureForError ());
4285 MethodData.Emit (Parent);
4289 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4290 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4296 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4297 Location, MethodBuilder);
4302 public override bool EnableOverloadChecks (MemberCore overload)
4304 // TODO: It can be deleted when members will be defined in correct order
4305 if (overload is Operator)
4306 return overload.EnableOverloadChecks (this);
4308 if (overload is Indexer)
4311 return base.EnableOverloadChecks (overload);
4314 public static void Error1599 (Location loc, Type t)
4316 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4319 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4321 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4322 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4327 if (mi.IsSpecialName)
4330 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4334 public void SetPartialDefinition (Method methodDefinition)
4336 caching_flags |= Flags.PartialDefinitionExists;
4337 methodDefinition.MethodBuilder = MethodBuilder;
4338 if (methodDefinition.attributes == null)
4341 if (attributes == null) {
4342 attributes = methodDefinition.attributes;
4344 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4348 protected override bool VerifyClsCompliance ()
4350 if (!base.VerifyClsCompliance ())
4353 if (ParameterInfo.Count > 0) {
4354 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4356 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4363 public abstract class ConstructorInitializer : ExpressionStatement
4365 ArrayList argument_list;
4366 MethodGroupExpr base_constructor_group;
4368 public ConstructorInitializer (ArrayList argument_list, Location loc)
4370 this.argument_list = argument_list;
4374 public ArrayList Arguments {
4376 return argument_list;
4380 public override Expression CreateExpressionTree (EmitContext ec)
4382 throw new NotSupportedException ("ET");
4385 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4387 if (argument_list != null){
4388 foreach (Argument a in argument_list){
4389 if (!a.Resolve (ec, loc))
4394 if (this is ConstructorBaseInitializer) {
4395 if (ec.ContainerType.BaseType == null)
4398 type = ec.ContainerType.BaseType;
4399 if (ec.ContainerType.IsValueType) {
4400 Report.Error (522, loc,
4401 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4406 // It is legal to have "this" initializers that take no arguments
4407 // in structs, they are just no-ops.
4409 // struct D { public D (int a) : this () {}
4411 if (ec.ContainerType.IsValueType && argument_list == null)
4414 type = ec.ContainerType;
4417 base_constructor_group = MemberLookupFinal (
4418 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4419 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4420 loc) as MethodGroupExpr;
4422 if (base_constructor_group == null)
4425 base_constructor_group = base_constructor_group.OverloadResolve (
4426 ec, ref argument_list, false, loc);
4428 if (base_constructor_group == null)
4431 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4433 if (base_ctor == caller_builder){
4434 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4440 public override Expression DoResolve (EmitContext ec)
4442 throw new NotSupportedException ();
4445 public override void Emit (EmitContext ec)
4447 // It can be null for static initializers
4448 if (base_constructor_group == null)
4453 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4455 base_constructor_group.EmitCall (ec, argument_list);
4458 public override void EmitStatement (EmitContext ec)
4464 public class ConstructorBaseInitializer : ConstructorInitializer {
4465 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4466 base (argument_list, l)
4471 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4472 public GeneratedBaseInitializer (Location loc):
4478 public class ConstructorThisInitializer : ConstructorInitializer {
4479 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4480 base (argument_list, l)
4485 public class Constructor : MethodCore, IMethodData {
4486 public ConstructorBuilder ConstructorBuilder;
4487 public ConstructorInitializer Initializer;
4488 ListDictionary declarative_security;
4489 bool has_compliant_args;
4492 // Modifiers allowed for a constructor.
4494 public const int AllowedModifiers =
4496 Modifiers.PROTECTED |
4497 Modifiers.INTERNAL |
4503 static readonly string[] attribute_targets = new string [] { "method" };
4506 // The spec claims that static is not permitted, but
4507 // my very own code has static constructors.
4509 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, Parameters args,
4510 ConstructorInitializer init, Location loc)
4511 : base (parent, null, null, mod, AllowedModifiers,
4512 new MemberName (name, loc), attrs, args)
4517 public bool HasCompliantArgs {
4518 get { return has_compliant_args; }
4521 public override AttributeTargets AttributeTargets {
4522 get { return AttributeTargets.Constructor; }
4526 // Returns true if this is a default constructor
4528 public bool IsDefault ()
4530 if ((ModFlags & Modifiers.STATIC) != 0)
4531 return Parameters.IsEmpty;
4533 return Parameters.IsEmpty &&
4534 (Initializer is ConstructorBaseInitializer) &&
4535 (Initializer.Arguments == null);
4538 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4540 if (a.IsValidSecurityAttribute ()) {
4541 if (declarative_security == null) {
4542 declarative_security = new ListDictionary ();
4544 a.ExtractSecurityPermissionSet (declarative_security);
4548 if (a.IsInternalMethodImplAttribute) {
4549 is_external_implementation = true;
4552 ConstructorBuilder.SetCustomAttribute (cb);
4555 protected override bool CheckBase ()
4557 if ((ModFlags & Modifiers.STATIC) != 0) {
4558 if (!Parameters.IsEmpty) {
4559 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4560 GetSignatureForError ());
4564 // the rest can be ignored
4568 // Check whether arguments were correct.
4569 if (!DefineParameters (Parameters))
4572 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4573 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4576 if (Parent.PartialContainer.Kind == Kind.Struct) {
4577 if (Parameters.Count == 0) {
4578 Report.Error (568, Location,
4579 "Structs cannot contain explicit parameterless constructors");
4584 CheckProtectedModifier ();
4590 // Creates the ConstructorBuilder
4592 public override bool Define ()
4594 if (ConstructorBuilder != null)
4597 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4598 MethodAttributes.SpecialName);
4600 if ((ModFlags & Modifiers.STATIC) != 0) {
4601 ca |= MethodAttributes.Static | MethodAttributes.Private;
4603 ca |= MethodAttributes.HideBySig;
4605 if ((ModFlags & Modifiers.PUBLIC) != 0)
4606 ca |= MethodAttributes.Public;
4607 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4608 if ((ModFlags & Modifiers.INTERNAL) != 0)
4609 ca |= MethodAttributes.FamORAssem;
4611 ca |= MethodAttributes.Family;
4612 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4613 ca |= MethodAttributes.Assembly;
4615 ca |= MethodAttributes.Private;
4618 if (!CheckAbstractAndExtern (block != null))
4621 // Check if arguments were correct.
4625 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4626 ca, CallingConventions,
4627 Parameters.GetEmitTypes ());
4629 if (Parent.PartialContainer.IsComImport) {
4630 if (!IsDefault ()) {
4631 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4632 Parent.GetSignatureForError ());
4634 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4637 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4638 TypeManager.AddMethod (ConstructorBuilder, this);
4640 // It's here only to report an error
4641 if (block != null && block.IsIterator) {
4642 member_type = TypeManager.void_type;
4643 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4652 public override void Emit ()
4654 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4655 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4657 if (OptAttributes != null)
4658 OptAttributes.Emit ();
4662 EmitContext ec = CreateEmitContext (null, null);
4665 // If we use a "this (...)" constructor initializer, then
4666 // do not emit field initializers, they are initialized in the other constructor
4668 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4669 !(Initializer is ConstructorThisInitializer);
4671 if (emit_field_initializers)
4672 Parent.PartialContainer.ResolveFieldInitializers (ec);
4674 if (block != null) {
4675 // If this is a non-static `struct' constructor and doesn't have any
4676 // initializer, it must initialize all of the struct's fields.
4677 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4678 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4679 block.AddThisVariable (Parent, Location);
4681 if (!block.ResolveMeta (ec, ParameterInfo))
4684 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4685 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4686 Initializer = new GeneratedBaseInitializer (Location);
4689 // Spec mandates that Initializers will not have `this' access
4691 if (Initializer != null) {
4693 Initializer.Resolve (ConstructorBuilder, ec);
4694 ec.IsStatic = false;
4695 block.AddScopeStatement (new StatementExpression (Initializer));
4700 Parameters.ApplyAttributes (ConstructorBuilder);
4702 SourceMethod source = null;
4704 ec.OmitDebuggingInfo = true;
4706 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4708 bool unreachable = false;
4709 if (block != null) {
4710 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4713 ec.EmitMeta (block);
4715 if (Report.Errors > 0)
4718 ec.EmitResolvedTopBlock (block, unreachable);
4722 source.CloseMethod ();
4724 if (declarative_security != null) {
4725 foreach (DictionaryEntry de in declarative_security) {
4726 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4733 // Is never override
4734 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4739 public override string GetSignatureForError()
4741 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4744 public override string[] ValidAttributeTargets {
4746 return attribute_targets;
4750 protected override bool VerifyClsCompliance ()
4752 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4756 if (ParameterInfo.Count > 0) {
4757 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4759 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4761 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4762 foreach (Type param in Parameters.Types) {
4763 if (param.IsArray) {
4769 has_compliant_args = true;
4773 #region IMethodData Members
4775 public System.Reflection.CallingConventions CallingConventions {
4777 CallingConventions cc = Parameters.CallingConvention;
4779 if (Parent.PartialContainer.Kind == Kind.Class)
4780 if ((ModFlags & Modifiers.STATIC) == 0)
4781 cc |= CallingConventions.HasThis;
4783 // FIXME: How is `ExplicitThis' used in C#?
4789 public MemberName MethodName {
4795 public Type ReturnType {
4801 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4803 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4804 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4805 ec.CurrentBlock = block;
4809 public bool IsExcluded()
4814 GenericMethod IMethodData.GenericMethod {
4820 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4827 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4829 public interface IMethodData
4831 CallingConventions CallingConventions { get; }
4832 Location Location { get; }
4833 MemberName MethodName { get; }
4834 Type ReturnType { get; }
4835 GenericMethod GenericMethod { get; }
4836 Parameters ParameterInfo { get; }
4838 Attributes OptAttributes { get; }
4839 ToplevelBlock Block { get; set; }
4841 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4842 ObsoleteAttribute GetObsoleteAttribute ();
4843 string GetSignatureForError ();
4845 bool IsClsComplianceRequired ();
4846 void SetMemberIsUsed ();
4847 void EmitExtraSymbolInfo (SourceMethod source);
4851 // Encapsulates most of the Method's state
4853 public class MethodData {
4855 static FieldInfo methodbuilder_attrs_field;
4857 public readonly IMethodData method;
4859 public readonly GenericMethod GenericMethod;
4862 // Are we implementing an interface ?
4864 public MethodInfo implementing;
4869 protected InterfaceMemberBase member;
4870 protected int modifiers;
4871 protected MethodAttributes flags;
4872 protected Type declaring_type;
4873 protected MethodInfo parent_method;
4875 MethodBuilder builder = null;
4876 public MethodBuilder MethodBuilder {
4882 public Type DeclaringType {
4884 return declaring_type;
4888 public MethodData (InterfaceMemberBase member,
4889 int modifiers, MethodAttributes flags, IMethodData method)
4891 this.member = member;
4892 this.modifiers = modifiers;
4895 this.method = method;
4898 public MethodData (InterfaceMemberBase member,
4899 int modifiers, MethodAttributes flags,
4900 IMethodData method, MethodBuilder builder,
4901 GenericMethod generic, MethodInfo parent_method)
4902 : this (member, modifiers, flags, method)
4904 this.builder = builder;
4905 this.GenericMethod = generic;
4906 this.parent_method = parent_method;
4909 public bool Define (DeclSpace parent, string method_full_name)
4911 string name = method.MethodName.Basename;
4913 TypeContainer container = parent.PartialContainer;
4915 PendingImplementation pending = container.PendingImplementations;
4916 if (pending != null){
4917 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4919 if (member.InterfaceType != null){
4920 if (implementing == null){
4921 if (member is PropertyBase) {
4922 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4923 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4924 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4927 Report.Error (539, method.Location,
4928 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4929 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4933 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4934 Report.SymbolRelatedToPreviousError (implementing);
4935 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4936 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4940 if (implementing != null) {
4941 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4942 if (prop_method == null) {
4943 if (TypeManager.IsSpecialMethod (implementing)) {
4944 Report.SymbolRelatedToPreviousError (implementing);
4945 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4946 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4947 implementing.Name.StartsWith ("get_") ? "get" : "set");
4949 } else if (implementing.DeclaringType.IsInterface) {
4950 if (!implementing.IsSpecialName) {
4951 Report.SymbolRelatedToPreviousError (implementing);
4952 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4953 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4956 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4957 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4958 Report.SymbolRelatedToPreviousError (implementing);
4959 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4960 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4969 // For implicit implementations, make sure we are public, for
4970 // explicit implementations, make sure we are private.
4972 if (implementing != null){
4974 // Setting null inside this block will trigger a more
4975 // verbose error reporting for missing interface implementations
4977 // The "candidate" function has been flagged already
4978 // but it wont get cleared
4980 if (member.IsExplicitImpl){
4981 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4982 Report.SymbolRelatedToPreviousError (implementing);
4983 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4984 method.GetSignatureForError ());
4988 if (implementing.DeclaringType.IsInterface) {
4990 // If this is an interface method implementation,
4991 // check for public accessibility
4993 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4995 implementing = null;
4997 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4998 // We may never be private.
4999 implementing = null;
5001 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5003 // We may be protected if we're overriding something.
5005 implementing = null;
5010 // Static is not allowed
5012 if ((modifiers & Modifiers.STATIC) != 0){
5013 implementing = null;
5018 // If implementing is still valid, set flags
5020 if (implementing != null){
5022 // When implementing interface methods, set NewSlot
5023 // unless, we are overwriting a method.
5025 if (implementing.DeclaringType.IsInterface){
5026 if ((modifiers & Modifiers.OVERRIDE) == 0)
5027 flags |= MethodAttributes.NewSlot;
5030 MethodAttributes.Virtual |
5031 MethodAttributes.HideBySig;
5033 // Set Final unless we're virtual, abstract or already overriding a method.
5034 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5035 flags |= MethodAttributes.Final;
5038 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5040 if (builder == null)
5043 if (container.CurrentType != null)
5044 declaring_type = container.CurrentType;
5046 declaring_type = container.TypeBuilder;
5048 if (implementing != null && member.IsExplicitImpl) {
5049 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5052 TypeManager.AddMethod (builder, method);
5054 if (GenericMethod != null) {
5055 bool is_override = member.IsExplicitImpl |
5056 ((modifiers & Modifiers.OVERRIDE) != 0);
5058 if (implementing != null)
5059 parent_method = implementing;
5061 EmitContext ec = method.CreateEmitContext (container, null);
5062 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5071 /// Create the MethodBuilder for the method
5073 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5075 if (builder == null) {
5076 builder = container.TypeBuilder.DefineMethod (
5077 method_name, flags, method.CallingConventions,
5078 method.ReturnType, param.GetEmitTypes ());
5084 // Generic method has been already defined to resolve method parameters
5085 // correctly when they use type parameters
5087 builder.SetParameters (param.GetEmitTypes ());
5088 builder.SetReturnType (method.ReturnType);
5090 if (builder.Attributes != flags) {
5092 if (methodbuilder_attrs_field == null)
5093 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5094 methodbuilder_attrs_field.SetValue (builder, flags);
5096 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5100 throw new InternalErrorException ();
5107 public void Emit (DeclSpace parent)
5109 ToplevelBlock block = method.Block;
5113 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5115 ec = method.CreateEmitContext (parent, null);
5117 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5119 if (GenericMethod != null)
5120 GenericMethod.EmitAttributes ();
5123 // clear the pending implementation flag
5125 if (implementing != null)
5126 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5127 member.InterfaceType, this, member.IsExplicitImpl);
5129 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5132 // Handle destructors specially
5134 // FIXME: This code generates buggy code
5136 if (member is Destructor)
5137 EmitDestructor (ec, block);
5139 ec.EmitTopBlock (method, block);
5141 if (source != null) {
5142 method.EmitExtraSymbolInfo (source);
5143 source.CloseMethod ();
5147 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5149 ILGenerator ig = ec.ig;
5151 Label finish = ig.DefineLabel ();
5153 block.SetDestructor ();
5155 ig.BeginExceptionBlock ();
5156 ec.ReturnLabel = finish;
5157 ec.HasReturnLabel = true;
5158 ec.EmitTopBlock (method, block);
5160 // ig.MarkLabel (finish);
5161 ig.BeginFinallyBlock ();
5163 if (ec.ContainerType.BaseType != null) {
5164 Expression member_lookup = Expression.MemberLookup (
5165 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5166 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5168 if (member_lookup != null){
5169 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5171 ig.Emit (OpCodes.Ldarg_0);
5172 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5176 ig.EndExceptionBlock ();
5177 //ig.MarkLabel (ec.ReturnLabel);
5178 ig.Emit (OpCodes.Ret);
5182 // TODO: Should derive from MethodCore
5183 public class Destructor : Method
5185 const int AllowedModifiers =
5189 static string[] attribute_targets = new string [] { "method" };
5191 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5192 string name, Parameters parameters, Attributes attrs,
5194 : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
5197 ModFlags &= ~Modifiers.PRIVATE;
5198 if (!RootContext.StdLib && parent.Name == "System.Object")
5199 ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
5201 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
5204 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5206 if (a.Type == TypeManager.conditional_attribute_type) {
5207 Error_ConditionalAttributeIsNotValid ();
5211 base.ApplyAttributeBuilder (a, cb);
5214 public override string GetSignatureForError ()
5216 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5219 public override string[] ValidAttributeTargets {
5221 return attribute_targets;
5226 public abstract class MemberBase : MemberCore
5228 protected FullNamedExpression type_name;
5229 protected Type member_type;
5231 public readonly DeclSpace ds;
5232 public readonly GenericMethod GenericMethod;
5234 protected MemberBase (DeclSpace parent, GenericMethod generic,
5235 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5236 MemberName name, Attributes attrs)
5237 : base (parent, name, attrs)
5239 this.ds = generic != null ? generic : (DeclSpace) parent;
5240 this.type_name = type;
5241 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5242 GenericMethod = generic;
5243 if (GenericMethod != null)
5244 GenericMethod.ModFlags = ModFlags;
5248 // Main member define entry
5250 public override bool Define ()
5252 DoMemberTypeIndependentChecks ();
5255 // Returns false only when type resolution failed
5257 if (!ResolveMemberType ())
5260 DoMemberTypeDependentChecks ();
5265 // Any type_name independent checks
5267 protected virtual void DoMemberTypeIndependentChecks ()
5269 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5270 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5271 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5272 GetSignatureForError (), Parent.GetSignatureForError ());
5277 // Any type_name dependent checks
5279 protected virtual void DoMemberTypeDependentChecks ()
5281 // verify accessibility
5282 if (!IsAccessibleAs (MemberType)) {
5283 Report.SymbolRelatedToPreviousError (MemberType);
5284 if (this is Property)
5285 Report.Error (53, Location,
5286 "Inconsistent accessibility: property type `" +
5287 TypeManager.CSharpName (MemberType) + "' is less " +
5288 "accessible than property `" + GetSignatureForError () + "'");
5289 else if (this is Indexer)
5290 Report.Error (54, Location,
5291 "Inconsistent accessibility: indexer return type `" +
5292 TypeManager.CSharpName (MemberType) + "' is less " +
5293 "accessible than indexer `" + GetSignatureForError () + "'");
5294 else if (this is MethodCore) {
5295 if (this is Operator)
5296 Report.Error (56, Location,
5297 "Inconsistent accessibility: return type `" +
5298 TypeManager.CSharpName (MemberType) + "' is less " +
5299 "accessible than operator `" + GetSignatureForError () + "'");
5301 Report.Error (50, Location,
5302 "Inconsistent accessibility: return type `" +
5303 TypeManager.CSharpName (MemberType) + "' is less " +
5304 "accessible than method `" + GetSignatureForError () + "'");
5306 Report.Error (52, Location,
5307 "Inconsistent accessibility: field type `" +
5308 TypeManager.CSharpName (MemberType) + "' is less " +
5309 "accessible than field `" + GetSignatureForError () + "'");
5314 protected bool IsTypePermitted ()
5316 if (TypeManager.IsSpecialType (MemberType)) {
5317 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5323 protected virtual bool CheckBase ()
5325 CheckProtectedModifier ();
5330 public Type MemberType {
5331 get { return member_type; }
5334 protected virtual bool ResolveMemberType ()
5336 if (member_type != null)
5337 throw new InternalErrorException ("Multi-resolve");
5339 IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5340 TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5345 // Replace original type name, error reporting can use fully resolved name
5349 member_type = te.Type;
5355 // Abstract class for all fields
5357 abstract public class FieldBase : MemberBase {
5358 public FieldBuilder FieldBuilder;
5359 public Status status;
5360 protected Expression initializer;
5363 public enum Status : byte {
5364 HAS_OFFSET = 4 // Used by FieldMember.
5367 static readonly string[] attribute_targets = new string [] { "field" };
5369 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5370 int allowed_mod, MemberName name, Attributes attrs)
5371 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5374 if ((mod & Modifiers.ABSTRACT) != 0)
5375 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5378 public override AttributeTargets AttributeTargets {
5380 return AttributeTargets.Field;
5384 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5386 if (a.Type == TypeManager.field_offset_attribute_type) {
5387 status |= Status.HAS_OFFSET;
5389 if (!Parent.PartialContainer.HasExplicitLayout) {
5390 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5394 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5395 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5401 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5402 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5408 if (a.Type == TypeManager.marshal_as_attr_type) {
5409 UnmanagedMarshal marshal = a.GetMarshal (this);
5410 if (marshal != null) {
5411 FieldBuilder.SetMarshal (marshal);
5416 if ((a.HasSecurityAttribute)) {
5417 a.Error_InvalidSecurityParent ();
5421 FieldBuilder.SetCustomAttribute (cb);
5424 protected override bool CheckBase ()
5426 if (!base.CheckBase ())
5429 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5430 if (conflict_symbol == null) {
5431 if ((ModFlags & Modifiers.NEW) != 0) {
5432 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5437 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5438 Report.SymbolRelatedToPreviousError (conflict_symbol);
5439 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5440 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5446 protected override void DoMemberTypeDependentChecks ()
5448 base.DoMemberTypeDependentChecks ();
5450 if (TypeManager.IsGenericParameter (MemberType))
5453 if (MemberType.IsSealed && MemberType.IsAbstract) {
5454 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5462 // Represents header string for documentation comment.
5464 public override string DocCommentHeader {
5465 get { return "F:"; }
5468 public override void Emit ()
5471 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5472 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5475 if (OptAttributes != null) {
5476 OptAttributes.Emit ();
5479 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5480 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5486 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5488 Report.SymbolRelatedToPreviousError (static_class);
5489 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5493 public Expression Initializer {
5495 if (value != null) {
5496 this.initializer = value;
5501 protected virtual bool IsFieldClsCompliant {
5503 if (FieldBuilder == null)
5506 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5510 public override string[] ValidAttributeTargets
5513 return attribute_targets;
5517 protected override bool VerifyClsCompliance ()
5519 if (!base.VerifyClsCompliance ())
5522 if (!IsFieldClsCompliant) {
5523 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5524 GetSignatureForError ());
5529 public void SetAssigned ()
5531 caching_flags |= Flags.IsAssigned;
5535 interface IFixedBuffer
5537 FieldInfo Element { get; }
5538 Type ElementType { get; }
5541 public class FixedFieldExternal: IFixedBuffer
5543 FieldInfo element_field;
5545 public FixedFieldExternal (FieldInfo fi)
5547 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5550 #region IFixedField Members
5552 public FieldInfo Element {
5554 return element_field;
5558 public Type ElementType {
5560 return element_field.FieldType;
5568 /// Fixed buffer implementation
5570 public class FixedField : FieldBase, IFixedBuffer
5572 public const string FixedElementName = "FixedElementField";
5573 static int GlobalCounter = 0;
5574 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5575 static FieldInfo[] fi;
5577 TypeBuilder fixed_buffer_type;
5578 FieldBuilder element;
5579 Expression size_expr;
5581 const int AllowedModifiers =
5584 Modifiers.PROTECTED |
5585 Modifiers.INTERNAL |
5588 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5589 Expression size_expr, Attributes attrs, Location loc):
5590 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5592 if (RootContext.Version < LanguageVersion.ISO_2)
5593 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5595 this.size_expr = size_expr;
5598 public override bool Define()
5600 if (!base.Define ())
5603 if (!TypeManager.IsPrimitiveType (MemberType)) {
5604 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",
5605 GetSignatureForError ());
5608 // Create nested fixed buffer container
5609 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5610 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5611 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5613 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5614 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5616 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5617 Parent.MemberCache.AddMember (FieldBuilder, this);
5618 TypeManager.RegisterFieldBase (FieldBuilder, this);
5623 protected override void DoMemberTypeIndependentChecks ()
5625 base.DoMemberTypeIndependentChecks ();
5627 if (!Parent.IsInUnsafeScope)
5628 Expression.UnsafeError (Location);
5630 if (Parent.PartialContainer.Kind != Kind.Struct) {
5631 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5632 GetSignatureForError ());
5636 public override void Emit()
5638 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5639 Constant c = size_expr.ResolveAsConstant (ec, this);
5643 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5644 if (buffer_size_const == null)
5647 int buffer_size = buffer_size_const.Value;
5649 if (buffer_size <= 0) {
5650 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5654 int type_size = Expression.GetTypeSize (MemberType);
5656 if (buffer_size > int.MaxValue / type_size) {
5657 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5658 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5662 buffer_size *= type_size;
5663 EmitFieldSize (buffer_size);
5667 // Emit compiler generated fixed buffer type attribute
5669 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5671 Type attr_type = TypeManager.CoreLookupType (
5672 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5674 if (attr_type != null) {
5675 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5677 cab = new CustomAttributeBuilder (ci, new object [0]);
5678 TypeManager.unsafe_value_type_attr = cab;
5684 fixed_buffer_type.SetCustomAttribute (cab);
5689 void EmitFieldSize (int buffer_size)
5691 if (TypeManager.struct_layout_attribute_type == null) {
5692 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5693 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5695 if (TypeManager.struct_layout_attribute_type == null)
5700 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5702 object [] fi_val = new object [] { buffer_size };
5704 if (TypeManager.struct_layout_attribute_ctor == null) {
5705 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5706 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5707 if (TypeManager.struct_layout_attribute_ctor == null)
5711 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5712 ctor_args, fi, fi_val);
5713 fixed_buffer_type.SetCustomAttribute (cab);
5716 // Don't emit FixedBufferAttribute attribute for private types
5718 if ((ModFlags & Modifiers.PRIVATE) != 0)
5721 if (TypeManager.fixed_buffer_attr_ctor == null) {
5722 if (TypeManager.fixed_buffer_attr_type == null) {
5723 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5724 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5726 if (TypeManager.fixed_buffer_attr_type == null)
5730 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5731 Location, TypeManager.type_type, TypeManager.int32_type);
5733 if (TypeManager.fixed_buffer_attr_ctor == null)
5737 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5738 FieldBuilder.SetCustomAttribute (cab);
5741 protected override bool IsFieldClsCompliant {
5747 public void SetCharSet (TypeAttributes ta)
5749 TypeAttributes cta = fixed_buffer_type.Attributes;
5750 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5751 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5752 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5753 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5754 else if (cta == 0 && ta != 0)
5755 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5758 void SetTypeBuilderCharSet (TypeAttributes ta)
5760 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5762 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5764 mi.Invoke (fixed_buffer_type, new object [] { ta });
5768 #region IFixedField Members
5770 public FieldInfo Element {
5776 public Type ElementType {
5786 // The Field class is used to represents class/struct fields during parsing.
5788 public class Field : FieldBase {
5790 // Modifiers allowed in a class declaration
5792 const int AllowedModifiers =
5795 Modifiers.PROTECTED |
5796 Modifiers.INTERNAL |
5799 Modifiers.VOLATILE |
5803 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5805 : base (parent, type, mod, AllowedModifiers, name, attrs)
5809 bool CanBeVolatile ()
5811 if (TypeManager.IsReferenceType (MemberType))
5814 if (MemberType.IsEnum)
5817 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5818 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5819 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5820 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5821 MemberType == TypeManager.float_type)
5827 bool CheckStructLayout (Type type, bool isStatic)
5829 if (TypeManager.IsBuiltinType (type))
5833 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5837 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5838 if (!TypeManager.IsGenericType (type))
5841 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5842 if (!CheckStructLayout (t, false))
5848 Report.Error (523, Location,
5849 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5850 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5854 public override bool Define ()
5856 if (!base.Define ())
5861 Type[] required_modifier = null;
5862 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5863 if (TypeManager.isvolatile_type == null)
5864 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5865 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5867 if (TypeManager.isvolatile_type != null)
5868 required_modifier = new Type [] { TypeManager.isvolatile_type };
5871 FieldBuilder = Parent.TypeBuilder.DefineField (
5872 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5874 FieldBuilder = Parent.TypeBuilder.DefineField (
5875 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5877 Parent.MemberCache.AddMember (FieldBuilder, this);
5878 TypeManager.RegisterFieldBase (FieldBuilder, this);
5880 catch (ArgumentException) {
5881 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5885 if (initializer != null) {
5886 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5887 new FieldInitializer (FieldBuilder, initializer, this));
5889 if (Parent.PartialContainer.Kind == Kind.Struct)
5890 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5896 protected override void DoMemberTypeDependentChecks ()
5898 base.DoMemberTypeDependentChecks ();
5900 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5901 if (!CanBeVolatile ()) {
5902 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5903 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5906 if ((ModFlags & Modifiers.READONLY) != 0) {
5907 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5908 GetSignatureForError ());
5913 public override string GetSignatureForError ()
5915 string s = base.GetSignatureForError ();
5916 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5919 // Undecorate name mangling
5920 int l = s.LastIndexOf ('>');
5921 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5924 protected override bool VerifyClsCompliance ()
5926 if (!base.VerifyClsCompliance ())
5929 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5930 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5938 // `set' and `get' accessors are represented with an Accessor.
5940 public class Accessor {
5942 // Null if the accessor is empty, or a Block if not
5944 public const int AllowedModifiers =
5946 Modifiers.PROTECTED |
5947 Modifiers.INTERNAL |
5950 public ToplevelBlock Block;
5951 public Attributes Attributes;
5952 public Location Location;
5953 public int ModFlags;
5954 public Parameters Parameters;
5956 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5962 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5966 // Ooouh Martin, templates are missing here.
5967 // When it will be possible move here a lot of child code and template method type.
5968 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5969 protected MethodData method_data;
5970 protected ToplevelBlock block;
5971 protected ListDictionary declarative_security;
5973 // The accessor are created event if they are not wanted.
5974 // But we need them because their names are reserved.
5975 // Field says whether accessor will be emited or not
5976 public readonly bool IsDummy;
5978 protected readonly string prefix;
5980 ReturnParameter return_attributes;
5982 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5983 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5985 this.prefix = prefix;
5989 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5991 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5992 accessor.Attributes)
5994 this.prefix = prefix;
5995 this.block = accessor.Block;
5998 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6000 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6003 public void UpdateName (InterfaceMemberBase member)
6005 SetMemberName (SetupName (prefix, member, Location));
6008 #region IMethodData Members
6010 public ToplevelBlock Block {
6020 public CallingConventions CallingConventions {
6022 return CallingConventions.Standard;
6026 public bool IsExcluded ()
6031 GenericMethod IMethodData.GenericMethod {
6037 public MemberName MethodName {
6043 public Type[] ParameterTypes {
6045 return ParameterInfo.Types;
6049 public abstract Parameters ParameterInfo { get ; }
6050 public abstract Type ReturnType { get; }
6051 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6055 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6057 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6058 a.Type == TypeManager.conditional_attribute_type) {
6059 Report.Error (1667, a.Location,
6060 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6061 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6065 if (a.IsValidSecurityAttribute ()) {
6066 if (declarative_security == null)
6067 declarative_security = new ListDictionary ();
6068 a.ExtractSecurityPermissionSet (declarative_security);
6072 if (a.Target == AttributeTargets.Method) {
6073 method_data.MethodBuilder.SetCustomAttribute (cb);
6077 if (a.Target == AttributeTargets.ReturnValue) {
6078 if (return_attributes == null)
6079 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6081 return_attributes.ApplyAttributeBuilder (a, cb);
6085 ApplyToExtraTarget (a, cb);
6088 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6090 throw new NotSupportedException ("You forgot to define special attribute target handling");
6093 // It is not supported for the accessors
6094 public sealed override bool Define()
6096 throw new NotSupportedException ();
6099 public void Emit (DeclSpace parent)
6101 EmitMethod (parent);
6104 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6105 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6106 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6107 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6109 if (OptAttributes != null)
6110 OptAttributes.Emit ();
6112 if (declarative_security != null) {
6113 foreach (DictionaryEntry de in declarative_security) {
6114 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6121 protected virtual void EmitMethod (DeclSpace parent)
6123 method_data.Emit (parent);
6126 public override bool EnableOverloadChecks (MemberCore overload)
6128 // This can only happen with indexers and it will
6129 // be catched as indexer difference
6130 if (overload is AbstractPropertyEventMethod)
6133 if (overload is MethodCore) {
6134 caching_flags |= Flags.MethodOverloadsExist;
6140 public override bool IsClsComplianceRequired()
6145 public bool IsDuplicateImplementation (MethodCore method)
6147 if (!MemberName.Equals (method.MemberName))
6150 Type[] param_types = method.ParameterTypes;
6152 if (param_types == null || param_types.Length != ParameterTypes.Length)
6155 for (int i = 0; i < param_types.Length; i++)
6156 if (param_types [i] != ParameterTypes [i])
6159 Report.SymbolRelatedToPreviousError (method);
6160 Report.Error (82, Location, "A member `{0}' is already reserved",
6161 method.GetSignatureForError ());
6165 public override bool IsUsed
6176 // Represents header string for documentation comment.
6178 public override string DocCommentHeader {
6179 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6182 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6187 // Properties and Indexers both generate PropertyBuilders, we use this to share
6188 // their common bits.
6190 abstract public class PropertyBase : PropertyBasedMember {
6192 public class GetMethod : PropertyMethod
6194 static string[] attribute_targets = new string [] { "method", "return" };
6196 public GetMethod (PropertyBase method):
6197 base (method, "get_")
6201 public GetMethod (PropertyBase method, Accessor accessor):
6202 base (method, accessor, "get_")
6206 public override MethodBuilder Define (DeclSpace parent)
6208 base.Define (parent);
6213 method_data = new MethodData (method, ModFlags, flags, this);
6215 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6218 return method_data.MethodBuilder;
6221 public override Type ReturnType {
6223 return method.MemberType;
6227 public override Parameters ParameterInfo {
6229 return Parameters.EmptyReadOnlyParameters;
6233 public override string[] ValidAttributeTargets {
6235 return attribute_targets;
6240 public class SetMethod : PropertyMethod {
6242 static string[] attribute_targets = new string [] { "method", "param", "return" };
6243 ImplicitParameter param_attr;
6244 protected Parameters parameters;
6246 public SetMethod (PropertyBase method) :
6247 base (method, "set_")
6249 parameters = new Parameters (
6250 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6253 public SetMethod (PropertyBase method, Accessor accessor):
6254 base (method, accessor, "set_")
6256 this.parameters = accessor.Parameters;
6259 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6261 if (a.Target == AttributeTargets.Parameter) {
6262 if (param_attr == null)
6263 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6265 param_attr.ApplyAttributeBuilder (a, cb);
6269 base.ApplyAttributeBuilder (a, cb);
6272 public override Parameters ParameterInfo {
6278 public override MethodBuilder Define (DeclSpace parent)
6280 parameters.Resolve (ResolveContext);
6281 base.Define (parent);
6286 method_data = new MethodData (method, ModFlags, flags, this);
6288 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6291 return method_data.MethodBuilder;
6294 public override Type ReturnType {
6296 return TypeManager.void_type;
6300 public override string[] ValidAttributeTargets {
6302 return attribute_targets;
6307 static string[] attribute_targets = new string [] { "property" };
6309 public abstract class PropertyMethod : AbstractPropertyEventMethod
6311 protected readonly PropertyBase method;
6312 protected MethodAttributes flags;
6314 public PropertyMethod (PropertyBase method, string prefix)
6315 : base (method, prefix)
6317 this.method = method;
6318 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6321 public PropertyMethod (PropertyBase method, Accessor accessor,
6323 : base (method, accessor, prefix)
6325 this.method = method;
6326 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6328 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6329 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6333 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6335 if (a.IsInternalMethodImplAttribute) {
6336 method.is_external_implementation = true;
6339 base.ApplyAttributeBuilder (a, cb);
6342 public override AttributeTargets AttributeTargets {
6344 return AttributeTargets.Method;
6348 public override bool IsClsComplianceRequired ()
6350 return method.IsClsComplianceRequired ();
6353 public virtual MethodBuilder Define (DeclSpace parent)
6355 CheckForDuplications ();
6358 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6359 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6360 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6362 Report.SymbolRelatedToPreviousError (mi);
6363 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6364 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6370 TypeContainer container = parent.PartialContainer;
6373 // Check for custom access modifier
6375 if ((ModFlags & Modifiers.Accessibility) == 0) {
6376 ModFlags |= method.ModFlags;
6377 flags = method.flags;
6379 if (container.Kind == Kind.Interface)
6380 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6381 GetSignatureForError ());
6383 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6384 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6387 CheckModifiers (ModFlags);
6388 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6389 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6390 flags = Modifiers.MethodAttr (ModFlags);
6391 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6394 CheckAbstractAndExtern (block != null);
6396 if (block != null && block.IsIterator)
6397 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6402 public bool HasCustomAccessModifier {
6404 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6408 public PropertyBase Property {
6414 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6416 return new EmitContext (this,
6417 ds, method.ds, method.Location, ig, ReturnType,
6418 method.ModFlags, false);
6421 public override ObsoleteAttribute GetObsoleteAttribute ()
6423 return method.GetObsoleteAttribute ();
6426 public override string GetSignatureForError()
6428 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6431 void CheckModifiers (int modflags)
6433 modflags &= Modifiers.Accessibility;
6435 int mflags = method.ModFlags & Modifiers.Accessibility;
6437 if ((mflags & Modifiers.PUBLIC) != 0) {
6438 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6440 else if ((mflags & Modifiers.PROTECTED) != 0) {
6441 if ((mflags & Modifiers.INTERNAL) != 0)
6442 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6444 flags |= Modifiers.PRIVATE;
6446 else if ((mflags & Modifiers.INTERNAL) != 0)
6447 flags |= Modifiers.PRIVATE;
6449 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6450 Report.Error (273, Location,
6451 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6452 GetSignatureForError (), method.GetSignatureForError ());
6456 protected bool CheckForDuplications ()
6458 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6461 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6465 public PropertyMethod Get, Set;
6466 public PropertyBuilder PropertyBuilder;
6467 public MethodBuilder GetBuilder, SetBuilder;
6469 protected bool define_set_first = false;
6471 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6472 int allowed_mod, MemberName name,
6473 Attributes attrs, bool define_set_first)
6474 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6476 this.define_set_first = define_set_first;
6479 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6481 if (a.HasSecurityAttribute) {
6482 a.Error_InvalidSecurityParent ();
6486 PropertyBuilder.SetCustomAttribute (cb);
6489 public override AttributeTargets AttributeTargets {
6491 return AttributeTargets.Property;
6495 protected override void DoMemberTypeDependentChecks ()
6497 base.DoMemberTypeDependentChecks ();
6501 if (MemberType.IsGenericParameter)
6505 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6506 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6510 protected override void DoMemberTypeIndependentChecks ()
6512 base.DoMemberTypeIndependentChecks ();
6515 // Accessors modifiers check
6517 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6518 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6519 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6520 GetSignatureForError ());
6523 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6524 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6525 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6526 Report.Error (276, Location,
6527 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6528 GetSignatureForError ());
6534 GetBuilder = Get.Define (Parent);
6535 return (Get.IsDummy) ? true : GetBuilder != null;
6538 bool DefineSet (bool define)
6543 SetBuilder = Set.Define (Parent);
6544 return (Set.IsDummy) ? true : SetBuilder != null;
6547 protected bool DefineAccessors ()
6549 return DefineSet (define_set_first) &&
6551 DefineSet (!define_set_first);
6554 protected abstract PropertyInfo ResolveBaseProperty ();
6556 // TODO: rename to Resolve......
6557 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6559 PropertyInfo base_property = ResolveBaseProperty ();
6560 if (base_property == null)
6563 base_ret_type = base_property.PropertyType;
6564 MethodInfo get_accessor = base_property.GetGetMethod (true);
6565 MethodInfo set_accessor = base_property.GetSetMethod (true);
6566 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6569 // Check base property accessors conflict
6571 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6572 if (get_accessor == null) {
6573 if (Get != null && !Get.IsDummy) {
6574 Report.SymbolRelatedToPreviousError (base_property);
6575 Report.Error (545, Location,
6576 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6577 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6580 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6582 if (!Get.IsDummy && !CheckAccessModifiers (
6583 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6584 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6587 if (set_accessor == null) {
6588 if (Set != null && !Set.IsDummy) {
6589 Report.SymbolRelatedToPreviousError (base_property);
6590 Report.Error (546, Location,
6591 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6592 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6595 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6597 if (!Set.IsDummy && !CheckAccessModifiers (
6598 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6599 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6603 // When one accessor does not exist and property hides base one
6604 // we need to propagate this upwards
6605 if (set_accessor == null)
6606 set_accessor = get_accessor;
6609 // Get the less restrictive access
6611 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6614 public override void Emit ()
6617 // The PropertyBuilder can be null for explicit implementations, in that
6618 // case, we do not actually emit the ".property", so there is nowhere to
6619 // put the attribute
6621 if (PropertyBuilder != null && OptAttributes != null)
6622 OptAttributes.Emit ();
6634 /// Tests whether accessors are not in collision with some method (CS0111)
6636 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6638 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6641 public override bool IsUsed
6647 return Get.IsUsed | Set.IsUsed;
6651 protected override void SetMemberName (MemberName new_name)
6653 base.SetMemberName (new_name);
6655 Get.UpdateName (this);
6656 Set.UpdateName (this);
6659 public override string[] ValidAttributeTargets {
6661 return attribute_targets;
6666 // Represents header string for documentation comment.
6668 public override string DocCommentHeader {
6669 get { return "P:"; }
6673 public class Property : PropertyBase {
6674 const int AllowedModifiers =
6677 Modifiers.PROTECTED |
6678 Modifiers.INTERNAL |
6682 Modifiers.OVERRIDE |
6683 Modifiers.ABSTRACT |
6688 const int AllowedInterfaceModifiers =
6691 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6692 MemberName name, Attributes attrs, Accessor get_block,
6693 Accessor set_block, bool define_set_first)
6694 : this (parent, type, mod, name, attrs, get_block, set_block,
6695 define_set_first, null)
6699 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6700 MemberName name, Attributes attrs, Accessor get_block,
6701 Accessor set_block, bool define_set_first, Block current_block)
6702 : base (parent, type, mod,
6703 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6704 name, attrs, define_set_first)
6706 if (get_block == null)
6707 Get = new GetMethod (this);
6709 Get = new GetMethod (this, get_block);
6711 if (set_block == null)
6712 Set = new SetMethod (this);
6714 Set = new SetMethod (this, set_block);
6716 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6717 get_block != null && get_block.Block == null &&
6718 set_block != null && set_block.Block == null) {
6719 if (RootContext.Version <= LanguageVersion.ISO_2)
6720 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6722 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
6723 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
6727 void CreateAutomaticProperty ()
6729 // Create backing field
6730 Field field = new Field (
6732 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6733 new MemberName ("<" + GetFullName (MemberName) + ">k__BackingField", Location), null);
6734 if (!field.Define ())
6737 Parent.PartialContainer.AddField (field);
6740 Get.Block = new ToplevelBlock (Parameters.EmptyReadOnlyParameters, Location);
6741 Return r = new Return (new SimpleName (field.Name, Location), Location);
6742 Get.Block.AddStatement (r);
6745 Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
6746 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6747 Set.Block.AddStatement (new StatementExpression (a));
6750 public override bool Define ()
6752 if (!base.Define ())
6755 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6757 if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6758 CreateAutomaticProperty ();
6760 if (!DefineAccessors ())
6766 // FIXME - PropertyAttributes.HasDefault ?
6768 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6769 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6772 PropertyBuilder.SetGetMethod (GetBuilder);
6773 Parent.MemberCache.AddMember (GetBuilder, Get);
6777 PropertyBuilder.SetSetMethod (SetBuilder);
6778 Parent.MemberCache.AddMember (SetBuilder, Set);
6781 TypeManager.RegisterProperty (PropertyBuilder, this);
6782 Parent.MemberCache.AddMember (PropertyBuilder, this);
6786 public override void Emit ()
6788 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6789 Report.Error (842, Location,
6790 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6791 GetSignatureForError ());
6797 protected override PropertyInfo ResolveBaseProperty ()
6799 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6800 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6805 /// Gigantic workaround for lameness in SRE follows :
6806 /// This class derives from EventInfo and attempts to basically
6807 /// wrap around the EventBuilder so that FindMembers can quickly
6808 /// return this in it search for members
6810 public class MyEventBuilder : EventInfo {
6813 // We use this to "point" to our Builder which is
6814 // not really a MemberInfo
6816 EventBuilder MyBuilder;
6819 // We "catch" and wrap these methods
6821 MethodInfo raise, remove, add;
6823 EventAttributes attributes;
6824 Type declaring_type, reflected_type, event_type;
6829 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6831 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6833 // And now store the values in our own fields.
6835 declaring_type = type_builder;
6837 reflected_type = type_builder;
6839 attributes = event_attr;
6842 this.event_type = event_type;
6846 // Methods that you have to override. Note that you only need
6847 // to "implement" the variants that take the argument (those are
6848 // the "abstract" methods, the others (GetAddMethod()) are
6851 public override MethodInfo GetAddMethod (bool nonPublic)
6856 public override MethodInfo GetRemoveMethod (bool nonPublic)
6861 public override MethodInfo GetRaiseMethod (bool nonPublic)
6867 // These methods make "MyEventInfo" look like a Builder
6869 public void SetRaiseMethod (MethodBuilder raiseMethod)
6871 raise = raiseMethod;
6872 MyBuilder.SetRaiseMethod (raiseMethod);
6875 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6877 remove = removeMethod;
6878 MyBuilder.SetRemoveOnMethod (removeMethod);
6881 public void SetAddOnMethod (MethodBuilder addMethod)
6884 MyBuilder.SetAddOnMethod (addMethod);
6887 public void SetCustomAttribute (CustomAttributeBuilder cb)
6889 MyBuilder.SetCustomAttribute (cb);
6892 public override object [] GetCustomAttributes (bool inherit)
6894 // FIXME : There's nothing which can be seemingly done here because
6895 // we have no way of getting at the custom attribute objects of the
6900 public override object [] GetCustomAttributes (Type t, bool inherit)
6902 // FIXME : Same here !
6906 public override bool IsDefined (Type t, bool b)
6911 public override EventAttributes Attributes {
6917 public override string Name {
6923 public override Type DeclaringType {
6925 return declaring_type;
6929 public override Type ReflectedType {
6931 return reflected_type;
6935 public Type EventType {
6941 public void SetUsed ()
6943 if (my_event != null) {
6944 // my_event.SetAssigned ();
6945 my_event.SetMemberIsUsed ();
6951 /// For case when event is declared like property (with add and remove accessors).
6953 public class EventProperty: Event {
6954 abstract class AEventPropertyAccessor : AEventAccessor
6956 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6957 base (method, accessor, prefix)
6961 public override MethodBuilder Define (DeclSpace ds)
6963 CheckAbstractAndExtern (block != null);
6964 return base.Define (ds);
6967 public override string GetSignatureForError ()
6969 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6973 sealed class AddDelegateMethod: AEventPropertyAccessor
6975 public AddDelegateMethod (Event method, Accessor accessor):
6976 base (method, accessor, "add_")
6980 protected override MethodInfo DelegateMethodInfo {
6982 return TypeManager.delegate_combine_delegate_delegate;
6987 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6989 public RemoveDelegateMethod (Event method, Accessor accessor):
6990 base (method, accessor, "remove_")
6994 protected override MethodInfo DelegateMethodInfo {
6996 return TypeManager.delegate_remove_delegate_delegate;
7002 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7004 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7006 Attributes attrs, Accessor add, Accessor remove)
7007 : base (parent, type, mod_flags, name, attrs)
7009 Add = new AddDelegateMethod (this, add);
7010 Remove = new RemoveDelegateMethod (this, remove);
7013 public override bool Define()
7015 if (!base.Define ())
7022 public override string[] ValidAttributeTargets {
7024 return attribute_targets;
7030 /// Event is declared like field.
7032 public class EventField : Event {
7033 abstract class EventFieldAccessor : AEventAccessor
7035 protected EventFieldAccessor (Event method, string prefix)
7036 : base (method, prefix)
7040 protected override void EmitMethod(DeclSpace parent)
7042 if (method_data.implementing != null)
7043 parent.PartialContainer.PendingImplementations.ImplementMethod (
7044 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
7046 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7049 MethodBuilder mb = method_data.MethodBuilder;
7050 ILGenerator ig = mb.GetILGenerator ();
7052 // TODO: because we cannot use generics yet
7053 FieldInfo field_info = ((EventField)method).FieldBuilder;
7055 if (parent is Class) {
7056 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7059 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7060 ig.Emit (OpCodes.Ldsfld, field_info);
7061 ig.Emit (OpCodes.Ldarg_0);
7062 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7063 ig.Emit (OpCodes.Castclass, method.MemberType);
7064 ig.Emit (OpCodes.Stsfld, field_info);
7066 ig.Emit (OpCodes.Ldarg_0);
7067 ig.Emit (OpCodes.Ldarg_0);
7068 ig.Emit (OpCodes.Ldfld, field_info);
7069 ig.Emit (OpCodes.Ldarg_1);
7070 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7071 ig.Emit (OpCodes.Castclass, method.MemberType);
7072 ig.Emit (OpCodes.Stfld, field_info);
7074 ig.Emit (OpCodes.Ret);
7078 sealed class AddDelegateMethod: EventFieldAccessor
7080 public AddDelegateMethod (Event method):
7081 base (method, "add_")
7085 protected override MethodInfo DelegateMethodInfo {
7087 return TypeManager.delegate_combine_delegate_delegate;
7092 sealed class RemoveDelegateMethod: EventFieldAccessor
7094 public RemoveDelegateMethod (Event method):
7095 base (method, "remove_")
7099 protected override MethodInfo DelegateMethodInfo {
7101 return TypeManager.delegate_remove_delegate_delegate;
7107 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7108 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7110 public FieldBuilder FieldBuilder;
7111 public Expression Initializer;
7113 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7114 : base (parent, type, mod_flags, name, attrs)
7116 Add = new AddDelegateMethod (this);
7117 Remove = new RemoveDelegateMethod (this);
7120 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7122 if (a.Target == AttributeTargets.Field) {
7123 FieldBuilder.SetCustomAttribute (cb);
7127 if (a.Target == AttributeTargets.Method) {
7128 int errors = Report.Errors;
7129 Add.ApplyAttributeBuilder (a, cb);
7130 if (errors == Report.Errors)
7131 Remove.ApplyAttributeBuilder (a, cb);
7135 base.ApplyAttributeBuilder (a, cb);
7138 public override bool Define()
7140 if (!base.Define ())
7146 // FIXME: We are unable to detect whether generic event is used because
7147 // we are using FieldExpr instead of EventExpr for event access in that
7148 // case. When this issue will be fixed this hack can be removed.
7149 if (TypeManager.IsGenericType (MemberType))
7152 if (Add.IsInterfaceImplementation)
7155 FieldBuilder = Parent.TypeBuilder.DefineField (
7157 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7158 TypeManager.RegisterEventField (EventBuilder, this);
7160 if (Initializer != null) {
7161 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7162 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7163 GetSignatureForError ());
7167 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7168 new FieldInitializer (FieldBuilder, Initializer, this));
7174 public override string[] ValidAttributeTargets
7177 return IsInterface ? attribute_targets_interface : attribute_targets;
7182 public abstract class Event : PropertyBasedMember {
7183 public abstract class AEventAccessor : AbstractPropertyEventMethod
7185 protected readonly Event method;
7186 ImplicitParameter param_attr;
7188 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7190 protected AEventAccessor (Event method, string prefix)
7191 : base (method, prefix)
7193 this.method = method;
7194 this.ModFlags = method.ModFlags;
7197 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7198 : base (method, accessor, prefix)
7200 this.method = method;
7201 this.ModFlags = method.ModFlags;
7204 public bool IsInterfaceImplementation {
7205 get { return method_data.implementing != null; }
7208 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7210 if (a.IsInternalMethodImplAttribute) {
7211 method.is_external_implementation = true;
7214 base.ApplyAttributeBuilder (a, cb);
7217 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7219 if (a.Target == AttributeTargets.Parameter) {
7220 if (param_attr == null)
7221 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7223 param_attr.ApplyAttributeBuilder (a, cb);
7227 base.ApplyAttributeBuilder (a, cb);
7230 public override AttributeTargets AttributeTargets {
7232 return AttributeTargets.Method;
7236 public override bool IsClsComplianceRequired ()
7238 return method.IsClsComplianceRequired ();
7241 public virtual MethodBuilder Define (DeclSpace parent)
7243 method_data = new MethodData (method, method.ModFlags,
7244 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7246 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7249 MethodBuilder mb = method_data.MethodBuilder;
7250 ParameterInfo.ApplyAttributes (mb);
7254 protected abstract MethodInfo DelegateMethodInfo { get; }
7256 public override Type ReturnType {
7258 return TypeManager.void_type;
7262 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7264 return new EmitContext (
7265 this, method.Parent, Location, ig, ReturnType,
7266 method.ModFlags, false);
7269 public override ObsoleteAttribute GetObsoleteAttribute ()
7271 return method.GetObsoleteAttribute ();
7274 public override string[] ValidAttributeTargets {
7276 return attribute_targets;
7280 public override Parameters ParameterInfo {
7282 return method.parameters;
7288 const int AllowedModifiers =
7291 Modifiers.PROTECTED |
7292 Modifiers.INTERNAL |
7297 Modifiers.OVERRIDE |
7299 Modifiers.ABSTRACT |
7302 const int AllowedInterfaceModifiers =
7305 public AEventAccessor Add, Remove;
7306 public MyEventBuilder EventBuilder;
7307 public MethodBuilder AddBuilder, RemoveBuilder;
7309 Parameters parameters;
7311 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7312 : base (parent, null, type, mod_flags,
7313 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7318 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7320 if ((a.HasSecurityAttribute)) {
7321 a.Error_InvalidSecurityParent ();
7325 EventBuilder.SetCustomAttribute (cb);
7328 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7330 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7333 public override AttributeTargets AttributeTargets {
7335 return AttributeTargets.Event;
7339 public override bool Define ()
7341 if (!base.Define ())
7344 if (!TypeManager.IsDelegateType (MemberType)) {
7345 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7348 parameters = Parameters.CreateFullyResolved (
7349 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7354 if (TypeManager.delegate_combine_delegate_delegate == null) {
7355 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7356 TypeManager.delegate_type, "Combine", Location,
7357 TypeManager.delegate_type, TypeManager.delegate_type);
7359 if (TypeManager.delegate_remove_delegate_delegate == null) {
7360 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7361 TypeManager.delegate_type, "Remove", Location,
7362 TypeManager.delegate_type, TypeManager.delegate_type);
7366 // Now define the accessors
7369 AddBuilder = Add.Define (Parent);
7370 if (AddBuilder == null)
7373 RemoveBuilder = Remove.Define (Parent);
7374 if (RemoveBuilder == null)
7377 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7378 EventBuilder.SetAddOnMethod (AddBuilder);
7379 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7381 Parent.MemberCache.AddMember (EventBuilder, this);
7382 Parent.MemberCache.AddMember (AddBuilder, Add);
7383 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7388 public override void Emit ()
7390 if (OptAttributes != null) {
7391 OptAttributes.Emit ();
7395 Remove.Emit (Parent);
7400 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7402 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7403 Parent.TypeBuilder, Name);
7408 AParametersCollection pd = TypeManager.GetParameterData (mi);
7409 base_ret_type = pd.Types [0];
7414 // Represents header string for documentation comment.
7416 public override string DocCommentHeader {
7417 get { return "E:"; }
7422 public class Indexer : PropertyBase
7424 public class GetIndexerMethod : GetMethod
7426 Parameters parameters;
7428 public GetIndexerMethod (Indexer method):
7431 this.parameters = method.parameters;
7434 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7435 base (method, accessor)
7437 parameters = accessor.Parameters;
7440 public override MethodBuilder Define (DeclSpace parent)
7442 parameters.Resolve (ResolveContext);
7443 return base.Define (parent);
7446 public override bool EnableOverloadChecks (MemberCore overload)
7448 if (base.EnableOverloadChecks (overload)) {
7449 overload.caching_flags |= Flags.MethodOverloadsExist;
7456 public override Parameters ParameterInfo {
7463 public class SetIndexerMethod: SetMethod
7465 public SetIndexerMethod (Indexer method):
7468 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7471 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7472 base (method, accessor)
7474 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7477 public override bool EnableOverloadChecks (MemberCore overload)
7479 if (base.EnableOverloadChecks (overload)) {
7480 overload.caching_flags |= Flags.MethodOverloadsExist;
7488 const int AllowedModifiers =
7491 Modifiers.PROTECTED |
7492 Modifiers.INTERNAL |
7496 Modifiers.OVERRIDE |
7501 const int AllowedInterfaceModifiers =
7504 public readonly Parameters parameters;
7506 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7507 Parameters parameters, Attributes attrs,
7508 Accessor get_block, Accessor set_block, bool define_set_first)
7509 : base (parent, type, mod,
7510 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7511 name, attrs, define_set_first)
7513 this.parameters = parameters;
7515 if (get_block == null)
7516 Get = new GetIndexerMethod (this);
7518 Get = new GetIndexerMethod (this, get_block);
7520 if (set_block == null)
7521 Set = new SetIndexerMethod (this);
7523 Set = new SetIndexerMethod (this, set_block);
7526 protected override bool CheckForDuplications ()
7528 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7531 public override bool Define ()
7533 if (!base.Define ())
7536 if (!DefineParameters (parameters))
7539 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7540 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7541 if (indexer_attr != null) {
7542 // Remove the attribute from the list because it is not emitted
7543 OptAttributes.Attrs.Remove (indexer_attr);
7545 string name = indexer_attr.GetIndexerAttributeValue ();
7551 if (IsExplicitImpl) {
7552 Report.Error (415, indexer_attr.Location,
7553 "The `IndexerName' attribute is valid only on an " +
7554 "indexer that is not an explicit interface member declaration");
7558 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7559 Report.Error (609, indexer_attr.Location,
7560 "Cannot set the `IndexerName' attribute on an indexer marked override");
7566 if (InterfaceType != null) {
7567 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7568 if (base_IndexerName != Name)
7569 ShortName = base_IndexerName;
7572 if (!Parent.PartialContainer.AddMember (this) ||
7573 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7576 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7578 if (!DefineAccessors ())
7585 // Now name the parameters
7587 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7588 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7591 PropertyBuilder.SetGetMethod (GetBuilder);
7592 Parent.MemberCache.AddMember (GetBuilder, Get);
7596 PropertyBuilder.SetSetMethod (SetBuilder);
7597 Parent.MemberCache.AddMember (SetBuilder, Set);
7600 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7601 Parent.MemberCache.AddMember (PropertyBuilder, this);
7605 public override bool EnableOverloadChecks (MemberCore overload)
7607 if (overload is Indexer) {
7608 caching_flags |= Flags.MethodOverloadsExist;
7612 return base.EnableOverloadChecks (overload);
7615 public override string GetDocCommentName (DeclSpace ds)
7617 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7620 public override string GetSignatureForError ()
7622 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7623 if (MemberName.Left != null) {
7625 sb.Append (MemberName.Left.GetSignatureForError ());
7628 sb.Append (".this");
7629 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7630 return sb.ToString ();
7633 protected override PropertyInfo ResolveBaseProperty ()
7635 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7636 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7639 protected override bool VerifyClsCompliance ()
7641 if (!base.VerifyClsCompliance ())
7644 parameters.VerifyClsCompliance ();
7649 public class Operator : MethodOrOperator {
7651 const int AllowedModifiers =
7657 public enum OpType : byte {
7667 // Unary and Binary operators
7690 // Implicit and Explicit
7694 // Just because of enum
7698 public readonly OpType OperatorType;
7700 static readonly string [] [] names;
7704 names = new string[(int)OpType.TOP][];
7705 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7706 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7707 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7708 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7709 names [(int) OpType.True] = new string [] { "true", "op_True" };
7710 names [(int) OpType.False] = new string [] { "false", "op_False" };
7711 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7712 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7713 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7714 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7715 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7716 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7717 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7718 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7719 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7720 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7721 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7722 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7723 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7724 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7725 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7726 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7727 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7728 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7729 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7730 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7733 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7734 int mod_flags, Parameters parameters,
7735 ToplevelBlock block, Attributes attrs, Location loc)
7736 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7737 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7739 OperatorType = type;
7743 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7745 if (a.Type == TypeManager.conditional_attribute_type) {
7746 Error_ConditionalAttributeIsNotValid ();
7750 base.ApplyAttributeBuilder (a, cb);
7753 public override bool Define ()
7755 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7756 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7757 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7760 if (!base.Define ())
7763 // imlicit and explicit operator of same types are not allowed
7764 if (OperatorType == OpType.Explicit)
7765 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7766 else if (OperatorType == OpType.Implicit)
7767 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7769 Type declaring_type = MethodData.DeclaringType;
7770 Type return_type = MemberType;
7771 Type first_arg_type = ParameterTypes [0];
7773 Type first_arg_type_unwrap = first_arg_type;
7774 if (TypeManager.IsNullableType (first_arg_type))
7775 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7777 Type return_type_unwrap = return_type;
7778 if (TypeManager.IsNullableType (return_type))
7779 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7782 // Rules for conversion operators
7784 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7785 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7786 Report.Error (555, Location,
7787 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7792 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7793 conv_type = first_arg_type;
7794 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7795 conv_type = return_type;
7797 Report.Error (556, Location,
7798 "User-defined conversion must convert to or from the enclosing type");
7803 // Because IsInterface and IsClass are not supported
7805 if (!TypeManager.IsGenericParameter (conv_type)) {
7806 if (conv_type.IsInterface) {
7807 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7808 GetSignatureForError ());
7812 if (conv_type.IsClass) {
7813 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7814 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7815 GetSignatureForError ());
7819 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7820 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7821 GetSignatureForError ());
7826 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7827 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7828 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");
7831 } else if (Parameters.Count == 1) {
7832 // Checks for Unary operators
7834 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7835 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7836 Report.Error (448, Location,
7837 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7840 if (first_arg_type != declaring_type) {
7842 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7847 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7848 Report.Error (562, Location,
7849 "The parameter type of a unary operator must be the containing type");
7853 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7854 if (return_type != TypeManager.bool_type){
7857 "The return type of operator True or False " +
7864 // Checks for Binary operators
7866 if (first_arg_type != declaring_type &&
7867 Parameters.Types [1] != declaring_type){
7870 "One of the parameters of a binary operator must " +
7871 "be the containing type");
7879 protected override bool ResolveMemberType ()
7881 if (!base.ResolveMemberType ())
7884 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7888 public override void Emit ()
7892 Parameters.ApplyAttributes (MethodBuilder);
7895 // abstract or extern methods have no bodies
7897 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7901 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7902 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7904 ec = CreateEmitContext (Parent, null);
7906 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7907 ec.EmitTopBlock (this, Block);
7910 source.CloseMethod ();
7915 // Operator cannot be override
7916 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7921 public static string GetName (OpType ot)
7923 return names [(int) ot] [0];
7926 public static string GetName (string metadata_name)
7928 for (int i = 0; i < names.Length; ++i) {
7929 if (names [i] [1] == metadata_name)
7930 return names [i] [0];
7935 public static string GetMetadataName (OpType ot)
7937 return names [(int) ot] [1];
7940 public static string GetMetadataName (string name)
7942 for (int i = 0; i < names.Length; ++i) {
7943 if (names [i] [0] == name)
7944 return names [i] [1];
7949 public OpType GetMatchingOperator ()
7951 switch (OperatorType) {
7952 case OpType.Equality:
7953 return OpType.Inequality;
7954 case OpType.Inequality:
7955 return OpType.Equality;
7957 return OpType.False;
7960 case OpType.GreaterThan:
7961 return OpType.LessThan;
7962 case OpType.LessThan:
7963 return OpType.GreaterThan;
7964 case OpType.GreaterThanOrEqual:
7965 return OpType.LessThanOrEqual;
7966 case OpType.LessThanOrEqual:
7967 return OpType.GreaterThanOrEqual;
7973 public override string GetSignatureForError ()
7975 StringBuilder sb = new StringBuilder ();
7976 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7977 sb.AppendFormat ("{0}.{1} operator {2}",
7978 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7981 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7984 sb.Append (Parameters.GetSignatureForError ());
7985 return sb.ToString ();
7990 // This is used to compare method signatures
7992 struct MethodSignature {
7994 public Type RetType;
7995 public Type [] Parameters;
7998 /// This delegate is used to extract methods which have the
7999 /// same signature as the argument
8001 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8003 public MethodSignature (string name, Type ret_type, Type [] parameters)
8008 if (parameters == null)
8009 Parameters = Type.EmptyTypes;
8011 Parameters = parameters;
8014 public override string ToString ()
8017 if (Parameters.Length != 0){
8018 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8019 for (int i = 0; i < Parameters.Length; i++){
8020 sb.Append (Parameters [i]);
8021 if (i+1 < Parameters.Length)
8024 pars = sb.ToString ();
8027 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8030 public override int GetHashCode ()
8032 return Name.GetHashCode ();
8035 public override bool Equals (Object o)
8037 MethodSignature other = (MethodSignature) o;
8039 if (other.Name != Name)
8042 if (other.RetType != RetType)
8045 if (Parameters == null){
8046 if (other.Parameters == null)
8051 if (other.Parameters == null)
8054 int c = Parameters.Length;
8055 if (other.Parameters.Length != c)
8058 for (int i = 0; i < c; i++)
8059 if (other.Parameters [i] != Parameters [i])
8065 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8067 MethodSignature sig = (MethodSignature) filter_criteria;
8069 if (m.Name != sig.Name)
8073 MethodInfo mi = m as MethodInfo;
8074 PropertyInfo pi = m as PropertyInfo;
8077 ReturnType = mi.ReturnType;
8078 else if (pi != null)
8079 ReturnType = pi.PropertyType;
8084 // we use sig.RetType == null to mean `do not check the
8085 // method return value.
8087 if (sig.RetType != null) {
8088 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8094 args = TypeManager.GetParameterData (mi).Types;
8096 args = TypeManager.GetParameterData (pi).Types;
8097 Type [] sigp = sig.Parameters;
8099 if (args.Length != sigp.Length)
8102 for (int i = args.Length - 1; i >= 0; i--)
8103 if (!TypeManager.IsEqual (args [i], sigp [i]))