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.Error (506, Location,
3388 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3389 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3393 // Now we check that the overriden method is not final
3395 if (base_method.IsFinal) {
3396 Report.SymbolRelatedToPreviousError (base_method);
3397 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3398 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3402 // Check that the permissions are not being changed
3404 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3405 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3407 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3408 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3412 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3413 Report.SymbolRelatedToPreviousError (base_method);
3414 if (this is PropertyBasedMember) {
3415 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3416 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3419 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3420 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3426 if ((ModFlags & Modifiers.NEW) == 0) {
3427 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3428 ModFlags |= Modifiers.NEW;
3429 Report.SymbolRelatedToPreviousError (base_method);
3430 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3431 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",
3432 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3434 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3435 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3439 if (base_method.IsAbstract && !IsInterface) {
3440 Report.SymbolRelatedToPreviousError (base_method);
3441 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3442 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3450 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3452 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3454 // when overriding protected internal, the method can be declared
3455 // protected internal only within the same assembly or assembly
3456 // which has InternalsVisibleTo
3458 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3459 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3460 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3462 // if it's not "protected internal", it must be "protected"
3466 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3468 // protected within the same assembly - an error
3471 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3472 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3474 // protected ok, but other attributes differ - report an error
3480 return (thisp == base_classp);
3484 public override bool Define ()
3487 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3488 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3490 flags = MethodAttributes.Public |
3491 MethodAttributes.Abstract |
3492 MethodAttributes.HideBySig |
3493 MethodAttributes.NewSlot |
3494 MethodAttributes.Virtual;
3496 Parent.PartialContainer.MethodModifiersValid (this);
3498 flags = Modifiers.MethodAttr (ModFlags);
3501 if (IsExplicitImpl) {
3502 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3503 if (iface_texpr == null)
3506 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3507 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3508 GetSignatureForError ());
3511 InterfaceType = iface_texpr.Type;
3513 if (!InterfaceType.IsInterface) {
3514 Report.SymbolRelatedToPreviousError (InterfaceType);
3515 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3516 TypeManager.CSharpName (InterfaceType));
3518 Parent.PartialContainer.VerifyImplements (this);
3521 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3524 return base.Define ();
3527 protected bool DefineParameters (Parameters parameters)
3529 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3531 if (!parameters.Resolve (rc))
3535 for (int i = 0; i < parameters.Count; ++i) {
3536 Parameter p = parameters [i];
3537 if (p.CheckAccessibility (this))
3540 Type t = parameters.Types [i];
3541 Report.SymbolRelatedToPreviousError (t);
3542 if (this is Indexer)
3543 Report.Error (55, Location,
3544 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3545 TypeManager.CSharpName (t), GetSignatureForError ());
3546 else if (this is Operator)
3547 Report.Error (57, Location,
3548 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3549 TypeManager.CSharpName (t), GetSignatureForError ());
3551 Report.Error (51, Location,
3552 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3553 TypeManager.CSharpName (t), GetSignatureForError ());
3559 public override void Emit()
3561 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3562 // We are more strict than Microsoft and report CS0626 as error
3563 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3564 Report.Error (626, Location,
3565 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3566 GetSignatureForError ());
3572 public override bool EnableOverloadChecks (MemberCore overload)
3575 // Two members can differ in their explicit interface
3576 // type parameter only
3578 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3579 if (imb != null && imb.IsExplicitImpl) {
3580 if (IsExplicitImpl) {
3581 caching_flags |= Flags.MethodOverloadsExist;
3586 return IsExplicitImpl;
3589 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3591 Report.SymbolRelatedToPreviousError (base_method);
3592 string base_name = TypeManager.GetFullNameSignature (base_method);
3593 string this_name = GetSignatureForError ();
3594 if (suffix != null) {
3595 base_name += suffix;
3596 this_name += suffix;
3599 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3600 this_name, Modifiers.GetDescription (ma), base_name);
3603 protected static string Error722 {
3605 return "`{0}': static types cannot be used as return types";
3610 /// Gets base method and its return type
3612 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3615 // The "short" name of this property / indexer / event. This is the
3616 // name without the explicit interface.
3618 public string ShortName
3620 get { return MemberName.Name; }
3621 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3625 // Returns full metadata method name
3627 public string GetFullName (MemberName name)
3629 if (!IsExplicitImpl)
3633 // When dealing with explicit members a full interface type
3634 // name is added to member name to avoid possible name conflicts
3636 // We use CSharpName which gets us full name with benefit of
3637 // replacing predefined names which saves some space and name
3640 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3643 protected override bool VerifyClsCompliance ()
3645 if (!base.VerifyClsCompliance ()) {
3646 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3647 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3650 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3651 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3656 if (GenericMethod != null)
3657 GenericMethod.VerifyClsCompliance ();
3662 public override bool IsUsed
3664 get { return IsExplicitImpl || base.IsUsed; }
3669 public abstract class MethodOrOperator : MethodCore, IMethodData
3671 public MethodBuilder MethodBuilder;
3672 ReturnParameter return_attributes;
3673 ListDictionary declarative_security;
3674 protected MethodData MethodData;
3676 static string[] attribute_targets = new string [] { "method", "return" };
3678 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3679 int allowed_mod, MemberName name,
3680 Attributes attrs, Parameters parameters)
3681 : base (parent, generic, type, mod, allowed_mod, name,
3686 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3688 if (a.Target == AttributeTargets.ReturnValue) {
3689 if (return_attributes == null)
3690 return_attributes = new ReturnParameter (MethodBuilder, Location);
3692 return_attributes.ApplyAttributeBuilder (a, cb);
3696 if (a.IsInternalMethodImplAttribute) {
3697 is_external_implementation = true;
3700 if (a.Type == TypeManager.dllimport_type) {
3701 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3702 if ((ModFlags & extern_static) != extern_static) {
3703 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3705 is_external_implementation = true;
3708 if (a.IsValidSecurityAttribute ()) {
3709 if (declarative_security == null)
3710 declarative_security = new ListDictionary ();
3711 a.ExtractSecurityPermissionSet (declarative_security);
3715 if (MethodBuilder != null)
3716 MethodBuilder.SetCustomAttribute (cb);
3719 public override AttributeTargets AttributeTargets {
3721 return AttributeTargets.Method;
3725 protected override bool CheckForDuplications ()
3727 string name = GetFullName (MemberName);
3728 if (MemberName.IsGeneric)
3729 name = MemberName.MakeName (name, MemberName.TypeArguments);
3731 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3734 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3736 return new EmitContext (
3737 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3740 protected override bool ResolveMemberType ()
3743 if (GenericMethod != null) {
3744 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3745 if (!GenericMethod.Define (MethodBuilder))
3750 return base.ResolveMemberType ();
3753 public override bool Define ()
3755 if (!base.Define ())
3761 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3763 // Current method is turned into automatically generated
3764 // wrapper which creates an instance of iterator
3766 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3767 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3770 if (IsPartialDefinition) {
3771 caching_flags &= ~Flags.Excluded_Undetected;
3772 caching_flags |= Flags.Excluded;
3773 // Add to member cache only when a partial method implementation is not there
3774 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3775 MethodBase mb = new PartialMethodDefinitionInfo (this);
3776 Parent.MemberCache.AddMember (mb, this);
3777 TypeManager.AddMethod (mb, this);
3783 MethodData = new MethodData (
3784 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3786 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3789 MethodBuilder = MethodData.MethodBuilder;
3792 if (MethodBuilder.IsGenericMethod)
3793 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3796 Parent.MemberCache.AddMember (MethodBuilder, this);
3801 protected override void DoMemberTypeIndependentChecks ()
3803 base.DoMemberTypeIndependentChecks ();
3805 CheckAbstractAndExtern (block != null);
3807 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3808 for (int i = 0; i < Parameters.Count; ++i) {
3809 if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3810 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3811 GetSignatureForError ());
3818 protected override void DoMemberTypeDependentChecks ()
3820 base.DoMemberTypeDependentChecks ();
3822 if (!TypeManager.IsGenericParameter (MemberType)) {
3823 if (MemberType.IsAbstract && MemberType.IsSealed) {
3824 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3829 public override void Emit ()
3832 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3833 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3834 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3835 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3837 if (OptAttributes != null)
3838 OptAttributes.Emit ();
3840 if (declarative_security != null) {
3841 foreach (DictionaryEntry de in declarative_security) {
3842 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3849 protected void Error_ConditionalAttributeIsNotValid ()
3851 Report.Error (577, Location,
3852 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3853 GetSignatureForError ());
3856 public bool IsPartialDefinition {
3858 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3862 public bool IsPartialImplementation {
3864 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3868 public override string[] ValidAttributeTargets {
3870 return attribute_targets;
3874 #region IMethodData Members
3876 public CallingConventions CallingConventions {
3878 CallingConventions cc = Parameters.CallingConvention;
3880 if ((ModFlags & Modifiers.STATIC) == 0)
3881 cc |= CallingConventions.HasThis;
3883 // FIXME: How is `ExplicitThis' used in C#?
3889 public Type ReturnType {
3895 public MemberName MethodName {
3901 protected override bool CheckBase ()
3903 if (!base.CheckBase ())
3906 // TODO: Destructor should derive from MethodCore
3907 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3908 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3909 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3917 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3919 public bool IsExcluded () {
3920 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3921 return (caching_flags & Flags.Excluded) != 0;
3923 caching_flags &= ~Flags.Excluded_Undetected;
3925 if (base_method == null) {
3926 if (OptAttributes == null)
3929 if (TypeManager.conditional_attribute_type == null)
3932 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3937 foreach (Attribute a in attrs) {
3938 string condition = a.GetConditionalAttributeValue ();
3939 if (condition == null)
3942 if (Location.CompilationUnit.IsConditionalDefined (condition))
3946 caching_flags |= Flags.Excluded;
3950 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3952 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3953 caching_flags |= Flags.Excluded;
3959 if (md.IsExcluded ()) {
3960 caching_flags |= Flags.Excluded;
3966 GenericMethod IMethodData.GenericMethod {
3968 return GenericMethod;
3972 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3979 public class SourceMethod : IMethodDef
3982 SourceMethodBuilder builder;
3984 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3986 this.method = method;
3988 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3991 public string Name {
3992 get { return method.Name; }
3997 if (method is MethodBuilder)
3998 return ((MethodBuilder) method).GetToken ().Token;
3999 else if (method is ConstructorBuilder)
4000 return ((ConstructorBuilder) method).GetToken ().Token;
4002 throw new NotSupportedException ();
4006 public void CloseMethod ()
4008 SymbolWriter.CloseMethod ();
4011 public void SetRealMethodName (string name)
4013 if (builder != null)
4014 builder.SetRealMethodName (name);
4017 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4019 if (!SymbolWriter.HasSymbolWriter)
4024 Location start_loc = block.StartLocation;
4025 if (start_loc.IsNull)
4028 ICompileUnit compile_unit = start_loc.CompilationUnit;
4029 if (compile_unit == null)
4032 return new SourceMethod (parent, method, compile_unit);
4036 public class Method : MethodOrOperator {
4039 /// Modifiers allowed in a class declaration
4041 const int AllowedModifiers =
4044 Modifiers.PROTECTED |
4045 Modifiers.INTERNAL |
4050 Modifiers.OVERRIDE |
4051 Modifiers.ABSTRACT |
4055 const int AllowedInterfaceModifiers =
4056 Modifiers.NEW | Modifiers.UNSAFE;
4058 public Method (DeclSpace parent, GenericMethod generic,
4059 FullNamedExpression return_type, int mod,
4060 MemberName name, Parameters parameters, Attributes attrs)
4061 : base (parent, generic, return_type, mod,
4062 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4063 name, attrs, parameters)
4067 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4068 MemberName name, Parameters parameters, Attributes attrs)
4069 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4073 public override string GetSignatureForError()
4075 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4078 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4080 Report.Error (17, location,
4081 "Program `{0}' has more than one entry point defined: `{1}'",
4082 CodeGen.FileName, TypeManager.CSharpSignature(b));
4085 bool IsEntryPoint ()
4087 if (ReturnType != TypeManager.void_type &&
4088 ReturnType != TypeManager.int32_type)
4091 if (Parameters.Count == 0)
4094 if (Parameters.Count > 1)
4097 Type t = Parameters.Types [0];
4098 return t.IsArray && t.GetArrayRank () == 1 &&
4099 TypeManager.GetElementType (t) == TypeManager.string_type &&
4100 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4103 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4105 if (a.Type == TypeManager.conditional_attribute_type) {
4106 if (IsExplicitImpl) {
4107 Error_ConditionalAttributeIsNotValid ();
4111 if (ReturnType != TypeManager.void_type) {
4112 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4116 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4117 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4122 Report.Error (582, Location, "Conditional not valid on interface members");
4126 if (MethodData.implementing != null) {
4127 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4128 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4129 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4133 for (int i = 0; i < Parameters.Count; ++i) {
4134 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4135 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4141 if (a.Type == TypeManager.extension_attribute_type) {
4142 a.Error_MisusedExtensionAttribute ();
4146 base.ApplyAttributeBuilder (a, cb);
4149 protected override bool CheckForDuplications ()
4151 if (!base.CheckForDuplications ())
4154 ArrayList ar = Parent.PartialContainer.Properties;
4156 for (int i = 0; i < ar.Count; ++i) {
4157 PropertyBase pb = (PropertyBase) ar [i];
4158 if (pb.AreAccessorsDuplicateImplementation (this))
4163 ar = Parent.PartialContainer.Indexers;
4165 for (int i = 0; i < ar.Count; ++i) {
4166 PropertyBase pb = (PropertyBase) ar [i];
4167 if (pb.AreAccessorsDuplicateImplementation (this))
4178 public override bool Define ()
4180 if (!base.Define ())
4183 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4184 Error1599 (Location, ReturnType);
4188 if (ReturnType == TypeManager.void_type && Parameters.Count == 0 &&
4189 Name == "Finalize" && !(this is Destructor)) {
4190 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4193 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4194 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4195 Parent.PartialContainer.Mark_HasEquals ();
4196 else if (Parameters.IsEmpty && Name == "GetHashCode")
4197 Parent.PartialContainer.Mark_HasGetHashCode ();
4200 if ((ModFlags & Modifiers.STATIC) == 0)
4203 if (Parameters.HasExtensionMethodType) {
4204 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4205 if (!Parent.IsTopLevel)
4206 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4207 GetSignatureForError ());
4209 if (TypeManager.extension_attribute_type == null) {
4210 Report.Error (1110, Location,
4211 "`{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",
4212 GetSignatureForError ());
4213 } else if (TypeManager.extension_attribute_attr == null) {
4214 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4215 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4218 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4221 ModFlags |= Modifiers.METHOD_EXTENSION;
4222 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4223 CodeGen.Assembly.HasExtensionMethods = true;
4225 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4226 GetSignatureForError ());
4231 // This is used to track the Entry Point,
4233 if (RootContext.NeedsEntryPoint &&
4235 (RootContext.MainClass == null ||
4236 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4237 if (IsEntryPoint ()) {
4239 if (RootContext.EntryPoint == null) {
4240 if (Parent.IsGeneric || MemberName.IsGeneric) {
4241 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4242 GetSignatureForError ());
4244 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4245 md.SetMemberIsUsed ();
4247 RootContext.EntryPoint = MethodBuilder;
4248 RootContext.EntryPointLocation = Location;
4251 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4252 Error_DuplicateEntryPoint (MethodBuilder, Location);
4255 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4256 GetSignatureForError ());
4266 public override void Emit ()
4269 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4270 if (IsPartialDefinition) {
4272 // Do attribute checks only when partial implementation does not exist
4274 if (MethodBuilder == null)
4280 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4281 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4282 GetSignatureForError ());
4284 MethodData.Emit (Parent);
4288 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4289 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4295 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4296 Location, MethodBuilder);
4301 public override bool EnableOverloadChecks (MemberCore overload)
4303 // TODO: It can be deleted when members will be defined in correct order
4304 if (overload is Operator)
4305 return overload.EnableOverloadChecks (this);
4307 if (overload is Indexer)
4310 return base.EnableOverloadChecks (overload);
4313 public static void Error1599 (Location loc, Type t)
4315 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4318 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4320 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4321 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4326 if (mi.IsSpecialName)
4329 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4333 public void SetPartialDefinition (Method methodDefinition)
4335 caching_flags |= Flags.PartialDefinitionExists;
4336 methodDefinition.MethodBuilder = MethodBuilder;
4337 if (methodDefinition.attributes == null)
4340 if (attributes == null) {
4341 attributes = methodDefinition.attributes;
4343 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4347 protected override bool VerifyClsCompliance ()
4349 if (!base.VerifyClsCompliance ())
4352 if (ParameterInfo.Count > 0) {
4353 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4355 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4362 public abstract class ConstructorInitializer : ExpressionStatement
4364 ArrayList argument_list;
4365 MethodGroupExpr base_constructor_group;
4367 public ConstructorInitializer (ArrayList argument_list, Location loc)
4369 this.argument_list = argument_list;
4373 public ArrayList Arguments {
4375 return argument_list;
4379 public override Expression CreateExpressionTree (EmitContext ec)
4381 throw new NotSupportedException ("ET");
4384 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4386 if (argument_list != null){
4387 foreach (Argument a in argument_list){
4388 if (!a.Resolve (ec, loc))
4393 if (this is ConstructorBaseInitializer) {
4394 if (ec.ContainerType.BaseType == null)
4397 type = ec.ContainerType.BaseType;
4398 if (ec.ContainerType.IsValueType) {
4399 Report.Error (522, loc,
4400 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4405 // It is legal to have "this" initializers that take no arguments
4406 // in structs, they are just no-ops.
4408 // struct D { public D (int a) : this () {}
4410 if (ec.ContainerType.IsValueType && argument_list == null)
4413 type = ec.ContainerType;
4416 base_constructor_group = MemberLookupFinal (
4417 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4418 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4419 loc) as MethodGroupExpr;
4421 if (base_constructor_group == null)
4424 base_constructor_group = base_constructor_group.OverloadResolve (
4425 ec, ref argument_list, false, loc);
4427 if (base_constructor_group == null)
4430 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4432 if (base_ctor == caller_builder){
4433 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4439 public override Expression DoResolve (EmitContext ec)
4441 throw new NotSupportedException ();
4444 public override void Emit (EmitContext ec)
4446 // It can be null for static initializers
4447 if (base_constructor_group == null)
4452 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4454 base_constructor_group.EmitCall (ec, argument_list);
4457 public override void EmitStatement (EmitContext ec)
4463 public class ConstructorBaseInitializer : ConstructorInitializer {
4464 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4465 base (argument_list, l)
4470 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4471 public GeneratedBaseInitializer (Location loc):
4477 public class ConstructorThisInitializer : ConstructorInitializer {
4478 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4479 base (argument_list, l)
4484 public class Constructor : MethodCore, IMethodData {
4485 public ConstructorBuilder ConstructorBuilder;
4486 public ConstructorInitializer Initializer;
4487 ListDictionary declarative_security;
4488 bool has_compliant_args;
4491 // Modifiers allowed for a constructor.
4493 public const int AllowedModifiers =
4495 Modifiers.PROTECTED |
4496 Modifiers.INTERNAL |
4502 static readonly string[] attribute_targets = new string [] { "method" };
4505 // The spec claims that static is not permitted, but
4506 // my very own code has static constructors.
4508 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, Parameters args,
4509 ConstructorInitializer init, Location loc)
4510 : base (parent, null, null, mod, AllowedModifiers,
4511 new MemberName (name, loc), attrs, args)
4516 public bool HasCompliantArgs {
4517 get { return has_compliant_args; }
4520 public override AttributeTargets AttributeTargets {
4521 get { return AttributeTargets.Constructor; }
4525 // Returns true if this is a default constructor
4527 public bool IsDefault ()
4529 if ((ModFlags & Modifiers.STATIC) != 0)
4530 return Parameters.IsEmpty;
4532 return Parameters.IsEmpty &&
4533 (Initializer is ConstructorBaseInitializer) &&
4534 (Initializer.Arguments == null);
4537 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4539 if (a.IsValidSecurityAttribute ()) {
4540 if (declarative_security == null) {
4541 declarative_security = new ListDictionary ();
4543 a.ExtractSecurityPermissionSet (declarative_security);
4547 if (a.IsInternalMethodImplAttribute) {
4548 is_external_implementation = true;
4551 ConstructorBuilder.SetCustomAttribute (cb);
4554 protected override bool CheckBase ()
4556 if ((ModFlags & Modifiers.STATIC) != 0) {
4557 if (!Parameters.IsEmpty) {
4558 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4559 GetSignatureForError ());
4563 // the rest can be ignored
4567 // Check whether arguments were correct.
4568 if (!DefineParameters (Parameters))
4571 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4572 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4575 if (Parent.PartialContainer.Kind == Kind.Struct) {
4576 if (Parameters.Count == 0) {
4577 Report.Error (568, Location,
4578 "Structs cannot contain explicit parameterless constructors");
4583 CheckProtectedModifier ();
4589 // Creates the ConstructorBuilder
4591 public override bool Define ()
4593 if (ConstructorBuilder != null)
4596 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4597 MethodAttributes.SpecialName);
4599 if ((ModFlags & Modifiers.STATIC) != 0) {
4600 ca |= MethodAttributes.Static | MethodAttributes.Private;
4602 ca |= MethodAttributes.HideBySig;
4604 if ((ModFlags & Modifiers.PUBLIC) != 0)
4605 ca |= MethodAttributes.Public;
4606 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4607 if ((ModFlags & Modifiers.INTERNAL) != 0)
4608 ca |= MethodAttributes.FamORAssem;
4610 ca |= MethodAttributes.Family;
4611 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4612 ca |= MethodAttributes.Assembly;
4614 ca |= MethodAttributes.Private;
4617 if (!CheckAbstractAndExtern (block != null))
4620 // Check if arguments were correct.
4624 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4625 ca, CallingConventions,
4626 Parameters.GetEmitTypes ());
4628 if (Parent.PartialContainer.IsComImport) {
4629 if (!IsDefault ()) {
4630 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4631 Parent.GetSignatureForError ());
4633 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4636 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4637 TypeManager.AddMethod (ConstructorBuilder, this);
4639 // It's here only to report an error
4640 if (block != null && block.IsIterator) {
4641 member_type = TypeManager.void_type;
4642 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4651 public override void Emit ()
4653 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4654 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4656 if (OptAttributes != null)
4657 OptAttributes.Emit ();
4661 EmitContext ec = CreateEmitContext (null, null);
4664 // If we use a "this (...)" constructor initializer, then
4665 // do not emit field initializers, they are initialized in the other constructor
4667 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4668 !(Initializer is ConstructorThisInitializer);
4670 if (emit_field_initializers)
4671 Parent.PartialContainer.ResolveFieldInitializers (ec);
4673 if (block != null) {
4674 // If this is a non-static `struct' constructor and doesn't have any
4675 // initializer, it must initialize all of the struct's fields.
4676 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4677 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4678 block.AddThisVariable (Parent, Location);
4680 if (!block.ResolveMeta (ec, ParameterInfo))
4683 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4684 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4685 Initializer = new GeneratedBaseInitializer (Location);
4688 // Spec mandates that Initializers will not have `this' access
4690 if (Initializer != null) {
4692 Initializer.Resolve (ConstructorBuilder, ec);
4693 ec.IsStatic = false;
4694 block.AddScopeStatement (new StatementExpression (Initializer));
4699 Parameters.ApplyAttributes (ConstructorBuilder);
4701 SourceMethod source = null;
4703 ec.OmitDebuggingInfo = true;
4705 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4707 bool unreachable = false;
4708 if (block != null) {
4709 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4712 ec.EmitMeta (block);
4714 if (Report.Errors > 0)
4717 ec.EmitResolvedTopBlock (block, unreachable);
4721 source.CloseMethod ();
4723 if (declarative_security != null) {
4724 foreach (DictionaryEntry de in declarative_security) {
4725 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4732 // Is never override
4733 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4738 public override string GetSignatureForError()
4740 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4743 public override string[] ValidAttributeTargets {
4745 return attribute_targets;
4749 protected override bool VerifyClsCompliance ()
4751 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4755 if (ParameterInfo.Count > 0) {
4756 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4758 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4760 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4761 foreach (Type param in Parameters.Types) {
4762 if (param.IsArray) {
4768 has_compliant_args = true;
4772 #region IMethodData Members
4774 public System.Reflection.CallingConventions CallingConventions {
4776 CallingConventions cc = Parameters.CallingConvention;
4778 if (Parent.PartialContainer.Kind == Kind.Class)
4779 if ((ModFlags & Modifiers.STATIC) == 0)
4780 cc |= CallingConventions.HasThis;
4782 // FIXME: How is `ExplicitThis' used in C#?
4788 public MemberName MethodName {
4794 public Type ReturnType {
4800 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4802 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4803 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4804 ec.CurrentBlock = block;
4808 public bool IsExcluded()
4813 GenericMethod IMethodData.GenericMethod {
4819 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4826 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4828 public interface IMethodData
4830 CallingConventions CallingConventions { get; }
4831 Location Location { get; }
4832 MemberName MethodName { get; }
4833 Type ReturnType { get; }
4834 GenericMethod GenericMethod { get; }
4835 Parameters ParameterInfo { get; }
4837 Attributes OptAttributes { get; }
4838 ToplevelBlock Block { get; set; }
4840 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4841 ObsoleteAttribute GetObsoleteAttribute ();
4842 string GetSignatureForError ();
4844 bool IsClsComplianceRequired ();
4845 void SetMemberIsUsed ();
4846 void EmitExtraSymbolInfo (SourceMethod source);
4850 // Encapsulates most of the Method's state
4852 public class MethodData {
4854 static FieldInfo methodbuilder_attrs_field;
4856 public readonly IMethodData method;
4858 public readonly GenericMethod GenericMethod;
4861 // Are we implementing an interface ?
4863 public MethodInfo implementing;
4868 protected InterfaceMemberBase member;
4869 protected int modifiers;
4870 protected MethodAttributes flags;
4871 protected Type declaring_type;
4872 protected MethodInfo parent_method;
4874 MethodBuilder builder = null;
4875 public MethodBuilder MethodBuilder {
4881 public Type DeclaringType {
4883 return declaring_type;
4887 public MethodData (InterfaceMemberBase member,
4888 int modifiers, MethodAttributes flags, IMethodData method)
4890 this.member = member;
4891 this.modifiers = modifiers;
4894 this.method = method;
4897 public MethodData (InterfaceMemberBase member,
4898 int modifiers, MethodAttributes flags,
4899 IMethodData method, MethodBuilder builder,
4900 GenericMethod generic, MethodInfo parent_method)
4901 : this (member, modifiers, flags, method)
4903 this.builder = builder;
4904 this.GenericMethod = generic;
4905 this.parent_method = parent_method;
4908 public bool Define (DeclSpace parent, string method_full_name)
4910 string name = method.MethodName.Basename;
4912 TypeContainer container = parent.PartialContainer;
4914 PendingImplementation pending = container.PendingImplementations;
4915 if (pending != null){
4916 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4918 if (member.InterfaceType != null){
4919 if (implementing == null){
4920 if (member is PropertyBase) {
4921 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4922 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4923 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4926 Report.Error (539, method.Location,
4927 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4928 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4932 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4933 Report.SymbolRelatedToPreviousError (implementing);
4934 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4935 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4939 if (implementing != null) {
4940 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4941 if (prop_method == null) {
4942 if (TypeManager.IsSpecialMethod (implementing)) {
4943 Report.SymbolRelatedToPreviousError (implementing);
4944 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4945 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4946 implementing.Name.StartsWith ("get_") ? "get" : "set");
4948 } else if (implementing.DeclaringType.IsInterface) {
4949 if (!implementing.IsSpecialName) {
4950 Report.SymbolRelatedToPreviousError (implementing);
4951 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4952 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4955 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4956 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4957 Report.SymbolRelatedToPreviousError (implementing);
4958 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4959 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4968 // For implicit implementations, make sure we are public, for
4969 // explicit implementations, make sure we are private.
4971 if (implementing != null){
4973 // Setting null inside this block will trigger a more
4974 // verbose error reporting for missing interface implementations
4976 // The "candidate" function has been flagged already
4977 // but it wont get cleared
4979 if (member.IsExplicitImpl){
4980 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4981 Report.SymbolRelatedToPreviousError (implementing);
4982 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4983 method.GetSignatureForError ());
4987 if (implementing.DeclaringType.IsInterface) {
4989 // If this is an interface method implementation,
4990 // check for public accessibility
4992 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4994 implementing = null;
4996 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4997 // We may never be private.
4998 implementing = null;
5000 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5002 // We may be protected if we're overriding something.
5004 implementing = null;
5009 // Static is not allowed
5011 if ((modifiers & Modifiers.STATIC) != 0){
5012 implementing = null;
5017 // If implementing is still valid, set flags
5019 if (implementing != null){
5021 // When implementing interface methods, set NewSlot
5022 // unless, we are overwriting a method.
5024 if (implementing.DeclaringType.IsInterface){
5025 if ((modifiers & Modifiers.OVERRIDE) == 0)
5026 flags |= MethodAttributes.NewSlot;
5029 MethodAttributes.Virtual |
5030 MethodAttributes.HideBySig;
5032 // Set Final unless we're virtual, abstract or already overriding a method.
5033 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5034 flags |= MethodAttributes.Final;
5037 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5039 if (builder == null)
5042 if (container.CurrentType != null)
5043 declaring_type = container.CurrentType;
5045 declaring_type = container.TypeBuilder;
5047 if (implementing != null && member.IsExplicitImpl) {
5048 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5051 TypeManager.AddMethod (builder, method);
5053 if (GenericMethod != null) {
5054 bool is_override = member.IsExplicitImpl |
5055 ((modifiers & Modifiers.OVERRIDE) != 0);
5057 if (implementing != null)
5058 parent_method = implementing;
5060 EmitContext ec = method.CreateEmitContext (container, null);
5061 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5070 /// Create the MethodBuilder for the method
5072 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5074 if (builder == null) {
5075 builder = container.TypeBuilder.DefineMethod (
5076 method_name, flags, method.CallingConventions,
5077 method.ReturnType, param.GetEmitTypes ());
5083 // Generic method has been already defined to resolve method parameters
5084 // correctly when they use type parameters
5086 builder.SetParameters (param.GetEmitTypes ());
5087 builder.SetReturnType (method.ReturnType);
5089 if (builder.Attributes != flags) {
5091 if (methodbuilder_attrs_field == null)
5092 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5093 methodbuilder_attrs_field.SetValue (builder, flags);
5095 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5099 throw new InternalErrorException ();
5106 public void Emit (DeclSpace parent)
5108 ToplevelBlock block = method.Block;
5112 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5114 ec = method.CreateEmitContext (parent, null);
5116 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5118 if (GenericMethod != null)
5119 GenericMethod.EmitAttributes ();
5122 // clear the pending implementation flag
5124 if (implementing != null)
5125 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5126 member.InterfaceType, this, member.IsExplicitImpl);
5128 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5131 // Handle destructors specially
5133 // FIXME: This code generates buggy code
5135 if (member is Destructor)
5136 EmitDestructor (ec, block);
5138 ec.EmitTopBlock (method, block);
5140 if (source != null) {
5141 method.EmitExtraSymbolInfo (source);
5142 source.CloseMethod ();
5146 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5148 ILGenerator ig = ec.ig;
5150 Label finish = ig.DefineLabel ();
5152 block.SetDestructor ();
5154 ig.BeginExceptionBlock ();
5155 ec.ReturnLabel = finish;
5156 ec.HasReturnLabel = true;
5157 ec.EmitTopBlock (method, block);
5159 // ig.MarkLabel (finish);
5160 ig.BeginFinallyBlock ();
5162 if (ec.ContainerType.BaseType != null) {
5163 Expression member_lookup = Expression.MemberLookup (
5164 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5165 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5167 if (member_lookup != null){
5168 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5170 ig.Emit (OpCodes.Ldarg_0);
5171 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5175 ig.EndExceptionBlock ();
5176 //ig.MarkLabel (ec.ReturnLabel);
5177 ig.Emit (OpCodes.Ret);
5181 // TODO: Should derive from MethodCore
5182 public class Destructor : Method
5184 const int AllowedModifiers =
5188 static string[] attribute_targets = new string [] { "method" };
5190 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5191 string name, Parameters parameters, Attributes attrs,
5193 : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
5196 ModFlags &= ~Modifiers.PRIVATE;
5197 if (!RootContext.StdLib && parent.Name == "System.Object")
5198 ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
5200 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
5203 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5205 if (a.Type == TypeManager.conditional_attribute_type) {
5206 Error_ConditionalAttributeIsNotValid ();
5210 base.ApplyAttributeBuilder (a, cb);
5213 public override string GetSignatureForError ()
5215 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5218 public override string[] ValidAttributeTargets {
5220 return attribute_targets;
5225 public abstract class MemberBase : MemberCore
5227 protected FullNamedExpression type_name;
5228 protected Type member_type;
5230 public readonly DeclSpace ds;
5231 public readonly GenericMethod GenericMethod;
5233 protected MemberBase (DeclSpace parent, GenericMethod generic,
5234 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5235 MemberName name, Attributes attrs)
5236 : base (parent, name, attrs)
5238 this.ds = generic != null ? generic : (DeclSpace) parent;
5239 this.type_name = type;
5240 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5241 GenericMethod = generic;
5242 if (GenericMethod != null)
5243 GenericMethod.ModFlags = ModFlags;
5247 // Main member define entry
5249 public override bool Define ()
5251 DoMemberTypeIndependentChecks ();
5254 // Returns false only when type resolution failed
5256 if (!ResolveMemberType ())
5259 DoMemberTypeDependentChecks ();
5264 // Any type_name independent checks
5266 protected virtual void DoMemberTypeIndependentChecks ()
5268 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5269 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5270 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5271 GetSignatureForError (), Parent.GetSignatureForError ());
5276 // Any type_name dependent checks
5278 protected virtual void DoMemberTypeDependentChecks ()
5280 // verify accessibility
5281 if (!IsAccessibleAs (MemberType)) {
5282 Report.SymbolRelatedToPreviousError (MemberType);
5283 if (this is Property)
5284 Report.Error (53, Location,
5285 "Inconsistent accessibility: property type `" +
5286 TypeManager.CSharpName (MemberType) + "' is less " +
5287 "accessible than property `" + GetSignatureForError () + "'");
5288 else if (this is Indexer)
5289 Report.Error (54, Location,
5290 "Inconsistent accessibility: indexer return type `" +
5291 TypeManager.CSharpName (MemberType) + "' is less " +
5292 "accessible than indexer `" + GetSignatureForError () + "'");
5293 else if (this is MethodCore) {
5294 if (this is Operator)
5295 Report.Error (56, Location,
5296 "Inconsistent accessibility: return type `" +
5297 TypeManager.CSharpName (MemberType) + "' is less " +
5298 "accessible than operator `" + GetSignatureForError () + "'");
5300 Report.Error (50, Location,
5301 "Inconsistent accessibility: return type `" +
5302 TypeManager.CSharpName (MemberType) + "' is less " +
5303 "accessible than method `" + GetSignatureForError () + "'");
5305 Report.Error (52, Location,
5306 "Inconsistent accessibility: field type `" +
5307 TypeManager.CSharpName (MemberType) + "' is less " +
5308 "accessible than field `" + GetSignatureForError () + "'");
5313 protected bool IsTypePermitted ()
5315 if (TypeManager.IsSpecialType (MemberType)) {
5316 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5322 protected virtual bool CheckBase ()
5324 CheckProtectedModifier ();
5329 public Type MemberType {
5330 get { return member_type; }
5333 protected virtual bool ResolveMemberType ()
5335 if (member_type != null)
5336 throw new InternalErrorException ("Multi-resolve");
5338 IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5339 TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5344 // Replace original type name, error reporting can use fully resolved name
5348 member_type = te.Type;
5354 // Abstract class for all fields
5356 abstract public class FieldBase : MemberBase {
5357 public FieldBuilder FieldBuilder;
5358 public Status status;
5359 protected Expression initializer;
5362 public enum Status : byte {
5363 HAS_OFFSET = 4 // Used by FieldMember.
5366 static readonly string[] attribute_targets = new string [] { "field" };
5368 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5369 int allowed_mod, MemberName name, Attributes attrs)
5370 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5373 if ((mod & Modifiers.ABSTRACT) != 0)
5374 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5377 public override AttributeTargets AttributeTargets {
5379 return AttributeTargets.Field;
5383 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5385 if (a.Type == TypeManager.field_offset_attribute_type) {
5386 status |= Status.HAS_OFFSET;
5388 if (!Parent.PartialContainer.HasExplicitLayout) {
5389 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5393 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5394 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5400 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5401 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5407 if (a.Type == TypeManager.marshal_as_attr_type) {
5408 UnmanagedMarshal marshal = a.GetMarshal (this);
5409 if (marshal != null) {
5410 FieldBuilder.SetMarshal (marshal);
5415 if ((a.HasSecurityAttribute)) {
5416 a.Error_InvalidSecurityParent ();
5420 FieldBuilder.SetCustomAttribute (cb);
5423 protected override bool CheckBase ()
5425 if (!base.CheckBase ())
5428 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5429 if (conflict_symbol == null) {
5430 if ((ModFlags & Modifiers.NEW) != 0) {
5431 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5436 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5437 Report.SymbolRelatedToPreviousError (conflict_symbol);
5438 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5439 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5445 protected override void DoMemberTypeDependentChecks ()
5447 base.DoMemberTypeDependentChecks ();
5449 if (TypeManager.IsGenericParameter (MemberType))
5452 if (MemberType.IsSealed && MemberType.IsAbstract) {
5453 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5461 // Represents header string for documentation comment.
5463 public override string DocCommentHeader {
5464 get { return "F:"; }
5467 public override void Emit ()
5470 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5471 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5474 if (OptAttributes != null) {
5475 OptAttributes.Emit ();
5478 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5479 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5485 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5487 Report.SymbolRelatedToPreviousError (static_class);
5488 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5492 public Expression Initializer {
5494 if (value != null) {
5495 this.initializer = value;
5500 protected virtual bool IsFieldClsCompliant {
5502 if (FieldBuilder == null)
5505 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5509 public override string[] ValidAttributeTargets
5512 return attribute_targets;
5516 protected override bool VerifyClsCompliance ()
5518 if (!base.VerifyClsCompliance ())
5521 if (!IsFieldClsCompliant) {
5522 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5523 GetSignatureForError ());
5528 public void SetAssigned ()
5530 caching_flags |= Flags.IsAssigned;
5534 interface IFixedBuffer
5536 FieldInfo Element { get; }
5537 Type ElementType { get; }
5540 public class FixedFieldExternal: IFixedBuffer
5542 FieldInfo element_field;
5544 public FixedFieldExternal (FieldInfo fi)
5546 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5549 #region IFixedField Members
5551 public FieldInfo Element {
5553 return element_field;
5557 public Type ElementType {
5559 return element_field.FieldType;
5567 /// Fixed buffer implementation
5569 public class FixedField : FieldBase, IFixedBuffer
5571 public const string FixedElementName = "FixedElementField";
5572 static int GlobalCounter = 0;
5573 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5574 static FieldInfo[] fi;
5576 TypeBuilder fixed_buffer_type;
5577 FieldBuilder element;
5578 Expression size_expr;
5580 const int AllowedModifiers =
5583 Modifiers.PROTECTED |
5584 Modifiers.INTERNAL |
5587 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5588 Expression size_expr, Attributes attrs, Location loc):
5589 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5591 if (RootContext.Version < LanguageVersion.ISO_2)
5592 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5594 this.size_expr = size_expr;
5597 public override bool Define()
5599 if (!base.Define ())
5602 if (!TypeManager.IsPrimitiveType (MemberType)) {
5603 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",
5604 GetSignatureForError ());
5607 // Create nested fixed buffer container
5608 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5609 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5610 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5612 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5613 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5615 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5616 Parent.MemberCache.AddMember (FieldBuilder, this);
5617 TypeManager.RegisterFieldBase (FieldBuilder, this);
5622 protected override void DoMemberTypeIndependentChecks ()
5624 base.DoMemberTypeIndependentChecks ();
5626 if (!Parent.IsInUnsafeScope)
5627 Expression.UnsafeError (Location);
5629 if (Parent.PartialContainer.Kind != Kind.Struct) {
5630 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5631 GetSignatureForError ());
5635 public override void Emit()
5637 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5638 Constant c = size_expr.ResolveAsConstant (ec, this);
5642 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5643 if (buffer_size_const == null)
5646 int buffer_size = buffer_size_const.Value;
5648 if (buffer_size <= 0) {
5649 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5653 int type_size = Expression.GetTypeSize (MemberType);
5655 if (buffer_size > int.MaxValue / type_size) {
5656 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5657 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5661 buffer_size *= type_size;
5662 EmitFieldSize (buffer_size);
5666 // Emit compiler generated fixed buffer type attribute
5668 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5670 Type attr_type = TypeManager.CoreLookupType (
5671 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5673 if (attr_type != null) {
5674 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5676 cab = new CustomAttributeBuilder (ci, new object [0]);
5677 TypeManager.unsafe_value_type_attr = cab;
5683 fixed_buffer_type.SetCustomAttribute (cab);
5688 void EmitFieldSize (int buffer_size)
5690 if (TypeManager.struct_layout_attribute_type == null) {
5691 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5692 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5694 if (TypeManager.struct_layout_attribute_type == null)
5699 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5701 object [] fi_val = new object [] { buffer_size };
5703 if (TypeManager.struct_layout_attribute_ctor == null) {
5704 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5705 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5706 if (TypeManager.struct_layout_attribute_ctor == null)
5710 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5711 ctor_args, fi, fi_val);
5712 fixed_buffer_type.SetCustomAttribute (cab);
5715 // Don't emit FixedBufferAttribute attribute for private types
5717 if ((ModFlags & Modifiers.PRIVATE) != 0)
5720 if (TypeManager.fixed_buffer_attr_ctor == null) {
5721 if (TypeManager.fixed_buffer_attr_type == null) {
5722 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5723 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5725 if (TypeManager.fixed_buffer_attr_type == null)
5729 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5730 Location, TypeManager.type_type, TypeManager.int32_type);
5732 if (TypeManager.fixed_buffer_attr_ctor == null)
5736 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5737 FieldBuilder.SetCustomAttribute (cab);
5740 protected override bool IsFieldClsCompliant {
5746 public void SetCharSet (TypeAttributes ta)
5748 TypeAttributes cta = fixed_buffer_type.Attributes;
5749 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5750 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5751 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5752 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5753 else if (cta == 0 && ta != 0)
5754 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5757 void SetTypeBuilderCharSet (TypeAttributes ta)
5759 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5761 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5763 mi.Invoke (fixed_buffer_type, new object [] { ta });
5767 #region IFixedField Members
5769 public FieldInfo Element {
5775 public Type ElementType {
5785 // The Field class is used to represents class/struct fields during parsing.
5787 public class Field : FieldBase {
5789 // Modifiers allowed in a class declaration
5791 const int AllowedModifiers =
5794 Modifiers.PROTECTED |
5795 Modifiers.INTERNAL |
5798 Modifiers.VOLATILE |
5802 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5804 : base (parent, type, mod, AllowedModifiers, name, attrs)
5808 bool CanBeVolatile ()
5810 if (TypeManager.IsReferenceType (MemberType))
5813 if (MemberType.IsEnum)
5816 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5817 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5818 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5819 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5820 MemberType == TypeManager.float_type)
5826 bool CheckStructLayout (Type type, bool isStatic)
5828 if (TypeManager.IsBuiltinType (type))
5832 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5836 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5837 if (!TypeManager.IsGenericType (type))
5840 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5841 if (!CheckStructLayout (t, false))
5847 Report.Error (523, Location,
5848 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5849 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5853 public override bool Define ()
5855 if (!base.Define ())
5860 Type[] required_modifier = null;
5861 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5862 if (TypeManager.isvolatile_type == null)
5863 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5864 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5866 if (TypeManager.isvolatile_type != null)
5867 required_modifier = new Type [] { TypeManager.isvolatile_type };
5870 FieldBuilder = Parent.TypeBuilder.DefineField (
5871 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5873 FieldBuilder = Parent.TypeBuilder.DefineField (
5874 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5876 Parent.MemberCache.AddMember (FieldBuilder, this);
5877 TypeManager.RegisterFieldBase (FieldBuilder, this);
5879 catch (ArgumentException) {
5880 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5884 if (initializer != null) {
5885 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5886 new FieldInitializer (FieldBuilder, initializer, this));
5888 if (Parent.PartialContainer.Kind == Kind.Struct)
5889 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5895 protected override void DoMemberTypeDependentChecks ()
5897 base.DoMemberTypeDependentChecks ();
5899 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5900 if (!CanBeVolatile ()) {
5901 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5902 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5905 if ((ModFlags & Modifiers.READONLY) != 0) {
5906 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5907 GetSignatureForError ());
5912 public override string GetSignatureForError ()
5914 string s = base.GetSignatureForError ();
5915 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5918 // Undecorate name mangling
5919 int l = s.LastIndexOf ('>');
5920 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5923 protected override bool VerifyClsCompliance ()
5925 if (!base.VerifyClsCompliance ())
5928 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5929 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5937 // `set' and `get' accessors are represented with an Accessor.
5939 public class Accessor {
5941 // Null if the accessor is empty, or a Block if not
5943 public const int AllowedModifiers =
5945 Modifiers.PROTECTED |
5946 Modifiers.INTERNAL |
5949 public ToplevelBlock Block;
5950 public Attributes Attributes;
5951 public Location Location;
5952 public int ModFlags;
5953 public Parameters Parameters;
5955 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5961 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5965 // Ooouh Martin, templates are missing here.
5966 // When it will be possible move here a lot of child code and template method type.
5967 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5968 protected MethodData method_data;
5969 protected ToplevelBlock block;
5970 protected ListDictionary declarative_security;
5972 // The accessor are created event if they are not wanted.
5973 // But we need them because their names are reserved.
5974 // Field says whether accessor will be emited or not
5975 public readonly bool IsDummy;
5977 protected readonly string prefix;
5979 ReturnParameter return_attributes;
5981 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5982 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5984 this.prefix = prefix;
5988 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5990 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5991 accessor.Attributes)
5993 this.prefix = prefix;
5994 this.block = accessor.Block;
5997 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5999 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6002 public void UpdateName (InterfaceMemberBase member)
6004 SetMemberName (SetupName (prefix, member, Location));
6007 #region IMethodData Members
6009 public ToplevelBlock Block {
6019 public CallingConventions CallingConventions {
6021 return CallingConventions.Standard;
6025 public bool IsExcluded ()
6030 GenericMethod IMethodData.GenericMethod {
6036 public MemberName MethodName {
6042 public Type[] ParameterTypes {
6044 return ParameterInfo.Types;
6048 public abstract Parameters ParameterInfo { get ; }
6049 public abstract Type ReturnType { get; }
6050 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6054 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6056 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6057 a.Type == TypeManager.conditional_attribute_type) {
6058 Report.Error (1667, a.Location,
6059 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6060 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6064 if (a.IsValidSecurityAttribute ()) {
6065 if (declarative_security == null)
6066 declarative_security = new ListDictionary ();
6067 a.ExtractSecurityPermissionSet (declarative_security);
6071 if (a.Target == AttributeTargets.Method) {
6072 method_data.MethodBuilder.SetCustomAttribute (cb);
6076 if (a.Target == AttributeTargets.ReturnValue) {
6077 if (return_attributes == null)
6078 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6080 return_attributes.ApplyAttributeBuilder (a, cb);
6084 ApplyToExtraTarget (a, cb);
6087 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6089 throw new NotSupportedException ("You forgot to define special attribute target handling");
6092 // It is not supported for the accessors
6093 public sealed override bool Define()
6095 throw new NotSupportedException ();
6098 public void Emit (DeclSpace parent)
6100 EmitMethod (parent);
6103 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6104 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6105 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6106 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6108 if (OptAttributes != null)
6109 OptAttributes.Emit ();
6111 if (declarative_security != null) {
6112 foreach (DictionaryEntry de in declarative_security) {
6113 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6120 protected virtual void EmitMethod (DeclSpace parent)
6122 method_data.Emit (parent);
6125 public override bool EnableOverloadChecks (MemberCore overload)
6127 // This can only happen with indexers and it will
6128 // be catched as indexer difference
6129 if (overload is AbstractPropertyEventMethod)
6132 if (overload is MethodCore) {
6133 caching_flags |= Flags.MethodOverloadsExist;
6139 public override bool IsClsComplianceRequired()
6144 public bool IsDuplicateImplementation (MethodCore method)
6146 if (!MemberName.Equals (method.MemberName))
6149 Type[] param_types = method.ParameterTypes;
6151 if (param_types == null || param_types.Length != ParameterTypes.Length)
6154 for (int i = 0; i < param_types.Length; i++)
6155 if (param_types [i] != ParameterTypes [i])
6158 Report.SymbolRelatedToPreviousError (method);
6159 Report.Error (82, Location, "A member `{0}' is already reserved",
6160 method.GetSignatureForError ());
6164 public override bool IsUsed
6175 // Represents header string for documentation comment.
6177 public override string DocCommentHeader {
6178 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6181 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6186 // Properties and Indexers both generate PropertyBuilders, we use this to share
6187 // their common bits.
6189 abstract public class PropertyBase : PropertyBasedMember {
6191 public class GetMethod : PropertyMethod
6193 static string[] attribute_targets = new string [] { "method", "return" };
6195 public GetMethod (PropertyBase method):
6196 base (method, "get_")
6200 public GetMethod (PropertyBase method, Accessor accessor):
6201 base (method, accessor, "get_")
6205 public override MethodBuilder Define (DeclSpace parent)
6207 base.Define (parent);
6212 method_data = new MethodData (method, ModFlags, flags, this);
6214 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6217 return method_data.MethodBuilder;
6220 public override Type ReturnType {
6222 return method.MemberType;
6226 public override Parameters ParameterInfo {
6228 return Parameters.EmptyReadOnlyParameters;
6232 public override string[] ValidAttributeTargets {
6234 return attribute_targets;
6239 public class SetMethod : PropertyMethod {
6241 static string[] attribute_targets = new string [] { "method", "param", "return" };
6242 ImplicitParameter param_attr;
6243 protected Parameters parameters;
6245 public SetMethod (PropertyBase method) :
6246 base (method, "set_")
6248 parameters = new Parameters (
6249 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6252 public SetMethod (PropertyBase method, Accessor accessor):
6253 base (method, accessor, "set_")
6255 this.parameters = accessor.Parameters;
6258 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6260 if (a.Target == AttributeTargets.Parameter) {
6261 if (param_attr == null)
6262 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6264 param_attr.ApplyAttributeBuilder (a, cb);
6268 base.ApplyAttributeBuilder (a, cb);
6271 public override Parameters ParameterInfo {
6277 public override MethodBuilder Define (DeclSpace parent)
6279 parameters.Resolve (ResolveContext);
6280 base.Define (parent);
6285 method_data = new MethodData (method, ModFlags, flags, this);
6287 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6290 return method_data.MethodBuilder;
6293 public override Type ReturnType {
6295 return TypeManager.void_type;
6299 public override string[] ValidAttributeTargets {
6301 return attribute_targets;
6306 static string[] attribute_targets = new string [] { "property" };
6308 public abstract class PropertyMethod : AbstractPropertyEventMethod
6310 protected readonly PropertyBase method;
6311 protected MethodAttributes flags;
6313 public PropertyMethod (PropertyBase method, string prefix)
6314 : base (method, prefix)
6316 this.method = method;
6317 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6320 public PropertyMethod (PropertyBase method, Accessor accessor,
6322 : base (method, accessor, prefix)
6324 this.method = method;
6325 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6327 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6328 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6332 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6334 if (a.IsInternalMethodImplAttribute) {
6335 method.is_external_implementation = true;
6338 base.ApplyAttributeBuilder (a, cb);
6341 public override AttributeTargets AttributeTargets {
6343 return AttributeTargets.Method;
6347 public override bool IsClsComplianceRequired ()
6349 return method.IsClsComplianceRequired ();
6352 public virtual MethodBuilder Define (DeclSpace parent)
6354 CheckForDuplications ();
6357 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6358 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6359 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6361 Report.SymbolRelatedToPreviousError (mi);
6362 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6363 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6369 TypeContainer container = parent.PartialContainer;
6372 // Check for custom access modifier
6374 if ((ModFlags & Modifiers.Accessibility) == 0) {
6375 ModFlags |= method.ModFlags;
6376 flags = method.flags;
6378 if (container.Kind == Kind.Interface)
6379 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6380 GetSignatureForError ());
6382 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6383 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6386 CheckModifiers (ModFlags);
6387 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6388 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6389 flags = Modifiers.MethodAttr (ModFlags);
6390 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6393 CheckAbstractAndExtern (block != null);
6395 if (block != null && block.IsIterator)
6396 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6401 public bool HasCustomAccessModifier {
6403 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6407 public PropertyBase Property {
6413 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6415 return new EmitContext (this,
6416 ds, method.ds, method.Location, ig, ReturnType,
6417 method.ModFlags, false);
6420 public override ObsoleteAttribute GetObsoleteAttribute ()
6422 return method.GetObsoleteAttribute ();
6425 public override string GetSignatureForError()
6427 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6430 void CheckModifiers (int modflags)
6432 modflags &= Modifiers.Accessibility;
6434 int mflags = method.ModFlags & Modifiers.Accessibility;
6436 if ((mflags & Modifiers.PUBLIC) != 0) {
6437 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6439 else if ((mflags & Modifiers.PROTECTED) != 0) {
6440 if ((mflags & Modifiers.INTERNAL) != 0)
6441 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6443 flags |= Modifiers.PRIVATE;
6445 else if ((mflags & Modifiers.INTERNAL) != 0)
6446 flags |= Modifiers.PRIVATE;
6448 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6449 Report.Error (273, Location,
6450 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6451 GetSignatureForError (), method.GetSignatureForError ());
6455 protected bool CheckForDuplications ()
6457 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6460 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6464 public PropertyMethod Get, Set;
6465 public PropertyBuilder PropertyBuilder;
6466 public MethodBuilder GetBuilder, SetBuilder;
6468 protected bool define_set_first = false;
6470 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6471 int allowed_mod, MemberName name,
6472 Attributes attrs, bool define_set_first)
6473 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6475 this.define_set_first = define_set_first;
6478 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6480 if (a.HasSecurityAttribute) {
6481 a.Error_InvalidSecurityParent ();
6485 PropertyBuilder.SetCustomAttribute (cb);
6488 public override AttributeTargets AttributeTargets {
6490 return AttributeTargets.Property;
6494 protected override void DoMemberTypeDependentChecks ()
6496 base.DoMemberTypeDependentChecks ();
6500 if (MemberType.IsGenericParameter)
6504 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6505 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6509 protected override void DoMemberTypeIndependentChecks ()
6511 base.DoMemberTypeIndependentChecks ();
6514 // Accessors modifiers check
6516 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6517 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6518 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6519 GetSignatureForError ());
6522 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6523 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6524 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6525 Report.Error (276, Location,
6526 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6527 GetSignatureForError ());
6533 GetBuilder = Get.Define (Parent);
6534 return (Get.IsDummy) ? true : GetBuilder != null;
6537 bool DefineSet (bool define)
6542 SetBuilder = Set.Define (Parent);
6543 return (Set.IsDummy) ? true : SetBuilder != null;
6546 protected bool DefineAccessors ()
6548 return DefineSet (define_set_first) &&
6550 DefineSet (!define_set_first);
6553 protected abstract PropertyInfo ResolveBaseProperty ();
6555 // TODO: rename to Resolve......
6556 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6558 PropertyInfo base_property = ResolveBaseProperty ();
6559 if (base_property == null)
6562 base_ret_type = base_property.PropertyType;
6563 MethodInfo get_accessor = base_property.GetGetMethod (true);
6564 MethodInfo set_accessor = base_property.GetSetMethod (true);
6565 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6568 // Check base property accessors conflict
6570 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6571 if (get_accessor == null) {
6572 if (Get != null && !Get.IsDummy) {
6573 Report.SymbolRelatedToPreviousError (base_property);
6574 Report.Error (545, Location,
6575 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6576 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6579 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6581 if (!Get.IsDummy && !CheckAccessModifiers (
6582 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6583 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6586 if (set_accessor == null) {
6587 if (Set != null && !Set.IsDummy) {
6588 Report.SymbolRelatedToPreviousError (base_property);
6589 Report.Error (546, Location,
6590 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6591 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6594 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6596 if (!Set.IsDummy && !CheckAccessModifiers (
6597 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6598 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6602 // When one accessor does not exist and property hides base one
6603 // we need to propagate this upwards
6604 if (set_accessor == null)
6605 set_accessor = get_accessor;
6608 // Get the less restrictive access
6610 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6613 public override void Emit ()
6616 // The PropertyBuilder can be null for explicit implementations, in that
6617 // case, we do not actually emit the ".property", so there is nowhere to
6618 // put the attribute
6620 if (PropertyBuilder != null && OptAttributes != null)
6621 OptAttributes.Emit ();
6633 /// Tests whether accessors are not in collision with some method (CS0111)
6635 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6637 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6640 public override bool IsUsed
6646 return Get.IsUsed | Set.IsUsed;
6650 protected override void SetMemberName (MemberName new_name)
6652 base.SetMemberName (new_name);
6654 Get.UpdateName (this);
6655 Set.UpdateName (this);
6658 public override string[] ValidAttributeTargets {
6660 return attribute_targets;
6665 // Represents header string for documentation comment.
6667 public override string DocCommentHeader {
6668 get { return "P:"; }
6672 public class Property : PropertyBase {
6673 const int AllowedModifiers =
6676 Modifiers.PROTECTED |
6677 Modifiers.INTERNAL |
6681 Modifiers.OVERRIDE |
6682 Modifiers.ABSTRACT |
6687 const int AllowedInterfaceModifiers =
6690 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6693 Field field = new Field (
6695 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6696 new MemberName ("<" + Name + ">k__BackingField", Location), null);
6697 ((TypeContainer)Parent).PartialContainer.AddField (field);
6700 get_block.Block = new ToplevelBlock (block, Parameters.EmptyReadOnlyParameters, Location);
6701 Return r = new Return (new SimpleName(field.Name, Location), Location);
6702 get_block.Block.AddStatement (r);
6703 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6706 set_block.Block = new ToplevelBlock (block, set_block.Parameters, Location);
6707 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6708 set_block.Block.AddStatement (new StatementExpression(a));
6709 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6712 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6713 MemberName name, Attributes attrs, Accessor get_block,
6714 Accessor set_block, bool define_set_first)
6715 : this (parent, type, mod, name, attrs, get_block, set_block,
6716 define_set_first, null)
6720 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6721 MemberName name, Attributes attrs, Accessor get_block,
6722 Accessor set_block, bool define_set_first, Block current_block)
6723 : base (parent, type, mod,
6724 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6725 name, attrs, define_set_first)
6727 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6728 get_block != null && get_block.Block == null &&
6729 set_block != null && set_block.Block == null) {
6730 if (RootContext.Version <= LanguageVersion.ISO_2)
6731 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6733 CreateAutomaticProperty (current_block, get_block, set_block);
6736 if (get_block == null)
6737 Get = new GetMethod (this);
6739 Get = new GetMethod (this, get_block);
6741 if (set_block == null)
6742 Set = new SetMethod (this);
6744 Set = new SetMethod (this, set_block);
6747 public override bool Define ()
6749 if (!base.Define ())
6752 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6754 if (!DefineAccessors ())
6760 // FIXME - PropertyAttributes.HasDefault ?
6762 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6763 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6766 PropertyBuilder.SetGetMethod (GetBuilder);
6767 Parent.MemberCache.AddMember (GetBuilder, Get);
6771 PropertyBuilder.SetSetMethod (SetBuilder);
6772 Parent.MemberCache.AddMember (SetBuilder, Set);
6775 TypeManager.RegisterProperty (PropertyBuilder, this);
6776 Parent.MemberCache.AddMember (PropertyBuilder, this);
6780 public override void Emit ()
6782 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6783 Report.Error (842, Location,
6784 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6785 GetSignatureForError ());
6791 protected override PropertyInfo ResolveBaseProperty ()
6793 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6794 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6799 /// Gigantic workaround for lameness in SRE follows :
6800 /// This class derives from EventInfo and attempts to basically
6801 /// wrap around the EventBuilder so that FindMembers can quickly
6802 /// return this in it search for members
6804 public class MyEventBuilder : EventInfo {
6807 // We use this to "point" to our Builder which is
6808 // not really a MemberInfo
6810 EventBuilder MyBuilder;
6813 // We "catch" and wrap these methods
6815 MethodInfo raise, remove, add;
6817 EventAttributes attributes;
6818 Type declaring_type, reflected_type, event_type;
6823 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6825 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6827 // And now store the values in our own fields.
6829 declaring_type = type_builder;
6831 reflected_type = type_builder;
6833 attributes = event_attr;
6836 this.event_type = event_type;
6840 // Methods that you have to override. Note that you only need
6841 // to "implement" the variants that take the argument (those are
6842 // the "abstract" methods, the others (GetAddMethod()) are
6845 public override MethodInfo GetAddMethod (bool nonPublic)
6850 public override MethodInfo GetRemoveMethod (bool nonPublic)
6855 public override MethodInfo GetRaiseMethod (bool nonPublic)
6861 // These methods make "MyEventInfo" look like a Builder
6863 public void SetRaiseMethod (MethodBuilder raiseMethod)
6865 raise = raiseMethod;
6866 MyBuilder.SetRaiseMethod (raiseMethod);
6869 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6871 remove = removeMethod;
6872 MyBuilder.SetRemoveOnMethod (removeMethod);
6875 public void SetAddOnMethod (MethodBuilder addMethod)
6878 MyBuilder.SetAddOnMethod (addMethod);
6881 public void SetCustomAttribute (CustomAttributeBuilder cb)
6883 MyBuilder.SetCustomAttribute (cb);
6886 public override object [] GetCustomAttributes (bool inherit)
6888 // FIXME : There's nothing which can be seemingly done here because
6889 // we have no way of getting at the custom attribute objects of the
6894 public override object [] GetCustomAttributes (Type t, bool inherit)
6896 // FIXME : Same here !
6900 public override bool IsDefined (Type t, bool b)
6905 public override EventAttributes Attributes {
6911 public override string Name {
6917 public override Type DeclaringType {
6919 return declaring_type;
6923 public override Type ReflectedType {
6925 return reflected_type;
6929 public Type EventType {
6935 public void SetUsed ()
6937 if (my_event != null) {
6938 // my_event.SetAssigned ();
6939 my_event.SetMemberIsUsed ();
6945 /// For case when event is declared like property (with add and remove accessors).
6947 public class EventProperty: Event {
6948 abstract class AEventPropertyAccessor : AEventAccessor
6950 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6951 base (method, accessor, prefix)
6955 public override MethodBuilder Define (DeclSpace ds)
6957 CheckAbstractAndExtern (block != null);
6958 return base.Define (ds);
6961 public override string GetSignatureForError ()
6963 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6967 sealed class AddDelegateMethod: AEventPropertyAccessor
6969 public AddDelegateMethod (Event method, Accessor accessor):
6970 base (method, accessor, "add_")
6974 protected override MethodInfo DelegateMethodInfo {
6976 return TypeManager.delegate_combine_delegate_delegate;
6981 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6983 public RemoveDelegateMethod (Event method, Accessor accessor):
6984 base (method, accessor, "remove_")
6988 protected override MethodInfo DelegateMethodInfo {
6990 return TypeManager.delegate_remove_delegate_delegate;
6996 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6998 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7000 Attributes attrs, Accessor add, Accessor remove)
7001 : base (parent, type, mod_flags, name, attrs)
7003 Add = new AddDelegateMethod (this, add);
7004 Remove = new RemoveDelegateMethod (this, remove);
7007 public override bool Define()
7009 if (!base.Define ())
7016 public override string[] ValidAttributeTargets {
7018 return attribute_targets;
7024 /// Event is declared like field.
7026 public class EventField : Event {
7027 abstract class EventFieldAccessor : AEventAccessor
7029 protected EventFieldAccessor (Event method, string prefix)
7030 : base (method, prefix)
7034 protected override void EmitMethod(DeclSpace parent)
7036 if (method_data.implementing != null)
7037 parent.PartialContainer.PendingImplementations.ImplementMethod (
7038 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
7040 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7043 MethodBuilder mb = method_data.MethodBuilder;
7044 ILGenerator ig = mb.GetILGenerator ();
7046 // TODO: because we cannot use generics yet
7047 FieldInfo field_info = ((EventField)method).FieldBuilder;
7049 if (parent is Class) {
7050 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7053 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7054 ig.Emit (OpCodes.Ldsfld, field_info);
7055 ig.Emit (OpCodes.Ldarg_0);
7056 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7057 ig.Emit (OpCodes.Castclass, method.MemberType);
7058 ig.Emit (OpCodes.Stsfld, field_info);
7060 ig.Emit (OpCodes.Ldarg_0);
7061 ig.Emit (OpCodes.Ldarg_0);
7062 ig.Emit (OpCodes.Ldfld, field_info);
7063 ig.Emit (OpCodes.Ldarg_1);
7064 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7065 ig.Emit (OpCodes.Castclass, method.MemberType);
7066 ig.Emit (OpCodes.Stfld, field_info);
7068 ig.Emit (OpCodes.Ret);
7072 sealed class AddDelegateMethod: EventFieldAccessor
7074 public AddDelegateMethod (Event method):
7075 base (method, "add_")
7079 protected override MethodInfo DelegateMethodInfo {
7081 return TypeManager.delegate_combine_delegate_delegate;
7086 sealed class RemoveDelegateMethod: EventFieldAccessor
7088 public RemoveDelegateMethod (Event method):
7089 base (method, "remove_")
7093 protected override MethodInfo DelegateMethodInfo {
7095 return TypeManager.delegate_remove_delegate_delegate;
7101 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7102 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7104 public FieldBuilder FieldBuilder;
7105 public Expression Initializer;
7107 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7108 : base (parent, type, mod_flags, name, attrs)
7110 Add = new AddDelegateMethod (this);
7111 Remove = new RemoveDelegateMethod (this);
7114 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7116 if (a.Target == AttributeTargets.Field) {
7117 FieldBuilder.SetCustomAttribute (cb);
7121 if (a.Target == AttributeTargets.Method) {
7122 int errors = Report.Errors;
7123 Add.ApplyAttributeBuilder (a, cb);
7124 if (errors == Report.Errors)
7125 Remove.ApplyAttributeBuilder (a, cb);
7129 base.ApplyAttributeBuilder (a, cb);
7132 public override bool Define()
7134 if (!base.Define ())
7140 // FIXME: We are unable to detect whether generic event is used because
7141 // we are using FieldExpr instead of EventExpr for event access in that
7142 // case. When this issue will be fixed this hack can be removed.
7143 if (TypeManager.IsGenericType (MemberType))
7146 if (Add.IsInterfaceImplementation)
7149 FieldBuilder = Parent.TypeBuilder.DefineField (
7151 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7152 TypeManager.RegisterEventField (EventBuilder, this);
7154 if (Initializer != null) {
7155 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7156 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7157 GetSignatureForError ());
7161 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7162 new FieldInitializer (FieldBuilder, Initializer, this));
7168 public override string[] ValidAttributeTargets
7171 return IsInterface ? attribute_targets_interface : attribute_targets;
7176 public abstract class Event : PropertyBasedMember {
7177 public abstract class AEventAccessor : AbstractPropertyEventMethod
7179 protected readonly Event method;
7180 ImplicitParameter param_attr;
7182 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7184 protected AEventAccessor (Event method, string prefix)
7185 : base (method, prefix)
7187 this.method = method;
7188 this.ModFlags = method.ModFlags;
7191 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7192 : base (method, accessor, prefix)
7194 this.method = method;
7195 this.ModFlags = method.ModFlags;
7198 public bool IsInterfaceImplementation {
7199 get { return method_data.implementing != null; }
7202 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7204 if (a.IsInternalMethodImplAttribute) {
7205 method.is_external_implementation = true;
7208 base.ApplyAttributeBuilder (a, cb);
7211 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7213 if (a.Target == AttributeTargets.Parameter) {
7214 if (param_attr == null)
7215 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7217 param_attr.ApplyAttributeBuilder (a, cb);
7221 base.ApplyAttributeBuilder (a, cb);
7224 public override AttributeTargets AttributeTargets {
7226 return AttributeTargets.Method;
7230 public override bool IsClsComplianceRequired ()
7232 return method.IsClsComplianceRequired ();
7235 public virtual MethodBuilder Define (DeclSpace parent)
7237 method_data = new MethodData (method, method.ModFlags,
7238 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7240 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7243 MethodBuilder mb = method_data.MethodBuilder;
7244 ParameterInfo.ApplyAttributes (mb);
7248 protected abstract MethodInfo DelegateMethodInfo { get; }
7250 public override Type ReturnType {
7252 return TypeManager.void_type;
7256 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7258 return new EmitContext (
7259 this, method.Parent, Location, ig, ReturnType,
7260 method.ModFlags, false);
7263 public override ObsoleteAttribute GetObsoleteAttribute ()
7265 return method.GetObsoleteAttribute ();
7268 public override string[] ValidAttributeTargets {
7270 return attribute_targets;
7274 public override Parameters ParameterInfo {
7276 return method.parameters;
7282 const int AllowedModifiers =
7285 Modifiers.PROTECTED |
7286 Modifiers.INTERNAL |
7291 Modifiers.OVERRIDE |
7293 Modifiers.ABSTRACT |
7296 const int AllowedInterfaceModifiers =
7299 public AEventAccessor Add, Remove;
7300 public MyEventBuilder EventBuilder;
7301 public MethodBuilder AddBuilder, RemoveBuilder;
7303 Parameters parameters;
7305 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7306 : base (parent, null, type, mod_flags,
7307 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7312 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7314 if ((a.HasSecurityAttribute)) {
7315 a.Error_InvalidSecurityParent ();
7319 EventBuilder.SetCustomAttribute (cb);
7322 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7324 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7327 public override AttributeTargets AttributeTargets {
7329 return AttributeTargets.Event;
7333 public override bool Define ()
7335 if (!base.Define ())
7338 if (!TypeManager.IsDelegateType (MemberType)) {
7339 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7342 parameters = Parameters.CreateFullyResolved (
7343 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7348 if (TypeManager.delegate_combine_delegate_delegate == null) {
7349 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7350 TypeManager.delegate_type, "Combine", Location,
7351 TypeManager.delegate_type, TypeManager.delegate_type);
7353 if (TypeManager.delegate_remove_delegate_delegate == null) {
7354 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7355 TypeManager.delegate_type, "Remove", Location,
7356 TypeManager.delegate_type, TypeManager.delegate_type);
7360 // Now define the accessors
7363 AddBuilder = Add.Define (Parent);
7364 if (AddBuilder == null)
7367 RemoveBuilder = Remove.Define (Parent);
7368 if (RemoveBuilder == null)
7371 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7372 EventBuilder.SetAddOnMethod (AddBuilder);
7373 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7375 Parent.MemberCache.AddMember (EventBuilder, this);
7376 Parent.MemberCache.AddMember (AddBuilder, Add);
7377 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7382 public override void Emit ()
7384 if (OptAttributes != null) {
7385 OptAttributes.Emit ();
7389 Remove.Emit (Parent);
7394 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7396 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7397 Parent.TypeBuilder, Name);
7402 AParametersCollection pd = TypeManager.GetParameterData (mi);
7403 base_ret_type = pd.Types [0];
7408 // Represents header string for documentation comment.
7410 public override string DocCommentHeader {
7411 get { return "E:"; }
7416 public class Indexer : PropertyBase
7418 public class GetIndexerMethod : GetMethod
7420 Parameters parameters;
7422 public GetIndexerMethod (Indexer method):
7425 this.parameters = method.parameters;
7428 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7429 base (method, accessor)
7431 parameters = accessor.Parameters;
7434 public override MethodBuilder Define (DeclSpace parent)
7436 parameters.Resolve (ResolveContext);
7437 return base.Define (parent);
7440 public override bool EnableOverloadChecks (MemberCore overload)
7442 if (base.EnableOverloadChecks (overload)) {
7443 overload.caching_flags |= Flags.MethodOverloadsExist;
7450 public override Parameters ParameterInfo {
7457 public class SetIndexerMethod: SetMethod
7459 public SetIndexerMethod (Indexer method):
7462 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7465 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7466 base (method, accessor)
7468 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7471 public override bool EnableOverloadChecks (MemberCore overload)
7473 if (base.EnableOverloadChecks (overload)) {
7474 overload.caching_flags |= Flags.MethodOverloadsExist;
7482 const int AllowedModifiers =
7485 Modifiers.PROTECTED |
7486 Modifiers.INTERNAL |
7490 Modifiers.OVERRIDE |
7495 const int AllowedInterfaceModifiers =
7498 public readonly Parameters parameters;
7500 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7501 Parameters parameters, Attributes attrs,
7502 Accessor get_block, Accessor set_block, bool define_set_first)
7503 : base (parent, type, mod,
7504 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7505 name, attrs, define_set_first)
7507 this.parameters = parameters;
7509 if (get_block == null)
7510 Get = new GetIndexerMethod (this);
7512 Get = new GetIndexerMethod (this, get_block);
7514 if (set_block == null)
7515 Set = new SetIndexerMethod (this);
7517 Set = new SetIndexerMethod (this, set_block);
7520 protected override bool CheckForDuplications ()
7522 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7525 public override bool Define ()
7527 if (!base.Define ())
7530 if (!DefineParameters (parameters))
7533 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7534 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7535 if (indexer_attr != null) {
7536 // Remove the attribute from the list because it is not emitted
7537 OptAttributes.Attrs.Remove (indexer_attr);
7539 string name = indexer_attr.GetIndexerAttributeValue ();
7545 if (IsExplicitImpl) {
7546 Report.Error (415, indexer_attr.Location,
7547 "The `IndexerName' attribute is valid only on an " +
7548 "indexer that is not an explicit interface member declaration");
7552 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7553 Report.Error (609, indexer_attr.Location,
7554 "Cannot set the `IndexerName' attribute on an indexer marked override");
7560 if (InterfaceType != null) {
7561 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7562 if (base_IndexerName != Name)
7563 ShortName = base_IndexerName;
7566 if (!Parent.PartialContainer.AddMember (this) ||
7567 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7570 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7572 if (!DefineAccessors ())
7579 // Now name the parameters
7581 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7582 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7585 PropertyBuilder.SetGetMethod (GetBuilder);
7586 Parent.MemberCache.AddMember (GetBuilder, Get);
7590 PropertyBuilder.SetSetMethod (SetBuilder);
7591 Parent.MemberCache.AddMember (SetBuilder, Set);
7594 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7595 Parent.MemberCache.AddMember (PropertyBuilder, this);
7599 public override bool EnableOverloadChecks (MemberCore overload)
7601 if (overload is Indexer) {
7602 caching_flags |= Flags.MethodOverloadsExist;
7606 return base.EnableOverloadChecks (overload);
7609 public override string GetDocCommentName (DeclSpace ds)
7611 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7614 public override string GetSignatureForError ()
7616 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7617 if (MemberName.Left != null) {
7619 sb.Append (MemberName.Left.GetSignatureForError ());
7622 sb.Append (".this");
7623 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7624 return sb.ToString ();
7627 protected override PropertyInfo ResolveBaseProperty ()
7629 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7630 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7633 protected override bool VerifyClsCompliance ()
7635 if (!base.VerifyClsCompliance ())
7638 parameters.VerifyClsCompliance ();
7643 public class Operator : MethodOrOperator {
7645 const int AllowedModifiers =
7651 public enum OpType : byte {
7661 // Unary and Binary operators
7684 // Implicit and Explicit
7688 // Just because of enum
7692 public readonly OpType OperatorType;
7694 static readonly string [] [] names;
7698 names = new string[(int)OpType.TOP][];
7699 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7700 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7701 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7702 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7703 names [(int) OpType.True] = new string [] { "true", "op_True" };
7704 names [(int) OpType.False] = new string [] { "false", "op_False" };
7705 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7706 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7707 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7708 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7709 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7710 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7711 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7712 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7713 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7714 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7715 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7716 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7717 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7718 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7719 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7720 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7721 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7722 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7723 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7724 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7727 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7728 int mod_flags, Parameters parameters,
7729 ToplevelBlock block, Attributes attrs, Location loc)
7730 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7731 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7733 OperatorType = type;
7737 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7739 if (a.Type == TypeManager.conditional_attribute_type) {
7740 Error_ConditionalAttributeIsNotValid ();
7744 base.ApplyAttributeBuilder (a, cb);
7747 public override bool Define ()
7749 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7750 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7751 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7754 if (!base.Define ())
7757 // imlicit and explicit operator of same types are not allowed
7758 if (OperatorType == OpType.Explicit)
7759 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7760 else if (OperatorType == OpType.Implicit)
7761 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7763 Type declaring_type = MethodData.DeclaringType;
7764 Type return_type = MemberType;
7765 Type first_arg_type = ParameterTypes [0];
7767 Type first_arg_type_unwrap = first_arg_type;
7768 if (TypeManager.IsNullableType (first_arg_type))
7769 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7771 Type return_type_unwrap = return_type;
7772 if (TypeManager.IsNullableType (return_type))
7773 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7776 // Rules for conversion operators
7778 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7779 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7780 Report.Error (555, Location,
7781 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7786 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7787 conv_type = first_arg_type;
7788 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7789 conv_type = return_type;
7791 Report.Error (556, Location,
7792 "User-defined conversion must convert to or from the enclosing type");
7797 // Because IsInterface and IsClass are not supported
7799 if (!TypeManager.IsGenericParameter (conv_type)) {
7800 if (conv_type.IsInterface) {
7801 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7802 GetSignatureForError ());
7806 if (conv_type.IsClass) {
7807 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7808 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7809 GetSignatureForError ());
7813 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7814 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7815 GetSignatureForError ());
7820 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7821 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7822 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");
7825 } else if (Parameters.Count == 1) {
7826 // Checks for Unary operators
7828 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7829 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7830 Report.Error (448, Location,
7831 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7834 if (first_arg_type != declaring_type) {
7836 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7841 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7842 Report.Error (562, Location,
7843 "The parameter type of a unary operator must be the containing type");
7847 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7848 if (return_type != TypeManager.bool_type){
7851 "The return type of operator True or False " +
7858 // Checks for Binary operators
7860 if (first_arg_type != declaring_type &&
7861 Parameters.Types [1] != declaring_type){
7864 "One of the parameters of a binary operator must " +
7865 "be the containing type");
7873 protected override bool ResolveMemberType ()
7875 if (!base.ResolveMemberType ())
7878 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7882 public override void Emit ()
7886 Parameters.ApplyAttributes (MethodBuilder);
7889 // abstract or extern methods have no bodies
7891 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7895 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7896 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7898 ec = CreateEmitContext (Parent, null);
7900 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7901 ec.EmitTopBlock (this, Block);
7904 source.CloseMethod ();
7909 // Operator cannot be override
7910 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7915 public static string GetName (OpType ot)
7917 return names [(int) ot] [0];
7920 public static string GetName (string metadata_name)
7922 for (int i = 0; i < names.Length; ++i) {
7923 if (names [i] [1] == metadata_name)
7924 return names [i] [0];
7929 public static string GetMetadataName (OpType ot)
7931 return names [(int) ot] [1];
7934 public static string GetMetadataName (string name)
7936 for (int i = 0; i < names.Length; ++i) {
7937 if (names [i] [0] == name)
7938 return names [i] [1];
7943 public OpType GetMatchingOperator ()
7945 switch (OperatorType) {
7946 case OpType.Equality:
7947 return OpType.Inequality;
7948 case OpType.Inequality:
7949 return OpType.Equality;
7951 return OpType.False;
7954 case OpType.GreaterThan:
7955 return OpType.LessThan;
7956 case OpType.LessThan:
7957 return OpType.GreaterThan;
7958 case OpType.GreaterThanOrEqual:
7959 return OpType.LessThanOrEqual;
7960 case OpType.LessThanOrEqual:
7961 return OpType.GreaterThanOrEqual;
7967 public override string GetSignatureForError ()
7969 StringBuilder sb = new StringBuilder ();
7970 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7971 sb.AppendFormat ("{0}.{1} operator {2}",
7972 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7975 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7978 sb.Append (Parameters.GetSignatureForError ());
7979 return sb.ToString ();
7984 // This is used to compare method signatures
7986 struct MethodSignature {
7988 public Type RetType;
7989 public Type [] Parameters;
7992 /// This delegate is used to extract methods which have the
7993 /// same signature as the argument
7995 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7997 public MethodSignature (string name, Type ret_type, Type [] parameters)
8002 if (parameters == null)
8003 Parameters = Type.EmptyTypes;
8005 Parameters = parameters;
8008 public override string ToString ()
8011 if (Parameters.Length != 0){
8012 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8013 for (int i = 0; i < Parameters.Length; i++){
8014 sb.Append (Parameters [i]);
8015 if (i+1 < Parameters.Length)
8018 pars = sb.ToString ();
8021 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8024 public override int GetHashCode ()
8026 return Name.GetHashCode ();
8029 public override bool Equals (Object o)
8031 MethodSignature other = (MethodSignature) o;
8033 if (other.Name != Name)
8036 if (other.RetType != RetType)
8039 if (Parameters == null){
8040 if (other.Parameters == null)
8045 if (other.Parameters == null)
8048 int c = Parameters.Length;
8049 if (other.Parameters.Length != c)
8052 for (int i = 0; i < c; i++)
8053 if (other.Parameters [i] != Parameters [i])
8059 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8061 MethodSignature sig = (MethodSignature) filter_criteria;
8063 if (m.Name != sig.Name)
8067 MethodInfo mi = m as MethodInfo;
8068 PropertyInfo pi = m as PropertyInfo;
8071 ReturnType = mi.ReturnType;
8072 else if (pi != null)
8073 ReturnType = pi.PropertyType;
8078 // we use sig.RetType == null to mean `do not check the
8079 // method return value.
8081 if (sig.RetType != null) {
8082 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8088 args = TypeManager.GetParameterData (mi).Types;
8090 args = TypeManager.GetParameterData (pi).Types;
8091 Type [] sigp = sig.Parameters;
8093 if (args.Length != sigp.Length)
8096 for (int i = args.Length - 1; i >= 0; i--)
8097 if (!TypeManager.IsEqual (args [i], sigp [i]))