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 (MethodOrOperator 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 ()
1151 if (PartialContainer != this)
1152 throw new InternalErrorException ();
1154 TypeExpr current_type = null;
1156 foreach (TypeParameter type_param in CurrentTypeParameters) {
1157 if (!type_param.Resolve (this)) {
1163 if (partial_parts != null && is_generic) {
1164 foreach (TypeContainer part in partial_parts)
1165 UpdateTypeParameterConstraints (part);
1168 foreach (TypeParameter type_param in TypeParameters) {
1169 if (!type_param.DefineType (this)) {
1175 // TODO: Very strange, why not simple make generic type from
1176 // current type parameters
1177 current_type = new GenericTypeExpr (this, Location);
1178 current_type = current_type.ResolveAsTypeTerminal (this, false);
1179 if (current_type == null) {
1184 CurrentType = current_type.Type;
1188 protected virtual bool DefineNestedTypes ()
1190 if (Types != null) {
1191 foreach (TypeContainer tc in Types)
1192 if (tc.DefineType () == null)
1196 if (Delegates != null) {
1197 foreach (Delegate d in Delegates)
1198 if (d.DefineType () == null)
1205 TypeContainer InTransit;
1207 protected bool CheckRecursiveDefinition (TypeContainer tc)
1209 if (InTransit != null) {
1210 Report.SymbolRelatedToPreviousError (this);
1211 if (this is Interface)
1213 529, tc.Location, "Inherited interface `{0}' causes a " +
1214 "cycle in the interface hierarchy of `{1}'",
1215 GetSignatureForError (), tc.GetSignatureForError ());
1218 146, tc.Location, "Circular base class dependency " +
1219 "involving `{0}' and `{1}'",
1220 tc.GetSignatureForError (), GetSignatureForError ());
1226 if (base_type != null && base_type.Type != null) {
1227 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1228 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1229 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1233 if (iface_exprs != null) {
1234 foreach (TypeExpr iface in iface_exprs) {
1235 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1236 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1237 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1242 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1250 /// Populates our TypeBuilder with fields and methods
1252 public override bool Define ()
1254 if (members_defined)
1255 return members_defined_ok;
1257 members_defined_ok = DoDefineMembers ();
1258 members_defined = true;
1260 return members_defined_ok;
1263 protected virtual bool DoDefineMembers ()
1265 if (iface_exprs != null) {
1266 foreach (TypeExpr iface in iface_exprs) {
1267 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1268 if ((oa != null) && !IsInObsoleteScope)
1269 AttributeTester.Report_ObsoleteMessage (
1270 oa, iface.GetSignatureForError (), Location);
1272 GenericTypeExpr ct = iface as GenericTypeExpr;
1273 if ((ct != null) && !ct.CheckConstraints (this))
1278 if (base_type != null) {
1279 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1280 if (obsolete_attr != null && !IsInObsoleteScope)
1281 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1283 GenericTypeExpr ct = base_type as GenericTypeExpr;
1284 if ((ct != null) && !ct.CheckConstraints (this))
1287 member_cache = new MemberCache (base_type.Type, this);
1288 } else if (Kind == Kind.Interface) {
1289 member_cache = new MemberCache (null, this);
1290 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1291 for (int i = 0; i < ifaces.Length; ++i)
1292 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1294 member_cache = new MemberCache (null, this);
1298 foreach (TypeContainer tc in types)
1299 member_cache.AddNestedType (tc);
1301 if (delegates != null)
1302 foreach (Delegate d in delegates)
1303 member_cache.AddNestedType (d);
1305 if (partial_parts != null) {
1306 foreach (TypeContainer part in partial_parts)
1307 part.member_cache = member_cache;
1311 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1312 if (conflict_symbol == null) {
1313 if ((ModFlags & Modifiers.NEW) != 0)
1314 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1316 if ((ModFlags & Modifiers.NEW) == 0) {
1317 Report.SymbolRelatedToPreviousError (conflict_symbol);
1318 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1319 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1324 DefineContainerMembers (constants);
1325 DefineContainerMembers (fields);
1327 if (Kind == Kind.Struct || Kind == Kind.Class) {
1328 pending = PendingImplementation.GetPendingImplementations (this);
1330 if (requires_delayed_unmanagedtype_check) {
1331 requires_delayed_unmanagedtype_check = false;
1332 foreach (Field f in fields) {
1333 if (f.MemberType != null && f.MemberType.IsPointer)
1334 TypeManager.VerifyUnManaged (f.MemberType, f.Location);
1340 // Constructors are not in the defined_names array
1342 DefineContainerMembers (instance_constructors);
1344 DefineContainerMembers (events);
1345 DefineContainerMembers (ordered_explicit_member_list);
1346 DefineContainerMembers (ordered_member_list);
1348 DefineContainerMembers (operators);
1349 DefineContainerMembers (delegates);
1351 ComputeIndexerName();
1352 CheckEqualsAndGetHashCode();
1354 if (CurrentType != null) {
1355 GenericType = CurrentType;
1360 // FIXME: This hack is needed because member cache does not work
1361 // with generic types, we rely on runtime to inflate dynamic types.
1362 // TODO: This hack requires member cache refactoring to be removed
1364 if (TypeBuilder.IsGenericType)
1365 member_cache = new MemberCache (this);
1371 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1374 mcal.DefineContainerMembers ();
1377 protected virtual void ComputeIndexerName ()
1379 if (indexers == null)
1382 string class_indexer_name = null;
1385 // If there's both an explicit and an implicit interface implementation, the
1386 // explicit one actually implements the interface while the other one is just
1387 // a normal indexer. See bug #37714.
1390 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1391 foreach (Indexer i in indexers) {
1392 if (i.InterfaceType != null) {
1393 if (seen_normal_indexers)
1394 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1398 seen_normal_indexers = true;
1400 if (class_indexer_name == null) {
1401 class_indexer_name = i.ShortName;
1405 if (i.ShortName != class_indexer_name)
1406 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");
1409 if (class_indexer_name != null)
1410 indexer_name = class_indexer_name;
1413 protected virtual void EmitIndexerName ()
1415 if (!seen_normal_indexers)
1418 if (TypeManager.default_member_ctor == null) {
1419 if (TypeManager.default_member_type == null) {
1420 TypeManager.default_member_type = TypeManager.CoreLookupType (
1421 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1423 if (TypeManager.default_member_type == null)
1427 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1428 TypeManager.default_member_type, Location, TypeManager.string_type);
1430 if (TypeManager.default_member_ctor == null)
1434 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1435 TypeBuilder.SetCustomAttribute (cb);
1438 protected virtual void CheckEqualsAndGetHashCode ()
1440 if (methods == null)
1443 if (HasEquals && !HasGetHashCode) {
1444 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1448 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1450 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1454 /// This function is based by a delegate to the FindMembers routine
1456 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1462 /// This filter is used by FindMembers, and we just keep
1463 /// a global for the filter to `AlwaysAccept'
1465 static MemberFilter accepting_filter;
1468 static TypeContainer ()
1470 accepting_filter = new MemberFilter (AlwaysAccept);
1473 public MethodInfo[] GetMethods ()
1475 ArrayList members = new ArrayList ();
1479 if (methods != null) {
1480 int len = methods.Count;
1481 for (int i = 0; i < len; i++) {
1482 Method m = (Method) methods [i];
1484 members.Add (m.MethodBuilder);
1488 if (operators != null) {
1489 int len = operators.Count;
1490 for (int i = 0; i < len; i++) {
1491 Operator o = (Operator) operators [i];
1493 members.Add (o.MethodBuilder);
1497 if (properties != null) {
1498 int len = properties.Count;
1499 for (int i = 0; i < len; i++) {
1500 Property p = (Property) properties [i];
1502 if (p.GetBuilder != null)
1503 members.Add (p.GetBuilder);
1504 if (p.SetBuilder != null)
1505 members.Add (p.SetBuilder);
1509 if (indexers != null) {
1510 int len = indexers.Count;
1511 for (int i = 0; i < len; i++) {
1512 Indexer ix = (Indexer) indexers [i];
1514 if (ix.GetBuilder != null)
1515 members.Add (ix.GetBuilder);
1516 if (ix.SetBuilder != null)
1517 members.Add (ix.SetBuilder);
1521 if (events != null) {
1522 int len = events.Count;
1523 for (int i = 0; i < len; i++) {
1524 Event e = (Event) events [i];
1526 if (e.AddBuilder != null)
1527 members.Add (e.AddBuilder);
1528 if (e.RemoveBuilder != null)
1529 members.Add (e.RemoveBuilder);
1533 MethodInfo[] retMethods = new MethodInfo [members.Count];
1534 members.CopyTo (retMethods, 0);
1538 // Indicated whether container has StructLayout attribute set Explicit
1539 public bool HasExplicitLayout {
1540 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1541 set { caching_flags |= Flags.HasExplicitLayout; }
1544 public bool HasStructLayout {
1545 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1546 set { caching_flags |= Flags.HasStructLayout; }
1550 // Return the nested type with name @name. Ensures that the nested type
1551 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1553 public Type FindNestedType (string name)
1555 if (PartialContainer != this)
1556 throw new InternalErrorException ("should not happen");
1558 ArrayList [] lists = { types, delegates };
1560 for (int j = 0; j < lists.Length; ++j) {
1561 ArrayList list = lists [j];
1565 int len = list.Count;
1566 for (int i = 0; i < len; ++i) {
1567 DeclSpace ds = (DeclSpace) list [i];
1568 if (ds.Basename == name) {
1569 return ds.DefineType ();
1577 private void FindMembers_NestedTypes (int modflags,
1578 BindingFlags bf, MemberFilter filter, object criteria,
1579 ref ArrayList members)
1581 ArrayList [] lists = { types, delegates };
1583 for (int j = 0; j < lists.Length; ++j) {
1584 ArrayList list = lists [j];
1588 int len = list.Count;
1589 for (int i = 0; i < len; i++) {
1590 DeclSpace ds = (DeclSpace) list [i];
1592 if ((ds.ModFlags & modflags) == 0)
1595 TypeBuilder tb = ds.TypeBuilder;
1597 if (!(criteria is string) || ds.Basename.Equals (criteria))
1598 tb = ds.DefineType ();
1601 if (tb != null && (filter (tb, criteria) == true)) {
1602 if (members == null)
1603 members = new ArrayList ();
1612 /// This method returns the members of this type just like Type.FindMembers would
1613 /// Only, we need to use this for types which are _being_ defined because MS'
1614 /// implementation can't take care of that.
1617 // FIXME: return an empty static array instead of null, that cleans up
1618 // some code and is consistent with some coding conventions I just found
1622 // Notice that in various cases we check if our field is non-null,
1623 // something that would normally mean that there was a bug elsewhere.
1625 // The problem happens while we are defining p-invoke methods, as those
1626 // will trigger a FindMembers, but this happens before things are defined
1628 // Since the whole process is a no-op, it is fine to check for null here.
1630 // TODO: This approach will be one day completely removed, it's already
1631 // used at few places only
1634 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1635 MemberFilter filter, object criteria)
1637 ArrayList members = null;
1640 if ((bf & BindingFlags.Public) != 0)
1641 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1643 if ((bf & BindingFlags.NonPublic) != 0)
1644 modflags |= Modifiers.PRIVATE;
1646 int static_mask = 0, static_flags = 0;
1647 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1648 case BindingFlags.Static:
1649 static_mask = static_flags = Modifiers.STATIC;
1652 case BindingFlags.Instance:
1653 static_mask = Modifiers.STATIC;
1658 static_mask = static_flags = 0;
1662 Timer.StartTimer (TimerType.TcFindMembers);
1665 filter = accepting_filter;
1667 if ((mt & MemberTypes.Field) != 0) {
1668 if (fields != null) {
1669 int len = fields.Count;
1670 for (int i = 0; i < len; i++) {
1671 FieldBase f = (FieldBase) fields [i];
1673 if ((f.ModFlags & modflags) == 0)
1675 if ((f.ModFlags & static_mask) != static_flags)
1678 FieldBuilder fb = f.FieldBuilder;
1679 if (fb != null && filter (fb, criteria) == true) {
1680 if (members == null)
1681 members = new ArrayList ();
1688 if (constants != null) {
1689 int len = constants.Count;
1690 for (int i = 0; i < len; i++) {
1691 Const con = (Const) constants [i];
1693 if ((con.ModFlags & modflags) == 0)
1695 if ((con.ModFlags & static_mask) != static_flags)
1698 FieldBuilder fb = con.FieldBuilder;
1701 fb = con.FieldBuilder;
1703 if (fb != null && filter (fb, criteria) == true) {
1704 if (members == null)
1705 members = new ArrayList ();
1713 if ((mt & MemberTypes.Method) != 0) {
1714 if (methods != null) {
1715 int len = methods.Count;
1716 for (int i = 0; i < len; i++) {
1717 MethodOrOperator m = (MethodOrOperator) methods [i];
1719 if ((m.ModFlags & modflags) == 0)
1721 if ((m.ModFlags & static_mask) != static_flags)
1724 MethodBuilder mb = m.MethodBuilder;
1726 if (mb != null && filter (mb, criteria) == true) {
1727 if (members == null)
1728 members = new ArrayList ();
1735 if (operators != null) {
1736 int len = operators.Count;
1737 for (int i = 0; i < len; i++) {
1738 Operator o = (Operator) operators [i];
1740 if ((o.ModFlags & modflags) == 0)
1742 if ((o.ModFlags & static_mask) != static_flags)
1745 MethodBuilder ob = o.MethodBuilder;
1746 if (ob != null && filter (ob, criteria) == true) {
1747 if (members == null)
1748 members = new ArrayList ();
1755 if (events != null) {
1756 foreach (Event e in events) {
1757 if ((e.ModFlags & modflags) == 0)
1759 if ((e.ModFlags & static_mask) != static_flags)
1762 MethodBuilder b = e.AddBuilder;
1763 if (b != null && filter (b, criteria)) {
1764 if (members == null)
1765 members = new ArrayList (4);
1770 b = e.RemoveBuilder;
1771 if (b != null && filter (b, criteria)) {
1772 if (members == null)
1773 members = new ArrayList (4);
1780 if (properties != null) {
1781 int len = properties.Count;
1782 for (int i = 0; i < len; i++) {
1783 Property p = (Property) properties [i];
1785 if ((p.ModFlags & modflags) == 0)
1787 if ((p.ModFlags & static_mask) != static_flags)
1793 if (b != null && filter (b, criteria) == true) {
1794 if (members == null)
1795 members = new ArrayList ();
1801 if (b != null && filter (b, criteria) == true) {
1802 if (members == null)
1803 members = new ArrayList ();
1810 if (indexers != null) {
1811 int len = indexers.Count;
1812 for (int i = 0; i < len; i++) {
1813 Indexer ix = (Indexer) indexers [i];
1815 if ((ix.ModFlags & modflags) == 0)
1817 if ((ix.ModFlags & static_mask) != static_flags)
1823 if (b != null && filter (b, criteria) == true) {
1824 if (members == null)
1825 members = new ArrayList ();
1831 if (b != null && filter (b, criteria) == true) {
1832 if (members == null)
1833 members = new ArrayList ();
1841 if ((mt & MemberTypes.Event) != 0) {
1842 if (events != null) {
1843 int len = events.Count;
1844 for (int i = 0; i < len; i++) {
1845 Event e = (Event) events [i];
1847 if ((e.ModFlags & modflags) == 0)
1849 if ((e.ModFlags & static_mask) != static_flags)
1852 MemberInfo eb = e.EventBuilder;
1853 if (eb != null && filter (eb, criteria) == true) {
1854 if (members == null)
1855 members = new ArrayList ();
1857 members.Add (e.EventBuilder);
1863 if ((mt & MemberTypes.Property) != 0){
1864 if (properties != null) {
1865 int len = properties.Count;
1866 for (int i = 0; i < len; i++) {
1867 Property p = (Property) properties [i];
1869 if ((p.ModFlags & modflags) == 0)
1871 if ((p.ModFlags & static_mask) != static_flags)
1874 MemberInfo pb = p.PropertyBuilder;
1875 if (pb != null && filter (pb, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1879 members.Add (p.PropertyBuilder);
1884 if (indexers != null) {
1885 int len = indexers.Count;
1886 for (int i = 0; i < len; i++) {
1887 Indexer ix = (Indexer) indexers [i];
1889 if ((ix.ModFlags & modflags) == 0)
1891 if ((ix.ModFlags & static_mask) != static_flags)
1894 MemberInfo ib = ix.PropertyBuilder;
1895 if (ib != null && filter (ib, criteria) == true) {
1896 if (members == null)
1897 members = new ArrayList ();
1899 members.Add (ix.PropertyBuilder);
1905 if ((mt & MemberTypes.NestedType) != 0)
1906 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1908 if ((mt & MemberTypes.Constructor) != 0){
1909 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1910 int len = instance_constructors.Count;
1911 for (int i = 0; i < len; i++) {
1912 Constructor c = (Constructor) instance_constructors [i];
1914 ConstructorBuilder cb = c.ConstructorBuilder;
1915 if (cb != null && filter (cb, criteria) == true) {
1916 if (members == null)
1917 members = new ArrayList ();
1924 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1925 ConstructorBuilder cb =
1926 default_static_constructor.ConstructorBuilder;
1928 if (cb != null && filter (cb, criteria) == true) {
1929 if (members == null)
1930 members = new ArrayList ();
1938 // Lookup members in base if requested.
1940 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1941 if (TypeBuilder.BaseType != null) {
1942 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1943 if (list.Count > 0) {
1944 if (members == null)
1945 members = new ArrayList ();
1947 members.AddRange (list);
1952 Timer.StopTimer (TimerType.TcFindMembers);
1954 if (members == null)
1955 return MemberList.Empty;
1957 return new MemberList (members);
1960 public override MemberCache MemberCache {
1962 return member_cache;
1966 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1967 MemberFilter filter, object criteria)
1969 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1972 return ds.FindMembers (mt, bf, filter, criteria);
1974 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1978 /// Emits the values for the constants
1980 public void EmitConstants ()
1982 if (constants != null)
1983 foreach (Const con in constants)
1988 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1993 foreach (MemberCore mc in al) {
1994 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1997 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1998 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2003 public virtual void VerifyMembers ()
2006 // Check for internal or private fields that were never assigned
2008 if (Report.WarningLevel >= 3) {
2009 CheckMemberUsage (properties, "property");
2010 CheckMemberUsage (methods, "method");
2011 CheckMemberUsage (constants, "constant");
2013 if (fields != null){
2014 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2015 foreach (FieldBase f in fields) {
2016 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2017 if (is_type_exposed)
2020 f.SetMemberIsUsed ();
2024 if ((f.caching_flags & Flags.IsAssigned) == 0)
2025 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2028 const int error_code = 414;
2030 const int error_code = 169;
2032 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2033 f.GetSignatureForError ());
2039 // Only report 649 on level 4
2041 if (Report.WarningLevel < 4)
2044 if ((f.caching_flags & Flags.IsAssigned) != 0)
2048 // Don't be pendatic over serializable attributes
2050 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2053 Constant c = New.Constantify (f.MemberType);
2054 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2055 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2061 // TODO: move to ClassOrStruct
2062 void EmitConstructors ()
2064 if (instance_constructors == null)
2067 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2068 bool has_compliant_args = false;
2070 foreach (Constructor c in instance_constructors) {
2074 catch (Exception e) {
2075 throw new InternalErrorException (c, e);
2078 if (has_compliant_args)
2081 has_compliant_args = c.HasCompliantArgs;
2083 if (!has_compliant_args)
2084 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2086 foreach (Constructor c in instance_constructors) {
2090 catch (Exception e) {
2091 throw new InternalErrorException (c, e);
2098 /// Emits the code, this step is performed after all
2099 /// the types, enumerations, constructors
2101 public virtual void EmitType ()
2103 if (OptAttributes != null)
2104 OptAttributes.Emit ();
2108 EmitConstructors ();
2110 // Can not continue if constants are broken
2112 if (Report.Errors > 0)
2115 if (default_static_constructor != null)
2116 default_static_constructor.Emit ();
2118 if (operators != null)
2119 foreach (Operator o in operators)
2122 if (properties != null)
2123 foreach (Property p in properties)
2126 if (indexers != null) {
2127 foreach (Indexer indx in indexers)
2132 if (events != null){
2133 foreach (Event e in Events)
2137 if (methods != null) {
2138 for (int i = 0; i < methods.Count; ++i)
2139 ((MethodOrOperator) methods [i]).Emit ();
2143 foreach (FieldBase f in fields)
2146 if (delegates != null) {
2147 foreach (Delegate d in Delegates) {
2152 if (pending != null)
2153 pending.VerifyPendingMethods ();
2155 if (Report.Errors > 0)
2158 if (compiler_generated != null) {
2159 for (int i = 0; i < compiler_generated.Count; ++i)
2160 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2164 public override void CloseType ()
2166 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2170 caching_flags |= Flags.CloseTypeCreated;
2171 TypeBuilder.CreateType ();
2172 } catch (TypeLoadException){
2174 // This is fine, the code still created the type
2176 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2177 // Console.WriteLine (e.Message);
2178 } catch (Exception e) {
2179 throw new InternalErrorException (this, e);
2183 foreach (TypeContainer tc in Types)
2184 if (tc.Kind == Kind.Struct)
2187 foreach (TypeContainer tc in Types)
2188 if (tc.Kind != Kind.Struct)
2192 if (Delegates != null)
2193 foreach (Delegate d in Delegates)
2196 if (compiler_generated != null)
2197 foreach (CompilerGeneratedClass c in compiler_generated)
2204 initialized_fields = null;
2205 initialized_static_fields = null;
2207 ordered_explicit_member_list = null;
2208 ordered_member_list = null;
2213 compiler_generated = null;
2214 default_constructor = null;
2215 default_static_constructor = null;
2217 OptAttributes = null;
2220 member_cache = null;
2224 // Performs the validation on a Method's modifiers (properties have
2225 // the same properties).
2227 public bool MethodModifiersValid (MemberCore mc)
2229 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2230 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2231 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2233 int flags = mc.ModFlags;
2236 // At most one of static, virtual or override
2238 if ((flags & Modifiers.STATIC) != 0){
2239 if ((flags & vao) != 0){
2240 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2241 mc.GetSignatureForError ());
2246 if (Kind == Kind.Struct){
2247 if ((flags & va) != 0){
2248 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2253 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2254 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2255 mc.GetSignatureForError ());
2260 // If the declaration includes the abstract modifier, then the
2261 // declaration does not include static, virtual or extern
2263 if ((flags & Modifiers.ABSTRACT) != 0){
2264 if ((flags & Modifiers.EXTERN) != 0){
2266 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2270 if ((flags & Modifiers.SEALED) != 0) {
2271 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2275 if ((flags & Modifiers.VIRTUAL) != 0){
2276 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2280 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2281 Report.SymbolRelatedToPreviousError (this);
2282 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2283 mc.GetSignatureForError (), GetSignatureForError ());
2288 if ((flags & Modifiers.PRIVATE) != 0){
2289 if ((flags & vao) != 0){
2290 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2295 if ((flags & Modifiers.SEALED) != 0){
2296 if ((flags & Modifiers.OVERRIDE) == 0){
2297 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2305 public Constructor DefaultStaticConstructor {
2306 get { return default_static_constructor; }
2309 protected override bool VerifyClsCompliance ()
2311 if (!base.VerifyClsCompliance ())
2316 Type base_type = TypeBuilder.BaseType;
2317 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2318 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2325 /// Checks whether container name is CLS Compliant
2327 void VerifyClsName ()
2329 Hashtable base_members = base_cache == null ?
2331 base_cache.GetPublicMembers ();
2332 Hashtable this_members = new Hashtable ();
2334 foreach (DictionaryEntry entry in defined_names) {
2335 MemberCore mc = (MemberCore)entry.Value;
2336 if (!mc.IsClsComplianceRequired ())
2339 string name = (string) entry.Key;
2340 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2342 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2343 object found = base_members [lcase];
2344 if (found == null) {
2345 found = this_members [lcase];
2346 if (found == null) {
2347 this_members.Add (lcase, mc);
2352 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2355 if (found is MemberInfo) {
2356 if (basename == ((MemberInfo) found).Name)
2358 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2360 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2363 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2369 /// Performs checks for an explicit interface implementation. First it
2370 /// checks whether the `interface_type' is a base inteface implementation.
2371 /// Then it checks whether `name' exists in the interface type.
2373 public bool VerifyImplements (InterfaceMemberBase mb)
2375 if (ifaces != null) {
2376 foreach (Type t in ifaces){
2377 if (TypeManager.IsEqual (t, mb.InterfaceType))
2382 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2383 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2384 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2388 public override Type LookupAnyGeneric (string typeName)
2390 if (types != null) {
2391 foreach (TypeContainer tc in types) {
2395 int pos = tc.Basename.LastIndexOf ('`');
2396 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2397 return tc.TypeBuilder;
2401 return base.LookupAnyGeneric (typeName);
2404 public void Mark_HasEquals ()
2406 cached_method |= CachedMethods.Equals;
2409 public void Mark_HasGetHashCode ()
2411 cached_method |= CachedMethods.GetHashCode;
2415 /// Method container contains Equals method
2417 public bool HasEquals {
2419 return (cached_method & CachedMethods.Equals) != 0;
2424 /// Method container contains GetHashCode method
2426 public bool HasGetHashCode {
2428 return (cached_method & CachedMethods.GetHashCode) != 0;
2432 public bool HasStaticFieldInitializer {
2434 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2438 cached_method |= CachedMethods.HasStaticFieldInitializer;
2440 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2448 string IMemberContainer.Name {
2454 Type IMemberContainer.Type {
2460 bool IMemberContainer.IsInterface {
2462 return Kind == Kind.Interface;
2466 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2468 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2470 if (GenericType != null)
2471 return TypeManager.FindMembers (GenericType, mt, new_bf,
2474 return FindMembers (mt, new_bf, null, null);
2478 // Generates xml doc comments (if any), and if required,
2479 // handle warning report.
2481 internal override void GenerateDocComment (DeclSpace ds)
2483 DocUtil.GenerateTypeDocComment (this, ds);
2486 public override string DocCommentHeader {
2487 get { return "T:"; }
2490 public MemberCache BaseCache {
2492 if (base_cache != null)
2494 if (TypeBuilder.BaseType != null)
2495 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2496 if (TypeBuilder.IsInterface)
2497 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2503 public abstract class ClassOrStruct : TypeContainer {
2504 ListDictionary declarative_security;
2506 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2507 MemberName name, Attributes attrs, Kind kind)
2508 : base (ns, parent, name, attrs, kind)
2512 protected override bool AddToContainer (MemberCore symbol, string name)
2514 if (name == MemberName.Name && symbol.MemberName.Left == null) {
2515 if (symbol is TypeParameter) {
2516 Report.Error (694, symbol.Location,
2517 "Type parameter `{0}' has same name as containing type, or method",
2518 symbol.GetSignatureForError ());
2522 Report.SymbolRelatedToPreviousError (this);
2523 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2524 symbol.GetSignatureForError ());
2528 return base.AddToContainer (symbol, name);
2531 public override void VerifyMembers ()
2533 base.VerifyMembers ();
2535 if ((events != null) && Report.WarningLevel >= 3) {
2536 foreach (Event e in events){
2537 // Note: The event can be assigned from same class only, so we can report
2538 // this warning for all accessibility modes
2539 if ((e.caching_flags & Flags.IsUsed) == 0)
2540 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2545 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2547 if (a.IsValidSecurityAttribute ()) {
2548 if (declarative_security == null)
2549 declarative_security = new ListDictionary ();
2551 a.ExtractSecurityPermissionSet (declarative_security);
2555 if (a.Type == TypeManager.struct_layout_attribute_type) {
2556 PartialContainer.HasStructLayout = true;
2558 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2559 PartialContainer.HasExplicitLayout = true;
2562 base.ApplyAttributeBuilder (a, cb);
2566 /// Defines the default constructors
2568 protected void DefineDefaultConstructor (bool is_static)
2570 // The default instance constructor is public
2571 // If the class is abstract, the default constructor is protected
2572 // The default static constructor is private
2576 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2578 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2581 Constructor c = new Constructor (this, MemberName.Name, mods,
2582 null, Parameters.EmptyReadOnlyParameters,
2583 new GeneratedBaseInitializer (Location),
2587 c.Block = new ToplevelBlock (Parameters.EmptyReadOnlyParameters, Location);
2590 public override bool Define ()
2592 CheckProtectedModifier ();
2596 if (default_static_constructor != null)
2597 default_static_constructor.Define ();
2602 public override void Emit ()
2604 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2605 DefineDefaultConstructor (true);
2606 default_static_constructor.Define ();
2611 if (declarative_security != null) {
2612 foreach (DictionaryEntry de in declarative_security) {
2613 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2618 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2620 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2623 protected override TypeAttributes TypeAttr {
2625 if (default_static_constructor == null)
2626 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2628 return base.TypeAttr;
2634 // TODO: should be sealed
2635 public class Class : ClassOrStruct {
2636 const int AllowedModifiers =
2639 Modifiers.PROTECTED |
2640 Modifiers.INTERNAL |
2642 Modifiers.ABSTRACT |
2647 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2649 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2651 : base (ns, parent, name, attrs, Kind.Class)
2653 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2654 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2656 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2657 Report.FeatureIsNotAvailable (Location, "static classes");
2661 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2663 if (part.Name == "System.Object")
2664 Report.Error (537, part.Location,
2665 "The class System.Object cannot have a base class or implement an interface.");
2666 base.AddBasesForPart (part, bases);
2669 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2671 if (a.Type == TypeManager.attribute_usage_type) {
2672 if (!TypeManager.IsAttributeType (BaseType) &&
2673 TypeBuilder.FullName != "System.Attribute") {
2674 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2678 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2679 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2683 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2684 !attributes.Contains (TypeManager.guid_attr_type)) {
2685 a.Error_MissingGuidAttribute ();
2689 if (a.Type == TypeManager.extension_attribute_type) {
2690 a.Error_MisusedExtensionAttribute ();
2694 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2697 base.ApplyAttributeBuilder (a, cb);
2700 public override AttributeTargets AttributeTargets {
2702 return AttributeTargets.Class;
2706 protected override void DefineContainerMembers (MemberCoreArrayList list)
2712 base.DefineContainerMembers (list);
2716 foreach (MemberCore m in list) {
2717 if (m is Operator) {
2718 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2722 if (m is Destructor) {
2723 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2728 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2732 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2735 if (m is Constructor) {
2736 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2740 Method method = m as Method;
2741 if (method != null && method.Parameters.HasExtensionMethodType) {
2742 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2746 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2749 base.DefineContainerMembers (list);
2752 public override bool Define ()
2754 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2755 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2758 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2759 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2762 return base.Define ();
2765 protected override bool DoDefineMembers ()
2767 if (InstanceConstructors == null && !IsStatic)
2768 DefineDefaultConstructor (false);
2770 return base.DoDefineMembers ();
2773 public override void Emit ()
2778 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2779 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2783 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2785 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2787 if (base_class == null) {
2788 if (RootContext.StdLib)
2789 base_class = TypeManager.system_object_expr;
2790 else if (Name != "System.Object")
2791 base_class = TypeManager.system_object_expr;
2793 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2795 689, base_class.Location,
2796 "Cannot derive from `{0}' because it is a type parameter",
2797 base_class.GetSignatureForError ());
2801 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2802 Report.Error (698, base_class.Location,
2803 "A generic type cannot derive from `{0}' because it is an attribute class",
2804 base_class.GetSignatureForError ());
2807 if (base_class.IsSealed){
2808 Report.SymbolRelatedToPreviousError (base_class.Type);
2809 if (base_class.Type.IsAbstract) {
2810 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2811 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2813 Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2814 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2819 if (!base_class.CanInheritFrom ()){
2820 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2821 GetSignatureForError (), base_class.GetSignatureForError ());
2825 if (!base_class.AsAccessible (this)) {
2826 Report.SymbolRelatedToPreviousError (base_class.Type);
2827 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2828 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2832 if (PartialContainer.IsStaticClass) {
2833 if (base_class.Type != TypeManager.object_type) {
2834 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2835 GetSignatureForError (), base_class.GetSignatureForError ());
2839 if (ifaces != null) {
2840 foreach (TypeExpr t in ifaces)
2841 Report.SymbolRelatedToPreviousError (t.Type);
2842 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2849 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2850 /// Valid only for attribute classes.
2851 public bool IsExcluded ()
2853 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2854 return (caching_flags & Flags.Excluded) != 0;
2856 caching_flags &= ~Flags.Excluded_Undetected;
2858 if (OptAttributes == null)
2861 if (TypeManager.conditional_attribute_type == null)
2864 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2869 foreach (Attribute a in attrs) {
2870 string condition = a.GetConditionalAttributeValue ();
2871 if (Location.CompilationUnit.IsConditionalDefined (condition))
2875 caching_flags |= Flags.Excluded;
2881 return (ModFlags & Modifiers.STATIC) != 0;
2886 // FIXME: How do we deal with the user specifying a different
2889 protected override TypeAttributes TypeAttr {
2891 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2893 ta |= StaticClassAttribute;
2899 public sealed class Struct : ClassOrStruct {
2901 // Modifiers allowed in a struct declaration
2903 const int AllowedModifiers =
2906 Modifiers.PROTECTED |
2907 Modifiers.INTERNAL |
2911 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2912 int mod, Attributes attrs)
2913 : base (ns, parent, name, attrs, Kind.Struct)
2917 if (parent.Parent == null)
2918 accmods = Modifiers.INTERNAL;
2920 accmods = Modifiers.PRIVATE;
2922 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2924 this.ModFlags |= Modifiers.SEALED;
2927 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2929 base.ApplyAttributeBuilder (a, cb);
2932 // When struct constains fixed fixed and struct layout has explicitly
2933 // set CharSet, its value has to be propagated to compiler generated
2934 // fixed field types
2936 if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
2937 for (int i = 0; i < Fields.Count; ++i) {
2938 FixedField ff = Fields [i] as FixedField;
2940 ff.SetCharSet (TypeBuilder.Attributes);
2945 public override AttributeTargets AttributeTargets {
2947 return AttributeTargets.Struct;
2951 public override bool IsUnmanagedType ()
2956 if (requires_delayed_unmanagedtype_check)
2959 foreach (FieldBase f in fields) {
2960 if ((f.ModFlags & Modifiers.STATIC) != 0)
2963 // It can happen when recursive unmanaged types are defined
2964 // struct S { S* s; }
2965 Type mt = f.MemberType;
2967 requires_delayed_unmanagedtype_check = true;
2971 // TODO: Remove when pointer types are under mcs control
2972 while (mt.IsPointer)
2973 mt = TypeManager.GetElementType (mt);
2974 if (TypeManager.IsEqual (mt, TypeBuilder))
2977 if (TypeManager.IsUnmanagedType (mt))
2986 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2988 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2990 // If we are compiling our runtime,
2991 // and we are defining ValueType, then our
2992 // base is `System.Object'.
2994 if (base_class == null) {
2995 if (!RootContext.StdLib && Name == "System.ValueType")
2996 base_class = TypeManager.system_object_expr;
2998 base_class = TypeManager.system_valuetype_expr;
3005 // FIXME: Allow the user to specify a different set of attributes
3006 // in some cases (Sealed for example is mandatory for a class,
3007 // but what SequentialLayout can be changed
3009 protected override TypeAttributes TypeAttr {
3011 const TypeAttributes DefaultTypeAttributes =
3012 TypeAttributes.SequentialLayout |
3013 TypeAttributes.Sealed |
3014 TypeAttributes.BeforeFieldInit;
3016 return base.TypeAttr | DefaultTypeAttributes;
3020 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3022 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3023 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3024 field.GetSignatureForError ());
3027 base.RegisterFieldForInitialization (field, expression);
3035 public sealed class Interface : TypeContainer, IMemberContainer {
3038 /// Modifiers allowed in a class declaration
3040 public const int AllowedModifiers =
3043 Modifiers.PROTECTED |
3044 Modifiers.INTERNAL |
3048 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3050 : base (ns, parent, name, attrs, Kind.Interface)
3054 if (parent.Parent == null)
3055 accmods = Modifiers.INTERNAL;
3057 accmods = Modifiers.PRIVATE;
3059 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3062 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3064 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3065 !attributes.Contains (TypeManager.guid_attr_type)) {
3066 a.Error_MissingGuidAttribute ();
3069 base.ApplyAttributeBuilder (a, cb);
3073 public override AttributeTargets AttributeTargets {
3075 return AttributeTargets.Interface;
3079 protected override TypeAttributes TypeAttr {
3081 const TypeAttributes DefaultTypeAttributes =
3082 TypeAttributes.AutoLayout |
3083 TypeAttributes.Abstract |
3084 TypeAttributes.Interface;
3086 return base.TypeAttr | DefaultTypeAttributes;
3090 protected override bool VerifyClsCompliance ()
3092 if (!base.VerifyClsCompliance ())
3095 if (ifaces != null) {
3096 foreach (Type t in ifaces) {
3097 if (AttributeTester.IsClsCompliant (t))
3100 Report.SymbolRelatedToPreviousError (t);
3101 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3102 GetSignatureForError (), TypeManager.CSharpName (t));
3110 // It is used as a base class for all property based members
3111 // This includes properties, indexers, and events
3112 public abstract class PropertyBasedMember : InterfaceMemberBase
3114 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3115 FullNamedExpression type, int mod, int allowed_mod,
3116 MemberName name, Attributes attrs)
3117 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3121 protected override bool VerifyClsCompliance ()
3123 if (!base.VerifyClsCompliance ())
3126 if (!AttributeTester.IsClsCompliant (MemberType)) {
3127 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3128 GetSignatureForError ());
3136 public abstract class MethodCore : InterfaceMemberBase
3138 public readonly Parameters Parameters;
3139 protected ToplevelBlock block;
3141 public MethodCore (DeclSpace parent, GenericMethod generic,
3142 FullNamedExpression type, int mod, int allowed_mod,
3143 MemberName name, Attributes attrs, Parameters parameters)
3144 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3146 Parameters = parameters;
3150 // Returns the System.Type array for the parameters of this method
3152 public Type [] ParameterTypes {
3154 return Parameters.Types;
3158 public Parameters ParameterInfo
3165 public ToplevelBlock Block {
3175 protected override bool CheckBase ()
3177 // Check whether arguments were correct.
3178 if (!DefineParameters (Parameters))
3181 return base.CheckBase ();
3185 // Returns a string that represents the signature for this
3186 // member which should be used in XML documentation.
3188 public override string GetDocCommentName (DeclSpace ds)
3190 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3194 // Raised (and passed an XmlElement that contains the comment)
3195 // when GenerateDocComment is writing documentation expectedly.
3197 // FIXME: with a few effort, it could be done with XmlReader,
3198 // that means removal of DOM use.
3200 internal override void OnGenerateDocComment (XmlElement el)
3202 DocUtil.OnMethodGenerateDocComment (this, el);
3206 // Represents header string for documentation comment.
3208 public override string DocCommentHeader
3210 get { return "M:"; }
3213 public override bool EnableOverloadChecks (MemberCore overload)
3215 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3216 caching_flags |= Flags.MethodOverloadsExist;
3220 return base.EnableOverloadChecks (overload);
3223 protected override bool VerifyClsCompliance ()
3225 if (!base.VerifyClsCompliance ())
3228 if (Parameters.HasArglist) {
3229 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3232 if (!AttributeTester.IsClsCompliant (MemberType)) {
3233 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3234 GetSignatureForError ());
3237 Parameters.VerifyClsCompliance ();
3243 public abstract class InterfaceMemberBase : MemberBase {
3245 // Whether this is an interface member.
3247 public bool IsInterface;
3250 // If true, this is an explicit interface implementation
3252 public bool IsExplicitImpl;
3254 protected bool is_external_implementation;
3257 // The interface type we are explicitly implementing
3259 public Type InterfaceType;
3262 // The method we're overriding if this is an override method.
3264 protected MethodInfo base_method;
3266 readonly int explicit_mod_flags;
3267 public MethodAttributes flags;
3269 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3270 FullNamedExpression type, int mod, int allowed_mod,
3271 MemberName name, Attributes attrs)
3272 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3275 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3276 IsExplicitImpl = (MemberName.Left != null);
3277 explicit_mod_flags = mod;
3280 protected override bool CheckBase ()
3282 if (!base.CheckBase ())
3285 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3286 CheckForDuplications ();
3291 // Is null for System.Object while compiling corlib and base interfaces
3292 if (Parent.PartialContainer.BaseCache == null) {
3293 if ((ModFlags & Modifiers.NEW) != 0) {
3294 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3299 Type base_ret_type = null;
3300 base_method = FindOutBaseMethod (ref base_ret_type);
3302 // method is override
3303 if (base_method != null) {
3304 if (!CheckMethodAgainstBase (base_ret_type))
3307 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3308 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3310 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3311 Report.SymbolRelatedToPreviousError (base_method);
3312 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3313 GetSignatureForError (), TypeManager.CSharpSignature (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 (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3319 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3326 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3327 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3328 if (conflict_symbol != null) {
3329 Report.SymbolRelatedToPreviousError (conflict_symbol);
3331 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3332 else if (this is PropertyBase)
3333 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3335 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3337 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3338 GetSignatureForError (), SimpleName.GetMemberType (this));
3343 if (conflict_symbol == null) {
3344 if ((ModFlags & Modifiers.NEW) != 0) {
3345 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3350 if ((ModFlags & Modifiers.NEW) == 0) {
3351 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3354 Report.SymbolRelatedToPreviousError (conflict_symbol);
3355 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3356 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3362 protected virtual bool CheckForDuplications ()
3364 return Parent.MemberCache.CheckExistingMembersOverloads (
3365 this, GetFullName (MemberName), Parameters.EmptyReadOnlyParameters);
3369 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3370 // that have been defined.
3372 // `name' is the user visible name for reporting errors (this is used to
3373 // provide the right name regarding method names and properties)
3375 bool CheckMethodAgainstBase (Type base_method_type)
3379 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3380 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3381 Report.SymbolRelatedToPreviousError (base_method);
3382 Report.Error (506, Location,
3383 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3384 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3388 // Now we check that the overriden method is not final
3390 if (base_method.IsFinal) {
3391 Report.SymbolRelatedToPreviousError (base_method);
3392 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3393 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3397 // Check that the permissions are not being changed
3399 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3400 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3402 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3403 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3407 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3408 Report.SymbolRelatedToPreviousError (base_method);
3409 if (this is PropertyBasedMember) {
3410 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3411 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3414 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3415 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3421 if ((ModFlags & Modifiers.NEW) == 0) {
3422 if ((ModFlags & Modifiers.OVERRIDE) == 0) {
3423 ModFlags |= Modifiers.NEW;
3424 Report.SymbolRelatedToPreviousError (base_method);
3425 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3426 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",
3427 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3429 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3430 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3434 if (base_method.IsAbstract && !IsInterface) {
3435 Report.SymbolRelatedToPreviousError (base_method);
3436 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3437 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3445 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3447 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3449 // when overriding protected internal, the method can be declared
3450 // protected internal only within the same assembly or assembly
3451 // which has InternalsVisibleTo
3453 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3454 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3455 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3457 // if it's not "protected internal", it must be "protected"
3461 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3463 // protected within the same assembly - an error
3466 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3467 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3469 // protected ok, but other attributes differ - report an error
3475 return (thisp == base_classp);
3479 public override bool Define ()
3482 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3483 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3485 flags = MethodAttributes.Public |
3486 MethodAttributes.Abstract |
3487 MethodAttributes.HideBySig |
3488 MethodAttributes.NewSlot |
3489 MethodAttributes.Virtual;
3491 Parent.PartialContainer.MethodModifiersValid (this);
3493 flags = Modifiers.MethodAttr (ModFlags);
3496 if (IsExplicitImpl) {
3497 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3498 if (iface_texpr == null)
3501 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3502 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3503 GetSignatureForError ());
3506 InterfaceType = iface_texpr.Type;
3508 if (!InterfaceType.IsInterface) {
3509 Report.SymbolRelatedToPreviousError (InterfaceType);
3510 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3511 TypeManager.CSharpName (InterfaceType));
3513 Parent.PartialContainer.VerifyImplements (this);
3516 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3519 return base.Define ();
3522 protected bool DefineParameters (Parameters parameters)
3524 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3526 if (!parameters.Resolve (rc))
3530 for (int i = 0; i < parameters.Count; ++i) {
3531 Parameter p = parameters [i];
3532 if (p.CheckAccessibility (this))
3535 Type t = parameters.Types [i];
3536 Report.SymbolRelatedToPreviousError (t);
3537 if (this is Indexer)
3538 Report.Error (55, Location,
3539 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3540 TypeManager.CSharpName (t), GetSignatureForError ());
3541 else if (this is Operator)
3542 Report.Error (57, Location,
3543 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3544 TypeManager.CSharpName (t), GetSignatureForError ());
3546 Report.Error (51, Location,
3547 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3548 TypeManager.CSharpName (t), GetSignatureForError ());
3554 public override void Emit()
3556 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3557 // We are more strict than Microsoft and report CS0626 as error
3558 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3559 Report.Error (626, Location,
3560 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3561 GetSignatureForError ());
3567 public override bool EnableOverloadChecks (MemberCore overload)
3570 // Two members can differ in their explicit interface
3571 // type parameter only
3573 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3574 if (imb != null && imb.IsExplicitImpl) {
3575 if (IsExplicitImpl) {
3576 caching_flags |= Flags.MethodOverloadsExist;
3581 return IsExplicitImpl;
3584 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3586 Report.SymbolRelatedToPreviousError (base_method);
3587 string base_name = TypeManager.GetFullNameSignature (base_method);
3588 string this_name = GetSignatureForError ();
3589 if (suffix != null) {
3590 base_name += suffix;
3591 this_name += suffix;
3594 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3595 this_name, Modifiers.GetDescription (ma), base_name);
3598 protected static string Error722 {
3600 return "`{0}': static types cannot be used as return types";
3605 /// Gets base method and its return type
3607 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3610 // The "short" name of this property / indexer / event. This is the
3611 // name without the explicit interface.
3613 public string ShortName
3615 get { return MemberName.Name; }
3616 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3620 // Returns full metadata method name
3622 public string GetFullName (MemberName name)
3624 if (!IsExplicitImpl)
3628 // When dealing with explicit members a full interface type
3629 // name is added to member name to avoid possible name conflicts
3631 // We use CSharpName which gets us full name with benefit of
3632 // replacing predefined names which saves some space and name
3635 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3638 protected override bool VerifyClsCompliance ()
3640 if (!base.VerifyClsCompliance ()) {
3641 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3642 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3645 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3646 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3651 if (GenericMethod != null)
3652 GenericMethod.VerifyClsCompliance ();
3657 public override bool IsUsed
3659 get { return IsExplicitImpl || base.IsUsed; }
3664 public abstract class MethodOrOperator : MethodCore, IMethodData
3666 public MethodBuilder MethodBuilder;
3667 ReturnParameter return_attributes;
3668 ListDictionary declarative_security;
3669 protected MethodData MethodData;
3671 static string[] attribute_targets = new string [] { "method", "return" };
3673 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3674 int allowed_mod, MemberName name,
3675 Attributes attrs, Parameters parameters)
3676 : base (parent, generic, type, mod, allowed_mod, name,
3681 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3683 if (a.Target == AttributeTargets.ReturnValue) {
3684 if (return_attributes == null)
3685 return_attributes = new ReturnParameter (MethodBuilder, Location);
3687 return_attributes.ApplyAttributeBuilder (a, cb);
3691 if (a.IsInternalMethodImplAttribute) {
3692 is_external_implementation = true;
3695 if (a.Type == TypeManager.dllimport_type) {
3696 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3697 if ((ModFlags & extern_static) != extern_static) {
3698 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3700 is_external_implementation = true;
3703 if (a.IsValidSecurityAttribute ()) {
3704 if (declarative_security == null)
3705 declarative_security = new ListDictionary ();
3706 a.ExtractSecurityPermissionSet (declarative_security);
3710 if (MethodBuilder != null)
3711 MethodBuilder.SetCustomAttribute (cb);
3714 public override AttributeTargets AttributeTargets {
3716 return AttributeTargets.Method;
3720 protected override bool CheckForDuplications ()
3722 string name = GetFullName (MemberName);
3723 if (MemberName.IsGeneric)
3724 name = MemberName.MakeName (name, MemberName.TypeArguments);
3726 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3729 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3731 return new EmitContext (
3732 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3735 protected override bool ResolveMemberType ()
3738 if (GenericMethod != null) {
3739 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3740 if (!GenericMethod.Define (this))
3745 return base.ResolveMemberType ();
3748 public override bool Define ()
3750 if (!base.Define ())
3756 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3758 // Current method is turned into automatically generated
3759 // wrapper which creates an instance of iterator
3761 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3762 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3765 if (IsPartialDefinition) {
3766 caching_flags &= ~Flags.Excluded_Undetected;
3767 caching_flags |= Flags.Excluded;
3768 // Add to member cache only when a partial method implementation is not there
3769 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3770 MethodBase mb = new PartialMethodDefinitionInfo (this);
3771 Parent.MemberCache.AddMember (mb, this);
3772 TypeManager.AddMethod (mb, this);
3778 MethodData = new MethodData (
3779 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3781 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3784 MethodBuilder = MethodData.MethodBuilder;
3787 if (MethodBuilder.IsGenericMethod)
3788 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3791 Parent.MemberCache.AddMember (MethodBuilder, this);
3796 protected override void DoMemberTypeIndependentChecks ()
3798 base.DoMemberTypeIndependentChecks ();
3800 CheckAbstractAndExtern (block != null);
3802 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3803 for (int i = 0; i < Parameters.Count; ++i) {
3804 if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3805 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3806 GetSignatureForError ());
3813 protected override void DoMemberTypeDependentChecks ()
3815 base.DoMemberTypeDependentChecks ();
3817 if (!TypeManager.IsGenericParameter (MemberType)) {
3818 if (MemberType.IsAbstract && MemberType.IsSealed) {
3819 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3824 public override void Emit ()
3827 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3828 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3829 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3830 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3832 if (OptAttributes != null)
3833 OptAttributes.Emit ();
3835 if (declarative_security != null) {
3836 foreach (DictionaryEntry de in declarative_security) {
3837 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3841 if (MethodData != null)
3842 MethodData.Emit (Parent);
3850 protected void Error_ConditionalAttributeIsNotValid ()
3852 Report.Error (577, Location,
3853 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3854 GetSignatureForError ());
3857 public bool IsPartialDefinition {
3859 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3863 public bool IsPartialImplementation {
3865 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3869 public override string[] ValidAttributeTargets {
3871 return attribute_targets;
3875 #region IMethodData Members
3877 public CallingConventions CallingConventions {
3879 CallingConventions cc = Parameters.CallingConvention;
3881 if ((ModFlags & Modifiers.STATIC) == 0)
3882 cc |= CallingConventions.HasThis;
3884 // FIXME: How is `ExplicitThis' used in C#?
3890 public Type ReturnType {
3896 public MemberName MethodName {
3903 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3905 public bool IsExcluded () {
3906 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3907 return (caching_flags & Flags.Excluded) != 0;
3909 caching_flags &= ~Flags.Excluded_Undetected;
3911 if (base_method == null) {
3912 if (OptAttributes == null)
3915 if (TypeManager.conditional_attribute_type == null)
3918 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3923 foreach (Attribute a in attrs) {
3924 string condition = a.GetConditionalAttributeValue ();
3925 if (condition == null)
3928 if (Location.CompilationUnit.IsConditionalDefined (condition))
3932 caching_flags |= Flags.Excluded;
3936 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3938 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3939 caching_flags |= Flags.Excluded;
3945 if (md.IsExcluded ()) {
3946 caching_flags |= Flags.Excluded;
3952 GenericMethod IMethodData.GenericMethod {
3954 return GenericMethod;
3958 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3965 public class SourceMethod : IMethodDef
3968 SourceMethodBuilder builder;
3970 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3972 this.method = method;
3974 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3977 public string Name {
3978 get { return method.Name; }
3983 if (method is MethodBuilder)
3984 return ((MethodBuilder) method).GetToken ().Token;
3985 else if (method is ConstructorBuilder)
3986 return ((ConstructorBuilder) method).GetToken ().Token;
3988 throw new NotSupportedException ();
3992 public void CloseMethod ()
3994 SymbolWriter.CloseMethod ();
3997 public void SetRealMethodName (string name)
3999 if (builder != null)
4000 builder.SetRealMethodName (name);
4003 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4005 if (!SymbolWriter.HasSymbolWriter)
4010 Location start_loc = block.StartLocation;
4011 if (start_loc.IsNull)
4014 ICompileUnit compile_unit = start_loc.CompilationUnit;
4015 if (compile_unit == null)
4018 return new SourceMethod (parent, method, compile_unit);
4022 public class Method : MethodOrOperator {
4025 /// Modifiers allowed in a class declaration
4027 const int AllowedModifiers =
4030 Modifiers.PROTECTED |
4031 Modifiers.INTERNAL |
4036 Modifiers.OVERRIDE |
4037 Modifiers.ABSTRACT |
4041 const int AllowedInterfaceModifiers =
4042 Modifiers.NEW | Modifiers.UNSAFE;
4044 public Method (DeclSpace parent, GenericMethod generic,
4045 FullNamedExpression return_type, int mod,
4046 MemberName name, Parameters parameters, Attributes attrs)
4047 : base (parent, generic, return_type, mod,
4048 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4049 name, attrs, parameters)
4053 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4054 MemberName name, Parameters parameters, Attributes attrs)
4055 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4059 public override string GetSignatureForError()
4061 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4064 static void Error_DuplicateEntryPoint (Method b)
4066 Report.Error (17, b.Location,
4067 "Program `{0}' has more than one entry point defined: `{1}'",
4068 CodeGen.FileName, b.GetSignatureForError ());
4071 bool IsEntryPoint ()
4073 if (ReturnType != TypeManager.void_type &&
4074 ReturnType != TypeManager.int32_type)
4077 if (Parameters.Count == 0)
4080 if (Parameters.Count > 1)
4083 Type t = Parameters.Types [0];
4084 return t.IsArray && t.GetArrayRank () == 1 &&
4085 TypeManager.GetElementType (t) == TypeManager.string_type &&
4086 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4089 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4091 if (a.Type == TypeManager.conditional_attribute_type) {
4092 if (IsExplicitImpl) {
4093 Error_ConditionalAttributeIsNotValid ();
4097 if (ReturnType != TypeManager.void_type) {
4098 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4102 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4103 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4108 Report.Error (582, Location, "Conditional not valid on interface members");
4112 if (MethodData.implementing != null) {
4113 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4114 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4115 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4119 for (int i = 0; i < Parameters.Count; ++i) {
4120 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4121 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4127 if (a.Type == TypeManager.extension_attribute_type) {
4128 a.Error_MisusedExtensionAttribute ();
4132 base.ApplyAttributeBuilder (a, cb);
4135 protected override bool CheckForDuplications ()
4137 if (!base.CheckForDuplications ())
4140 ArrayList ar = Parent.PartialContainer.Properties;
4142 for (int i = 0; i < ar.Count; ++i) {
4143 PropertyBase pb = (PropertyBase) ar [i];
4144 if (pb.AreAccessorsDuplicateImplementation (this))
4149 ar = Parent.PartialContainer.Indexers;
4151 for (int i = 0; i < ar.Count; ++i) {
4152 PropertyBase pb = (PropertyBase) ar [i];
4153 if (pb.AreAccessorsDuplicateImplementation (this))
4161 protected override bool CheckBase ()
4163 if (!base.CheckBase ())
4166 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
4167 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
4168 TypeManager.CSharpSignature (base_method));
4177 public override bool Define ()
4179 if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
4180 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4183 if (!base.Define ())
4186 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4187 Error1599 (Location, ReturnType);
4191 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4192 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4193 Parent.PartialContainer.Mark_HasEquals ();
4194 else if (Parameters.IsEmpty && Name == "GetHashCode")
4195 Parent.PartialContainer.Mark_HasGetHashCode ();
4198 if ((ModFlags & Modifiers.STATIC) == 0)
4201 if (Parameters.HasExtensionMethodType) {
4202 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4203 if (!Parent.IsTopLevel)
4204 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4205 GetSignatureForError ());
4207 if (TypeManager.extension_attribute_type == null) {
4208 Report.Error (1110, Location,
4209 "`{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",
4210 GetSignatureForError ());
4211 } else if (TypeManager.extension_attribute_attr == null) {
4212 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4213 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4216 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4219 ModFlags |= Modifiers.METHOD_EXTENSION;
4220 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4221 CodeGen.Assembly.HasExtensionMethods = true;
4223 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4224 GetSignatureForError ());
4229 // This is used to track the Entry Point,
4231 if (RootContext.NeedsEntryPoint &&
4233 (RootContext.MainClass == null ||
4234 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4235 if (IsEntryPoint ()) {
4237 if (RootContext.EntryPoint == null) {
4238 if (Parent.IsGeneric || MemberName.IsGeneric) {
4239 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4240 GetSignatureForError ());
4242 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4243 md.SetMemberIsUsed ();
4245 RootContext.EntryPoint = this;
4248 Error_DuplicateEntryPoint (RootContext.EntryPoint);
4249 Error_DuplicateEntryPoint (this);
4252 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4253 GetSignatureForError ());
4263 public override void Emit ()
4266 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4267 if (IsPartialDefinition) {
4269 // Do attribute checks only when partial implementation does not exist
4271 if (MethodBuilder == null)
4277 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4278 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4279 GetSignatureForError ());
4284 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4285 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4289 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4290 Location, MethodBuilder);
4295 public override bool EnableOverloadChecks (MemberCore overload)
4297 // TODO: It can be deleted when members will be defined in correct order
4298 if (overload is Operator)
4299 return overload.EnableOverloadChecks (this);
4301 if (overload is Indexer)
4304 return base.EnableOverloadChecks (overload);
4307 public static void Error1599 (Location loc, Type t)
4309 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4312 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4314 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4315 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4320 if (mi.IsSpecialName)
4323 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4327 public void SetPartialDefinition (Method methodDefinition)
4329 caching_flags |= Flags.PartialDefinitionExists;
4330 methodDefinition.MethodBuilder = MethodBuilder;
4331 if (methodDefinition.attributes == null)
4334 if (attributes == null) {
4335 attributes = methodDefinition.attributes;
4337 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4341 protected override bool VerifyClsCompliance ()
4343 if (!base.VerifyClsCompliance ())
4346 if (ParameterInfo.Count > 0) {
4347 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4349 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4356 public abstract class ConstructorInitializer : ExpressionStatement
4358 ArrayList argument_list;
4359 MethodGroupExpr base_constructor_group;
4361 public ConstructorInitializer (ArrayList argument_list, Location loc)
4363 this.argument_list = argument_list;
4367 public ArrayList Arguments {
4369 return argument_list;
4373 public override Expression CreateExpressionTree (EmitContext ec)
4375 throw new NotSupportedException ("ET");
4378 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4380 if (argument_list != null){
4381 foreach (Argument a in argument_list){
4382 if (!a.Resolve (ec, loc))
4387 if (this is ConstructorBaseInitializer) {
4388 if (ec.ContainerType.BaseType == null)
4391 type = ec.ContainerType.BaseType;
4392 if (TypeManager.IsStruct (ec.ContainerType)) {
4393 Report.Error (522, loc,
4394 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4399 // It is legal to have "this" initializers that take no arguments
4400 // in structs, they are just no-ops.
4402 // struct D { public D (int a) : this () {}
4404 if (TypeManager.IsStruct (ec.ContainerType) && argument_list == null)
4407 type = ec.ContainerType;
4410 base_constructor_group = MemberLookupFinal (
4411 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4412 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4413 loc) as MethodGroupExpr;
4415 if (base_constructor_group == null)
4418 base_constructor_group = base_constructor_group.OverloadResolve (
4419 ec, ref argument_list, false, loc);
4421 if (base_constructor_group == null)
4424 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4426 if (base_ctor == caller_builder){
4427 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4433 public override Expression DoResolve (EmitContext ec)
4435 throw new NotSupportedException ();
4438 public override void Emit (EmitContext ec)
4440 // It can be null for static initializers
4441 if (base_constructor_group == null)
4446 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4448 base_constructor_group.EmitCall (ec, argument_list);
4451 public override void EmitStatement (EmitContext ec)
4457 public class ConstructorBaseInitializer : ConstructorInitializer {
4458 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4459 base (argument_list, l)
4464 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4465 public GeneratedBaseInitializer (Location loc):
4471 public class ConstructorThisInitializer : ConstructorInitializer {
4472 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4473 base (argument_list, l)
4478 public class Constructor : MethodCore, IMethodData {
4479 public ConstructorBuilder ConstructorBuilder;
4480 public ConstructorInitializer Initializer;
4481 ListDictionary declarative_security;
4482 bool has_compliant_args;
4485 // Modifiers allowed for a constructor.
4487 public const int AllowedModifiers =
4489 Modifiers.PROTECTED |
4490 Modifiers.INTERNAL |
4496 static readonly string[] attribute_targets = new string [] { "method" };
4499 // The spec claims that static is not permitted, but
4500 // my very own code has static constructors.
4502 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, Parameters args,
4503 ConstructorInitializer init, Location loc)
4504 : base (parent, null, null, mod, AllowedModifiers,
4505 new MemberName (name, loc), attrs, args)
4510 public bool HasCompliantArgs {
4511 get { return has_compliant_args; }
4514 public override AttributeTargets AttributeTargets {
4515 get { return AttributeTargets.Constructor; }
4519 // Returns true if this is a default constructor
4521 public bool IsDefault ()
4523 if ((ModFlags & Modifiers.STATIC) != 0)
4524 return Parameters.IsEmpty;
4526 return Parameters.IsEmpty &&
4527 (Initializer is ConstructorBaseInitializer) &&
4528 (Initializer.Arguments == null);
4531 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4533 if (a.IsValidSecurityAttribute ()) {
4534 if (declarative_security == null) {
4535 declarative_security = new ListDictionary ();
4537 a.ExtractSecurityPermissionSet (declarative_security);
4541 if (a.IsInternalMethodImplAttribute) {
4542 is_external_implementation = true;
4545 ConstructorBuilder.SetCustomAttribute (cb);
4548 protected override bool CheckBase ()
4550 if ((ModFlags & Modifiers.STATIC) != 0) {
4551 if (!Parameters.IsEmpty) {
4552 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4553 GetSignatureForError ());
4557 // the rest can be ignored
4561 // Check whether arguments were correct.
4562 if (!DefineParameters (Parameters))
4565 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4566 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4569 if (Parent.PartialContainer.Kind == Kind.Struct) {
4570 if (Parameters.Count == 0) {
4571 Report.Error (568, Location,
4572 "Structs cannot contain explicit parameterless constructors");
4577 CheckProtectedModifier ();
4583 // Creates the ConstructorBuilder
4585 public override bool Define ()
4587 if (ConstructorBuilder != null)
4590 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4591 MethodAttributes.SpecialName);
4593 if ((ModFlags & Modifiers.STATIC) != 0) {
4594 ca |= MethodAttributes.Static | MethodAttributes.Private;
4596 ca |= MethodAttributes.HideBySig;
4598 if ((ModFlags & Modifiers.PUBLIC) != 0)
4599 ca |= MethodAttributes.Public;
4600 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4601 if ((ModFlags & Modifiers.INTERNAL) != 0)
4602 ca |= MethodAttributes.FamORAssem;
4604 ca |= MethodAttributes.Family;
4605 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4606 ca |= MethodAttributes.Assembly;
4608 ca |= MethodAttributes.Private;
4611 if (!CheckAbstractAndExtern (block != null))
4614 // Check if arguments were correct.
4618 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4619 ca, CallingConventions,
4620 Parameters.GetEmitTypes ());
4622 if (Parent.PartialContainer.IsComImport) {
4623 if (!IsDefault ()) {
4624 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4625 Parent.GetSignatureForError ());
4627 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4630 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4631 TypeManager.AddMethod (ConstructorBuilder, this);
4633 // It's here only to report an error
4634 if (block != null && block.IsIterator) {
4635 member_type = TypeManager.void_type;
4636 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4645 public override void Emit ()
4647 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4648 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4650 if (OptAttributes != null)
4651 OptAttributes.Emit ();
4655 EmitContext ec = CreateEmitContext (null, null);
4658 // If we use a "this (...)" constructor initializer, then
4659 // do not emit field initializers, they are initialized in the other constructor
4661 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4662 !(Initializer is ConstructorThisInitializer);
4664 if (emit_field_initializers)
4665 Parent.PartialContainer.ResolveFieldInitializers (ec);
4667 if (block != null) {
4668 // If this is a non-static `struct' constructor and doesn't have any
4669 // initializer, it must initialize all of the struct's fields.
4670 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4671 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4672 block.AddThisVariable (Parent, Location);
4674 if (!block.ResolveMeta (ec, ParameterInfo))
4677 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4678 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4679 Initializer = new GeneratedBaseInitializer (Location);
4682 // Spec mandates that Initializers will not have `this' access
4684 if (Initializer != null) {
4686 Initializer.Resolve (ConstructorBuilder, ec);
4687 ec.IsStatic = false;
4688 block.AddScopeStatement (new StatementExpression (Initializer));
4693 Parameters.ApplyAttributes (ConstructorBuilder);
4695 SourceMethod source = null;
4697 ec.OmitDebuggingInfo = true;
4699 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4701 bool unreachable = false;
4702 if (block != null) {
4703 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4706 ec.EmitMeta (block);
4708 if (Report.Errors > 0)
4711 ec.EmitResolvedTopBlock (block, unreachable);
4715 source.CloseMethod ();
4717 if (declarative_security != null) {
4718 foreach (DictionaryEntry de in declarative_security) {
4719 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4726 // Is never override
4727 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4732 public override string GetSignatureForError()
4734 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4737 public override string[] ValidAttributeTargets {
4739 return attribute_targets;
4743 protected override bool VerifyClsCompliance ()
4745 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4749 if (ParameterInfo.Count > 0) {
4750 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4752 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4754 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4755 foreach (Type param in Parameters.Types) {
4756 if (param.IsArray) {
4762 has_compliant_args = true;
4766 #region IMethodData Members
4768 public System.Reflection.CallingConventions CallingConventions {
4770 CallingConventions cc = Parameters.CallingConvention;
4772 if (Parent.PartialContainer.Kind == Kind.Class)
4773 if ((ModFlags & Modifiers.STATIC) == 0)
4774 cc |= CallingConventions.HasThis;
4776 // FIXME: How is `ExplicitThis' used in C#?
4782 public MemberName MethodName {
4788 public Type ReturnType {
4794 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4796 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4797 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4798 ec.CurrentBlock = block;
4802 public bool IsExcluded()
4807 GenericMethod IMethodData.GenericMethod {
4813 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4820 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4822 public interface IMethodData
4824 CallingConventions CallingConventions { get; }
4825 Location Location { get; }
4826 MemberName MethodName { get; }
4827 Type ReturnType { get; }
4828 GenericMethod GenericMethod { get; }
4829 Parameters ParameterInfo { get; }
4831 Attributes OptAttributes { get; }
4832 ToplevelBlock Block { get; set; }
4834 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4835 ObsoleteAttribute GetObsoleteAttribute ();
4836 string GetSignatureForError ();
4838 bool IsClsComplianceRequired ();
4839 void SetMemberIsUsed ();
4840 void EmitExtraSymbolInfo (SourceMethod source);
4844 // Encapsulates most of the Method's state
4846 public class MethodData {
4848 static FieldInfo methodbuilder_attrs_field;
4850 public readonly IMethodData method;
4852 public readonly GenericMethod GenericMethod;
4855 // Are we implementing an interface ?
4857 public MethodInfo implementing;
4862 protected InterfaceMemberBase member;
4863 protected int modifiers;
4864 protected MethodAttributes flags;
4865 protected Type declaring_type;
4866 protected MethodInfo parent_method;
4868 MethodBuilder builder = null;
4869 public MethodBuilder MethodBuilder {
4875 public Type DeclaringType {
4877 return declaring_type;
4881 public MethodData (InterfaceMemberBase member,
4882 int modifiers, MethodAttributes flags, IMethodData method)
4884 this.member = member;
4885 this.modifiers = modifiers;
4888 this.method = method;
4891 public MethodData (InterfaceMemberBase member,
4892 int modifiers, MethodAttributes flags,
4893 IMethodData method, MethodBuilder builder,
4894 GenericMethod generic, MethodInfo parent_method)
4895 : this (member, modifiers, flags, method)
4897 this.builder = builder;
4898 this.GenericMethod = generic;
4899 this.parent_method = parent_method;
4902 public bool Define (DeclSpace parent, string method_full_name)
4904 string name = method.MethodName.Basename;
4906 TypeContainer container = parent.PartialContainer;
4908 PendingImplementation pending = container.PendingImplementations;
4909 if (pending != null){
4910 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4912 if (member.InterfaceType != null){
4913 if (implementing == null){
4914 if (member is PropertyBase) {
4915 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4916 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4917 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4920 Report.Error (539, method.Location,
4921 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4922 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4926 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4927 Report.SymbolRelatedToPreviousError (implementing);
4928 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4929 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4933 if (implementing != null) {
4934 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4935 if (prop_method == null) {
4936 if (TypeManager.IsSpecialMethod (implementing)) {
4937 Report.SymbolRelatedToPreviousError (implementing);
4938 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4939 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4940 implementing.Name.StartsWith ("get_") ? "get" : "set");
4942 } else if (implementing.DeclaringType.IsInterface) {
4943 if (!implementing.IsSpecialName) {
4944 Report.SymbolRelatedToPreviousError (implementing);
4945 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4946 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4949 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4950 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4951 Report.SymbolRelatedToPreviousError (implementing);
4952 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4953 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4962 // For implicit implementations, make sure we are public, for
4963 // explicit implementations, make sure we are private.
4965 if (implementing != null){
4967 // Setting null inside this block will trigger a more
4968 // verbose error reporting for missing interface implementations
4970 // The "candidate" function has been flagged already
4971 // but it wont get cleared
4973 if (member.IsExplicitImpl){
4974 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4975 Report.SymbolRelatedToPreviousError (implementing);
4976 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4977 method.GetSignatureForError ());
4981 if (implementing.DeclaringType.IsInterface) {
4983 // If this is an interface method implementation,
4984 // check for public accessibility
4986 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4988 implementing = null;
4990 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4991 // We may never be private.
4992 implementing = null;
4994 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4996 // We may be protected if we're overriding something.
4998 implementing = null;
5003 // Static is not allowed
5005 if ((modifiers & Modifiers.STATIC) != 0){
5006 implementing = null;
5011 // If implementing is still valid, set flags
5013 if (implementing != null){
5015 // When implementing interface methods, set NewSlot
5016 // unless, we are overwriting a method.
5018 if (implementing.DeclaringType.IsInterface){
5019 if ((modifiers & Modifiers.OVERRIDE) == 0)
5020 flags |= MethodAttributes.NewSlot;
5023 MethodAttributes.Virtual |
5024 MethodAttributes.HideBySig;
5026 // Set Final unless we're virtual, abstract or already overriding a method.
5027 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5028 flags |= MethodAttributes.Final;
5031 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5033 if (builder == null)
5036 if (container.CurrentType != null)
5037 declaring_type = container.CurrentType;
5039 declaring_type = container.TypeBuilder;
5041 if (implementing != null && member.IsExplicitImpl) {
5042 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5045 TypeManager.AddMethod (builder, method);
5047 if (GenericMethod != null) {
5048 bool is_override = member.IsExplicitImpl |
5049 ((modifiers & Modifiers.OVERRIDE) != 0);
5051 if (implementing != null)
5052 parent_method = implementing;
5054 EmitContext ec = method.CreateEmitContext (container, null);
5055 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5064 /// Create the MethodBuilder for the method
5066 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5068 if (builder == null) {
5069 builder = container.TypeBuilder.DefineMethod (
5070 method_name, flags, method.CallingConventions,
5071 method.ReturnType, param.GetEmitTypes ());
5077 // Generic method has been already defined to resolve method parameters
5078 // correctly when they use type parameters
5080 builder.SetParameters (param.GetEmitTypes ());
5081 builder.SetReturnType (method.ReturnType);
5083 if (builder.Attributes != flags) {
5085 if (methodbuilder_attrs_field == null)
5086 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5087 methodbuilder_attrs_field.SetValue (builder, flags);
5089 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5093 throw new InternalErrorException ();
5100 public void Emit (DeclSpace parent)
5102 ToplevelBlock block = method.Block;
5106 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5108 ec = method.CreateEmitContext (parent, null);
5110 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5112 if (GenericMethod != null)
5113 GenericMethod.EmitAttributes ();
5116 // clear the pending implementation flag
5118 if (implementing != null)
5119 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5120 member.InterfaceType, this, member.IsExplicitImpl);
5122 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5124 ec.EmitTopBlock (method, block);
5126 if (source != null) {
5127 method.EmitExtraSymbolInfo (source);
5128 source.CloseMethod ();
5133 public class Destructor : MethodOrOperator
5135 const int AllowedModifiers =
5139 static readonly string[] attribute_targets = new string [] { "method" };
5141 public static readonly string MetadataName = "Finalize";
5143 public Destructor (DeclSpace parent, int mod, Parameters parameters, Attributes attrs, Location l)
5144 : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
5145 new MemberName (MetadataName, l), attrs, parameters)
5147 ModFlags &= ~Modifiers.PRIVATE;
5148 ModFlags |= Modifiers.PROTECTED;
5151 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5153 if (a.Type == TypeManager.conditional_attribute_type) {
5154 Error_ConditionalAttributeIsNotValid ();
5158 base.ApplyAttributeBuilder (a, cb);
5161 protected override bool CheckBase ()
5163 flags |= MethodAttributes.Virtual;
5165 if (!base.CheckBase ())
5168 if (Parent.PartialContainer.BaseCache == null)
5171 Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
5172 if (base_type != null && Block != null) {
5173 MethodGroupExpr method_expr = Expression.MethodLookup (Parent.TypeBuilder, base_type, MetadataName, Location);
5174 if (method_expr == null)
5175 throw new NotImplementedException ();
5177 method_expr.IsBase = true;
5178 method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
5180 ToplevelBlock new_block = new ToplevelBlock (Block.StartLocation);
5181 new_block.EndLocation = Block.EndLocation;
5183 Block finaly_block = new ExplicitBlock (new_block, Location, Location);
5184 Block try_block = new Block (new_block, block);
5187 // 0-size arguments to avoid CS0250 error
5188 // TODO: Should use AddScopeStatement or something else which emits correct
5191 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new ArrayList (0))));
5192 new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
5200 public override string GetSignatureForError ()
5202 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5205 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5210 public override string[] ValidAttributeTargets {
5212 return attribute_targets;
5217 public abstract class MemberBase : MemberCore
5219 protected FullNamedExpression type_name;
5220 protected Type member_type;
5222 public readonly DeclSpace ds;
5223 public readonly GenericMethod GenericMethod;
5225 protected MemberBase (DeclSpace parent, GenericMethod generic,
5226 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5227 MemberName name, Attributes attrs)
5228 : base (parent, name, attrs)
5230 this.ds = generic != null ? generic : (DeclSpace) parent;
5231 this.type_name = type;
5232 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5233 GenericMethod = generic;
5234 if (GenericMethod != null)
5235 GenericMethod.ModFlags = ModFlags;
5239 // Main member define entry
5241 public override bool Define ()
5243 DoMemberTypeIndependentChecks ();
5246 // Returns false only when type resolution failed
5248 if (!ResolveMemberType ())
5251 DoMemberTypeDependentChecks ();
5256 // Any type_name independent checks
5258 protected virtual void DoMemberTypeIndependentChecks ()
5260 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5261 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5262 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5263 GetSignatureForError (), Parent.GetSignatureForError ());
5268 // Any type_name dependent checks
5270 protected virtual void DoMemberTypeDependentChecks ()
5272 // verify accessibility
5273 if (!IsAccessibleAs (MemberType)) {
5274 Report.SymbolRelatedToPreviousError (MemberType);
5275 if (this is Property)
5276 Report.Error (53, Location,
5277 "Inconsistent accessibility: property type `" +
5278 TypeManager.CSharpName (MemberType) + "' is less " +
5279 "accessible than property `" + GetSignatureForError () + "'");
5280 else if (this is Indexer)
5281 Report.Error (54, Location,
5282 "Inconsistent accessibility: indexer return type `" +
5283 TypeManager.CSharpName (MemberType) + "' is less " +
5284 "accessible than indexer `" + GetSignatureForError () + "'");
5285 else if (this is MethodCore) {
5286 if (this is Operator)
5287 Report.Error (56, Location,
5288 "Inconsistent accessibility: return type `" +
5289 TypeManager.CSharpName (MemberType) + "' is less " +
5290 "accessible than operator `" + GetSignatureForError () + "'");
5292 Report.Error (50, Location,
5293 "Inconsistent accessibility: return type `" +
5294 TypeManager.CSharpName (MemberType) + "' is less " +
5295 "accessible than method `" + GetSignatureForError () + "'");
5297 Report.Error (52, Location,
5298 "Inconsistent accessibility: field type `" +
5299 TypeManager.CSharpName (MemberType) + "' is less " +
5300 "accessible than field `" + GetSignatureForError () + "'");
5305 protected bool IsTypePermitted ()
5307 if (TypeManager.IsSpecialType (MemberType)) {
5308 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5314 protected virtual bool CheckBase ()
5316 CheckProtectedModifier ();
5321 public Type MemberType {
5322 get { return member_type; }
5325 protected virtual bool ResolveMemberType ()
5327 if (member_type != null)
5328 throw new InternalErrorException ("Multi-resolve");
5330 IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5331 TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5336 // Replace original type name, error reporting can use fully resolved name
5340 member_type = te.Type;
5346 // Abstract class for all fields
5348 abstract public class FieldBase : MemberBase {
5349 public FieldBuilder FieldBuilder;
5350 public Status status;
5351 protected Expression initializer;
5354 public enum Status : byte {
5355 HAS_OFFSET = 4 // Used by FieldMember.
5358 static readonly string[] attribute_targets = new string [] { "field" };
5360 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5361 int allowed_mod, MemberName name, Attributes attrs)
5362 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5365 if ((mod & Modifiers.ABSTRACT) != 0)
5366 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5369 public override AttributeTargets AttributeTargets {
5371 return AttributeTargets.Field;
5375 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5377 if (a.Type == TypeManager.field_offset_attribute_type) {
5378 status |= Status.HAS_OFFSET;
5380 if (!Parent.PartialContainer.HasExplicitLayout) {
5381 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5385 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5386 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5392 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5393 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5399 if (a.Type == TypeManager.marshal_as_attr_type) {
5400 UnmanagedMarshal marshal = a.GetMarshal (this);
5401 if (marshal != null) {
5402 FieldBuilder.SetMarshal (marshal);
5407 if ((a.HasSecurityAttribute)) {
5408 a.Error_InvalidSecurityParent ();
5412 FieldBuilder.SetCustomAttribute (cb);
5415 protected override bool CheckBase ()
5417 if (!base.CheckBase ())
5420 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5421 if (conflict_symbol == null) {
5422 if ((ModFlags & Modifiers.NEW) != 0) {
5423 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5428 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5429 Report.SymbolRelatedToPreviousError (conflict_symbol);
5430 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5431 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5437 protected override void DoMemberTypeDependentChecks ()
5439 base.DoMemberTypeDependentChecks ();
5441 if (TypeManager.IsGenericParameter (MemberType))
5444 if (MemberType.IsSealed && MemberType.IsAbstract) {
5445 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5453 // Represents header string for documentation comment.
5455 public override string DocCommentHeader {
5456 get { return "F:"; }
5459 public override void Emit ()
5462 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5463 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5466 if (OptAttributes != null) {
5467 OptAttributes.Emit ();
5470 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5471 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5477 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5479 Report.SymbolRelatedToPreviousError (static_class);
5480 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5484 public Expression Initializer {
5486 if (value != null) {
5487 this.initializer = value;
5492 protected virtual bool IsFieldClsCompliant {
5494 if (FieldBuilder == null)
5497 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5501 public override string[] ValidAttributeTargets
5504 return attribute_targets;
5508 protected override bool VerifyClsCompliance ()
5510 if (!base.VerifyClsCompliance ())
5513 if (!IsFieldClsCompliant) {
5514 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5515 GetSignatureForError ());
5520 public void SetAssigned ()
5522 caching_flags |= Flags.IsAssigned;
5526 interface IFixedBuffer
5528 FieldInfo Element { get; }
5529 Type ElementType { get; }
5532 public class FixedFieldExternal: IFixedBuffer
5534 FieldInfo element_field;
5536 public FixedFieldExternal (FieldInfo fi)
5538 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5541 #region IFixedField Members
5543 public FieldInfo Element {
5545 return element_field;
5549 public Type ElementType {
5551 return element_field.FieldType;
5559 /// Fixed buffer implementation
5561 public class FixedField : FieldBase, IFixedBuffer
5563 public const string FixedElementName = "FixedElementField";
5564 static int GlobalCounter = 0;
5565 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5566 static FieldInfo[] fi;
5568 TypeBuilder fixed_buffer_type;
5569 FieldBuilder element;
5570 Expression size_expr;
5572 const int AllowedModifiers =
5575 Modifiers.PROTECTED |
5576 Modifiers.INTERNAL |
5579 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5580 Expression size_expr, Attributes attrs, Location loc):
5581 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5583 if (RootContext.Version < LanguageVersion.ISO_2)
5584 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5586 this.size_expr = size_expr;
5589 public override bool Define()
5591 if (!base.Define ())
5594 if (!TypeManager.IsPrimitiveType (MemberType)) {
5595 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",
5596 GetSignatureForError ());
5599 // Create nested fixed buffer container
5600 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5601 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5602 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5604 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5605 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5607 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5608 Parent.MemberCache.AddMember (FieldBuilder, this);
5609 TypeManager.RegisterFieldBase (FieldBuilder, this);
5614 protected override void DoMemberTypeIndependentChecks ()
5616 base.DoMemberTypeIndependentChecks ();
5618 if (!Parent.IsInUnsafeScope)
5619 Expression.UnsafeError (Location);
5621 if (Parent.PartialContainer.Kind != Kind.Struct) {
5622 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5623 GetSignatureForError ());
5627 public override void Emit()
5629 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5630 Constant c = size_expr.ResolveAsConstant (ec, this);
5634 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5635 if (buffer_size_const == null)
5638 int buffer_size = buffer_size_const.Value;
5640 if (buffer_size <= 0) {
5641 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5645 int type_size = Expression.GetTypeSize (MemberType);
5647 if (buffer_size > int.MaxValue / type_size) {
5648 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5649 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5653 buffer_size *= type_size;
5654 EmitFieldSize (buffer_size);
5658 // Emit compiler generated fixed buffer type attribute
5660 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5662 Type attr_type = TypeManager.CoreLookupType (
5663 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5665 if (attr_type != null) {
5666 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5668 cab = new CustomAttributeBuilder (ci, new object [0]);
5669 TypeManager.unsafe_value_type_attr = cab;
5675 fixed_buffer_type.SetCustomAttribute (cab);
5680 void EmitFieldSize (int buffer_size)
5682 if (TypeManager.struct_layout_attribute_type == null) {
5683 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5684 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5686 if (TypeManager.struct_layout_attribute_type == null)
5691 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5693 object [] fi_val = new object [] { buffer_size };
5695 if (TypeManager.struct_layout_attribute_ctor == null) {
5696 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5697 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5698 if (TypeManager.struct_layout_attribute_ctor == null)
5702 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5703 ctor_args, fi, fi_val);
5704 fixed_buffer_type.SetCustomAttribute (cab);
5707 // Don't emit FixedBufferAttribute attribute for private types
5709 if ((ModFlags & Modifiers.PRIVATE) != 0)
5712 if (TypeManager.fixed_buffer_attr_ctor == null) {
5713 if (TypeManager.fixed_buffer_attr_type == null) {
5714 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5715 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5717 if (TypeManager.fixed_buffer_attr_type == null)
5721 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5722 Location, TypeManager.type_type, TypeManager.int32_type);
5724 if (TypeManager.fixed_buffer_attr_ctor == null)
5728 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5729 FieldBuilder.SetCustomAttribute (cab);
5732 protected override bool IsFieldClsCompliant {
5738 public void SetCharSet (TypeAttributes ta)
5740 TypeAttributes cta = fixed_buffer_type.Attributes;
5741 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5742 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5743 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5744 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5745 else if (cta == 0 && ta != 0)
5746 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5749 void SetTypeBuilderCharSet (TypeAttributes ta)
5751 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5753 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5755 mi.Invoke (fixed_buffer_type, new object [] { ta });
5759 #region IFixedField Members
5761 public FieldInfo Element {
5767 public Type ElementType {
5777 // The Field class is used to represents class/struct fields during parsing.
5779 public class Field : FieldBase {
5781 // Modifiers allowed in a class declaration
5783 const int AllowedModifiers =
5786 Modifiers.PROTECTED |
5787 Modifiers.INTERNAL |
5790 Modifiers.VOLATILE |
5794 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5796 : base (parent, type, mod, AllowedModifiers, name, attrs)
5800 bool CanBeVolatile ()
5802 if (TypeManager.IsReferenceType (MemberType))
5805 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5806 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5807 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5808 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5809 MemberType == TypeManager.float_type)
5812 if (TypeManager.IsEnumType (MemberType))
5818 bool CheckStructLayout (Type type, bool isStatic)
5820 if (TypeManager.IsBuiltinType (type))
5824 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5828 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5829 if (!TypeManager.IsGenericType (type))
5832 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5833 if (!CheckStructLayout (t, false))
5839 Report.Error (523, Location,
5840 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5841 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5845 public override bool Define ()
5847 if (!base.Define ())
5852 Type[] required_modifier = null;
5853 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5854 if (TypeManager.isvolatile_type == null)
5855 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5856 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5858 if (TypeManager.isvolatile_type != null)
5859 required_modifier = new Type [] { TypeManager.isvolatile_type };
5862 FieldBuilder = Parent.TypeBuilder.DefineField (
5863 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5865 FieldBuilder = Parent.TypeBuilder.DefineField (
5866 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5868 Parent.MemberCache.AddMember (FieldBuilder, this);
5869 TypeManager.RegisterFieldBase (FieldBuilder, this);
5871 catch (ArgumentException) {
5872 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5876 if (initializer != null) {
5877 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5878 new FieldInitializer (FieldBuilder, initializer, this));
5880 if (Parent.PartialContainer.Kind == Kind.Struct)
5881 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5887 protected override void DoMemberTypeDependentChecks ()
5889 base.DoMemberTypeDependentChecks ();
5891 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5892 if (!CanBeVolatile ()) {
5893 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5894 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5897 if ((ModFlags & Modifiers.READONLY) != 0) {
5898 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5899 GetSignatureForError ());
5904 public override string GetSignatureForError ()
5906 string s = base.GetSignatureForError ();
5907 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5910 // Undecorate name mangling
5911 int l = s.LastIndexOf ('>');
5912 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5915 protected override bool VerifyClsCompliance ()
5917 if (!base.VerifyClsCompliance ())
5920 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5921 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5929 // `set' and `get' accessors are represented with an Accessor.
5931 public class Accessor {
5933 // Null if the accessor is empty, or a Block if not
5935 public const int AllowedModifiers =
5937 Modifiers.PROTECTED |
5938 Modifiers.INTERNAL |
5941 public ToplevelBlock Block;
5942 public Attributes Attributes;
5943 public Location Location;
5944 public int ModFlags;
5945 public Parameters Parameters;
5947 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5953 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5957 // Ooouh Martin, templates are missing here.
5958 // When it will be possible move here a lot of child code and template method type.
5959 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5960 protected MethodData method_data;
5961 protected ToplevelBlock block;
5962 protected ListDictionary declarative_security;
5964 // The accessor are created event if they are not wanted.
5965 // But we need them because their names are reserved.
5966 // Field says whether accessor will be emited or not
5967 public readonly bool IsDummy;
5969 protected readonly string prefix;
5971 ReturnParameter return_attributes;
5973 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5974 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5976 this.prefix = prefix;
5980 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5982 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5983 accessor.Attributes)
5985 this.prefix = prefix;
5986 this.block = accessor.Block;
5989 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5991 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5994 public void UpdateName (InterfaceMemberBase member)
5996 SetMemberName (SetupName (prefix, member, Location));
5999 #region IMethodData Members
6001 public ToplevelBlock Block {
6011 public CallingConventions CallingConventions {
6013 return CallingConventions.Standard;
6017 public bool IsExcluded ()
6022 GenericMethod IMethodData.GenericMethod {
6028 public MemberName MethodName {
6034 public Type[] ParameterTypes {
6036 return ParameterInfo.Types;
6040 public abstract Parameters ParameterInfo { get ; }
6041 public abstract Type ReturnType { get; }
6042 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6046 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6048 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6049 a.Type == TypeManager.conditional_attribute_type) {
6050 Report.Error (1667, a.Location,
6051 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6052 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6056 if (a.IsValidSecurityAttribute ()) {
6057 if (declarative_security == null)
6058 declarative_security = new ListDictionary ();
6059 a.ExtractSecurityPermissionSet (declarative_security);
6063 if (a.Target == AttributeTargets.Method) {
6064 method_data.MethodBuilder.SetCustomAttribute (cb);
6068 if (a.Target == AttributeTargets.ReturnValue) {
6069 if (return_attributes == null)
6070 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6072 return_attributes.ApplyAttributeBuilder (a, cb);
6076 ApplyToExtraTarget (a, cb);
6079 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6081 throw new NotSupportedException ("You forgot to define special attribute target handling");
6084 // It is not supported for the accessors
6085 public sealed override bool Define()
6087 throw new NotSupportedException ();
6090 public void Emit (DeclSpace parent)
6092 EmitMethod (parent);
6095 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6096 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6097 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6098 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6100 if (OptAttributes != null)
6101 OptAttributes.Emit ();
6103 if (declarative_security != null) {
6104 foreach (DictionaryEntry de in declarative_security) {
6105 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6112 protected virtual void EmitMethod (DeclSpace parent)
6114 method_data.Emit (parent);
6117 public override bool EnableOverloadChecks (MemberCore overload)
6119 // This can only happen with indexers and it will
6120 // be catched as indexer difference
6121 if (overload is AbstractPropertyEventMethod)
6124 if (overload is MethodCore) {
6125 caching_flags |= Flags.MethodOverloadsExist;
6131 public override bool IsClsComplianceRequired()
6136 public bool IsDuplicateImplementation (MethodCore method)
6138 if (!MemberName.Equals (method.MemberName))
6141 Type[] param_types = method.ParameterTypes;
6143 if (param_types == null || param_types.Length != ParameterTypes.Length)
6146 for (int i = 0; i < param_types.Length; i++)
6147 if (param_types [i] != ParameterTypes [i])
6150 Report.SymbolRelatedToPreviousError (method);
6151 Report.Error (82, Location, "A member `{0}' is already reserved",
6152 method.GetSignatureForError ());
6156 public override bool IsUsed
6167 // Represents header string for documentation comment.
6169 public override string DocCommentHeader {
6170 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6173 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6178 // Properties and Indexers both generate PropertyBuilders, we use this to share
6179 // their common bits.
6181 abstract public class PropertyBase : PropertyBasedMember {
6183 public class GetMethod : PropertyMethod
6185 static string[] attribute_targets = new string [] { "method", "return" };
6187 public GetMethod (PropertyBase method):
6188 base (method, "get_")
6192 public GetMethod (PropertyBase method, Accessor accessor):
6193 base (method, accessor, "get_")
6197 public override MethodBuilder Define (DeclSpace parent)
6199 base.Define (parent);
6204 method_data = new MethodData (method, ModFlags, flags, this);
6206 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6209 return method_data.MethodBuilder;
6212 public override Type ReturnType {
6214 return method.MemberType;
6218 public override Parameters ParameterInfo {
6220 return Parameters.EmptyReadOnlyParameters;
6224 public override string[] ValidAttributeTargets {
6226 return attribute_targets;
6231 public class SetMethod : PropertyMethod {
6233 static string[] attribute_targets = new string [] { "method", "param", "return" };
6234 ImplicitParameter param_attr;
6235 protected Parameters parameters;
6237 public SetMethod (PropertyBase method) :
6238 base (method, "set_")
6240 parameters = new Parameters (
6241 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6244 public SetMethod (PropertyBase method, Accessor accessor):
6245 base (method, accessor, "set_")
6247 this.parameters = accessor.Parameters;
6250 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6252 if (a.Target == AttributeTargets.Parameter) {
6253 if (param_attr == null)
6254 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6256 param_attr.ApplyAttributeBuilder (a, cb);
6260 base.ApplyAttributeBuilder (a, cb);
6263 public override Parameters ParameterInfo {
6269 public override MethodBuilder Define (DeclSpace parent)
6271 parameters.Resolve (ResolveContext);
6272 base.Define (parent);
6277 method_data = new MethodData (method, ModFlags, flags, this);
6279 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6282 return method_data.MethodBuilder;
6285 public override Type ReturnType {
6287 return TypeManager.void_type;
6291 public override string[] ValidAttributeTargets {
6293 return attribute_targets;
6298 static string[] attribute_targets = new string [] { "property" };
6300 public abstract class PropertyMethod : AbstractPropertyEventMethod
6302 protected readonly PropertyBase method;
6303 protected MethodAttributes flags;
6305 public PropertyMethod (PropertyBase method, string prefix)
6306 : base (method, prefix)
6308 this.method = method;
6309 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6312 public PropertyMethod (PropertyBase method, Accessor accessor,
6314 : base (method, accessor, prefix)
6316 this.method = method;
6317 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6319 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6320 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6324 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6326 if (a.IsInternalMethodImplAttribute) {
6327 method.is_external_implementation = true;
6330 base.ApplyAttributeBuilder (a, cb);
6333 public override AttributeTargets AttributeTargets {
6335 return AttributeTargets.Method;
6339 public override bool IsClsComplianceRequired ()
6341 return method.IsClsComplianceRequired ();
6344 public virtual MethodBuilder Define (DeclSpace parent)
6346 CheckForDuplications ();
6349 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6350 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6351 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6353 Report.SymbolRelatedToPreviousError (mi);
6354 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6355 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6361 TypeContainer container = parent.PartialContainer;
6364 // Check for custom access modifier
6366 if ((ModFlags & Modifiers.Accessibility) == 0) {
6367 ModFlags |= method.ModFlags;
6368 flags = method.flags;
6370 if (container.Kind == Kind.Interface)
6371 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6372 GetSignatureForError ());
6374 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6375 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6378 CheckModifiers (ModFlags);
6379 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6380 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6381 flags = Modifiers.MethodAttr (ModFlags);
6382 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6385 CheckAbstractAndExtern (block != null);
6387 if (block != null && block.IsIterator)
6388 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6393 public bool HasCustomAccessModifier {
6395 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6399 public PropertyBase Property {
6405 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6407 return new EmitContext (this,
6408 ds, method.ds, method.Location, ig, ReturnType,
6409 method.ModFlags, false);
6412 public override ObsoleteAttribute GetObsoleteAttribute ()
6414 return method.GetObsoleteAttribute ();
6417 public override string GetSignatureForError()
6419 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6422 void CheckModifiers (int modflags)
6424 modflags &= Modifiers.Accessibility;
6426 int mflags = method.ModFlags & Modifiers.Accessibility;
6428 if ((mflags & Modifiers.PUBLIC) != 0) {
6429 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6431 else if ((mflags & Modifiers.PROTECTED) != 0) {
6432 if ((mflags & Modifiers.INTERNAL) != 0)
6433 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6435 flags |= Modifiers.PRIVATE;
6437 else if ((mflags & Modifiers.INTERNAL) != 0)
6438 flags |= Modifiers.PRIVATE;
6440 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6441 Report.Error (273, Location,
6442 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6443 GetSignatureForError (), method.GetSignatureForError ());
6447 protected bool CheckForDuplications ()
6449 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6452 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6456 public PropertyMethod Get, Set;
6457 public PropertyBuilder PropertyBuilder;
6458 public MethodBuilder GetBuilder, SetBuilder;
6460 protected bool define_set_first = false;
6462 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6463 int allowed_mod, MemberName name,
6464 Attributes attrs, bool define_set_first)
6465 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6467 this.define_set_first = define_set_first;
6470 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6472 if (a.HasSecurityAttribute) {
6473 a.Error_InvalidSecurityParent ();
6477 PropertyBuilder.SetCustomAttribute (cb);
6480 public override AttributeTargets AttributeTargets {
6482 return AttributeTargets.Property;
6486 protected override void DoMemberTypeDependentChecks ()
6488 base.DoMemberTypeDependentChecks ();
6492 if (MemberType.IsGenericParameter)
6496 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6497 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6501 protected override void DoMemberTypeIndependentChecks ()
6503 base.DoMemberTypeIndependentChecks ();
6506 // Accessors modifiers check
6508 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6509 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6510 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6511 GetSignatureForError ());
6514 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6515 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6516 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6517 Report.Error (276, Location,
6518 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6519 GetSignatureForError ());
6525 GetBuilder = Get.Define (Parent);
6526 return (Get.IsDummy) ? true : GetBuilder != null;
6529 bool DefineSet (bool define)
6534 SetBuilder = Set.Define (Parent);
6535 return (Set.IsDummy) ? true : SetBuilder != null;
6538 protected bool DefineAccessors ()
6540 return DefineSet (define_set_first) &&
6542 DefineSet (!define_set_first);
6545 protected abstract PropertyInfo ResolveBaseProperty ();
6547 // TODO: rename to Resolve......
6548 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6550 PropertyInfo base_property = ResolveBaseProperty ();
6551 if (base_property == null)
6554 base_ret_type = base_property.PropertyType;
6555 MethodInfo get_accessor = base_property.GetGetMethod (true);
6556 MethodInfo set_accessor = base_property.GetSetMethod (true);
6557 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6560 // Check base property accessors conflict
6562 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6563 if (get_accessor == null) {
6564 if (Get != null && !Get.IsDummy) {
6565 Report.SymbolRelatedToPreviousError (base_property);
6566 Report.Error (545, Location,
6567 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6568 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6571 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6573 if (!Get.IsDummy && !CheckAccessModifiers (
6574 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6575 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6578 if (set_accessor == null) {
6579 if (Set != null && !Set.IsDummy) {
6580 Report.SymbolRelatedToPreviousError (base_property);
6581 Report.Error (546, Location,
6582 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6583 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6586 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6588 if (!Set.IsDummy && !CheckAccessModifiers (
6589 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6590 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6594 // When one accessor does not exist and property hides base one
6595 // we need to propagate this upwards
6596 if (set_accessor == null)
6597 set_accessor = get_accessor;
6600 // Get the less restrictive access
6602 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6605 public override void Emit ()
6608 // The PropertyBuilder can be null for explicit implementations, in that
6609 // case, we do not actually emit the ".property", so there is nowhere to
6610 // put the attribute
6612 if (PropertyBuilder != null && OptAttributes != null)
6613 OptAttributes.Emit ();
6625 /// Tests whether accessors are not in collision with some method (CS0111)
6627 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6629 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6632 public override bool IsUsed
6638 return Get.IsUsed | Set.IsUsed;
6642 protected override void SetMemberName (MemberName new_name)
6644 base.SetMemberName (new_name);
6646 Get.UpdateName (this);
6647 Set.UpdateName (this);
6650 public override string[] ValidAttributeTargets {
6652 return attribute_targets;
6657 // Represents header string for documentation comment.
6659 public override string DocCommentHeader {
6660 get { return "P:"; }
6664 public class Property : PropertyBase {
6665 const int AllowedModifiers =
6668 Modifiers.PROTECTED |
6669 Modifiers.INTERNAL |
6673 Modifiers.OVERRIDE |
6674 Modifiers.ABSTRACT |
6679 const int AllowedInterfaceModifiers =
6682 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6683 MemberName name, Attributes attrs, Accessor get_block,
6684 Accessor set_block, bool define_set_first)
6685 : this (parent, type, mod, name, attrs, get_block, set_block,
6686 define_set_first, null)
6690 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6691 MemberName name, Attributes attrs, Accessor get_block,
6692 Accessor set_block, bool define_set_first, Block current_block)
6693 : base (parent, type, mod,
6694 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6695 name, attrs, define_set_first)
6697 if (get_block == null)
6698 Get = new GetMethod (this);
6700 Get = new GetMethod (this, get_block);
6702 if (set_block == null)
6703 Set = new SetMethod (this);
6705 Set = new SetMethod (this, set_block);
6707 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6708 get_block != null && get_block.Block == null &&
6709 set_block != null && set_block.Block == null) {
6710 if (RootContext.Version <= LanguageVersion.ISO_2)
6711 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6713 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
6714 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
6718 void CreateAutomaticProperty ()
6720 // Create backing field
6721 Field field = new Field (
6723 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6724 new MemberName ("<" + GetFullName (MemberName) + ">k__BackingField", Location), null);
6725 if (!field.Define ())
6728 Parent.PartialContainer.AddField (field);
6731 Get.Block = new ToplevelBlock (Parameters.EmptyReadOnlyParameters, Location);
6732 Return r = new Return (new SimpleName (field.Name, Location), Location);
6733 Get.Block.AddStatement (r);
6736 Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
6737 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6738 Set.Block.AddStatement (new StatementExpression (a));
6741 public override bool Define ()
6743 if (!base.Define ())
6746 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6748 if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6749 CreateAutomaticProperty ();
6751 if (!DefineAccessors ())
6757 // FIXME - PropertyAttributes.HasDefault ?
6759 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6760 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6763 PropertyBuilder.SetGetMethod (GetBuilder);
6764 Parent.MemberCache.AddMember (GetBuilder, Get);
6768 PropertyBuilder.SetSetMethod (SetBuilder);
6769 Parent.MemberCache.AddMember (SetBuilder, Set);
6772 TypeManager.RegisterProperty (PropertyBuilder, this);
6773 Parent.MemberCache.AddMember (PropertyBuilder, this);
6777 public override void Emit ()
6779 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6780 Report.Error (842, Location,
6781 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6782 GetSignatureForError ());
6788 protected override PropertyInfo ResolveBaseProperty ()
6790 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6791 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6796 /// Gigantic workaround for lameness in SRE follows :
6797 /// This class derives from EventInfo and attempts to basically
6798 /// wrap around the EventBuilder so that FindMembers can quickly
6799 /// return this in it search for members
6801 public class MyEventBuilder : EventInfo {
6804 // We use this to "point" to our Builder which is
6805 // not really a MemberInfo
6807 EventBuilder MyBuilder;
6810 // We "catch" and wrap these methods
6812 MethodInfo raise, remove, add;
6814 EventAttributes attributes;
6815 Type declaring_type, reflected_type, event_type;
6820 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6822 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6824 // And now store the values in our own fields.
6826 declaring_type = type_builder;
6828 reflected_type = type_builder;
6830 attributes = event_attr;
6833 this.event_type = event_type;
6837 // Methods that you have to override. Note that you only need
6838 // to "implement" the variants that take the argument (those are
6839 // the "abstract" methods, the others (GetAddMethod()) are
6842 public override MethodInfo GetAddMethod (bool nonPublic)
6847 public override MethodInfo GetRemoveMethod (bool nonPublic)
6852 public override MethodInfo GetRaiseMethod (bool nonPublic)
6858 // These methods make "MyEventInfo" look like a Builder
6860 public void SetRaiseMethod (MethodBuilder raiseMethod)
6862 raise = raiseMethod;
6863 MyBuilder.SetRaiseMethod (raiseMethod);
6866 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6868 remove = removeMethod;
6869 MyBuilder.SetRemoveOnMethod (removeMethod);
6872 public void SetAddOnMethod (MethodBuilder addMethod)
6875 MyBuilder.SetAddOnMethod (addMethod);
6878 public void SetCustomAttribute (CustomAttributeBuilder cb)
6880 MyBuilder.SetCustomAttribute (cb);
6883 public override object [] GetCustomAttributes (bool inherit)
6885 // FIXME : There's nothing which can be seemingly done here because
6886 // we have no way of getting at the custom attribute objects of the
6891 public override object [] GetCustomAttributes (Type t, bool inherit)
6893 // FIXME : Same here !
6897 public override bool IsDefined (Type t, bool b)
6902 public override EventAttributes Attributes {
6908 public override string Name {
6914 public override Type DeclaringType {
6916 return declaring_type;
6920 public override Type ReflectedType {
6922 return reflected_type;
6926 public Type EventType {
6932 public void SetUsed ()
6934 if (my_event != null) {
6935 // my_event.SetAssigned ();
6936 my_event.SetMemberIsUsed ();
6942 /// For case when event is declared like property (with add and remove accessors).
6944 public class EventProperty: Event {
6945 abstract class AEventPropertyAccessor : AEventAccessor
6947 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6948 base (method, accessor, prefix)
6952 public override MethodBuilder Define (DeclSpace ds)
6954 CheckAbstractAndExtern (block != null);
6955 return base.Define (ds);
6958 public override string GetSignatureForError ()
6960 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6964 sealed class AddDelegateMethod: AEventPropertyAccessor
6966 public AddDelegateMethod (Event method, Accessor accessor):
6967 base (method, accessor, "add_")
6971 protected override MethodInfo DelegateMethodInfo {
6973 return TypeManager.delegate_combine_delegate_delegate;
6978 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6980 public RemoveDelegateMethod (Event method, Accessor accessor):
6981 base (method, accessor, "remove_")
6985 protected override MethodInfo DelegateMethodInfo {
6987 return TypeManager.delegate_remove_delegate_delegate;
6993 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6995 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6997 Attributes attrs, Accessor add, Accessor remove)
6998 : base (parent, type, mod_flags, name, attrs)
7000 Add = new AddDelegateMethod (this, add);
7001 Remove = new RemoveDelegateMethod (this, remove);
7004 public override bool Define()
7006 if (!base.Define ())
7013 public override string[] ValidAttributeTargets {
7015 return attribute_targets;
7021 /// Event is declared like field.
7023 public class EventField : Event {
7024 abstract class EventFieldAccessor : AEventAccessor
7026 protected EventFieldAccessor (Event method, string prefix)
7027 : base (method, prefix)
7031 protected override void EmitMethod(DeclSpace parent)
7033 if (method_data.implementing != null)
7034 parent.PartialContainer.PendingImplementations.ImplementMethod (
7035 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
7037 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7040 MethodBuilder mb = method_data.MethodBuilder;
7041 ILGenerator ig = mb.GetILGenerator ();
7043 // TODO: because we cannot use generics yet
7044 FieldInfo field_info = ((EventField)method).FieldBuilder;
7046 if (parent is Class) {
7047 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7050 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7051 ig.Emit (OpCodes.Ldsfld, field_info);
7052 ig.Emit (OpCodes.Ldarg_0);
7053 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7054 ig.Emit (OpCodes.Castclass, method.MemberType);
7055 ig.Emit (OpCodes.Stsfld, field_info);
7057 ig.Emit (OpCodes.Ldarg_0);
7058 ig.Emit (OpCodes.Ldarg_0);
7059 ig.Emit (OpCodes.Ldfld, field_info);
7060 ig.Emit (OpCodes.Ldarg_1);
7061 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7062 ig.Emit (OpCodes.Castclass, method.MemberType);
7063 ig.Emit (OpCodes.Stfld, field_info);
7065 ig.Emit (OpCodes.Ret);
7069 sealed class AddDelegateMethod: EventFieldAccessor
7071 public AddDelegateMethod (Event method):
7072 base (method, "add_")
7076 protected override MethodInfo DelegateMethodInfo {
7078 return TypeManager.delegate_combine_delegate_delegate;
7083 sealed class RemoveDelegateMethod: EventFieldAccessor
7085 public RemoveDelegateMethod (Event method):
7086 base (method, "remove_")
7090 protected override MethodInfo DelegateMethodInfo {
7092 return TypeManager.delegate_remove_delegate_delegate;
7098 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7099 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7101 public FieldBuilder FieldBuilder;
7102 public Expression Initializer;
7104 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7105 : base (parent, type, mod_flags, name, attrs)
7107 Add = new AddDelegateMethod (this);
7108 Remove = new RemoveDelegateMethod (this);
7111 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7113 if (a.Target == AttributeTargets.Field) {
7114 FieldBuilder.SetCustomAttribute (cb);
7118 if (a.Target == AttributeTargets.Method) {
7119 int errors = Report.Errors;
7120 Add.ApplyAttributeBuilder (a, cb);
7121 if (errors == Report.Errors)
7122 Remove.ApplyAttributeBuilder (a, cb);
7126 base.ApplyAttributeBuilder (a, cb);
7129 public override bool Define()
7131 if (!base.Define ())
7137 // FIXME: We are unable to detect whether generic event is used because
7138 // we are using FieldExpr instead of EventExpr for event access in that
7139 // case. When this issue will be fixed this hack can be removed.
7140 if (TypeManager.IsGenericType (MemberType))
7143 if (Add.IsInterfaceImplementation)
7146 FieldBuilder = Parent.TypeBuilder.DefineField (
7148 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7149 TypeManager.RegisterEventField (EventBuilder, this);
7151 if (Initializer != null) {
7152 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7153 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7154 GetSignatureForError ());
7158 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7159 new FieldInitializer (FieldBuilder, Initializer, this));
7165 public override string[] ValidAttributeTargets
7168 return IsInterface ? attribute_targets_interface : attribute_targets;
7173 public abstract class Event : PropertyBasedMember {
7174 public abstract class AEventAccessor : AbstractPropertyEventMethod
7176 protected readonly Event method;
7177 ImplicitParameter param_attr;
7179 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7181 protected AEventAccessor (Event method, string prefix)
7182 : base (method, prefix)
7184 this.method = method;
7185 this.ModFlags = method.ModFlags;
7188 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7189 : base (method, accessor, prefix)
7191 this.method = method;
7192 this.ModFlags = method.ModFlags;
7195 public bool IsInterfaceImplementation {
7196 get { return method_data.implementing != null; }
7199 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7201 if (a.IsInternalMethodImplAttribute) {
7202 method.is_external_implementation = true;
7205 base.ApplyAttributeBuilder (a, cb);
7208 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7210 if (a.Target == AttributeTargets.Parameter) {
7211 if (param_attr == null)
7212 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7214 param_attr.ApplyAttributeBuilder (a, cb);
7218 base.ApplyAttributeBuilder (a, cb);
7221 public override AttributeTargets AttributeTargets {
7223 return AttributeTargets.Method;
7227 public override bool IsClsComplianceRequired ()
7229 return method.IsClsComplianceRequired ();
7232 public virtual MethodBuilder Define (DeclSpace parent)
7234 method_data = new MethodData (method, method.ModFlags,
7235 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7237 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7240 MethodBuilder mb = method_data.MethodBuilder;
7241 ParameterInfo.ApplyAttributes (mb);
7245 protected abstract MethodInfo DelegateMethodInfo { get; }
7247 public override Type ReturnType {
7249 return TypeManager.void_type;
7253 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7255 return new EmitContext (
7256 this, method.Parent, Location, ig, ReturnType,
7257 method.ModFlags, false);
7260 public override ObsoleteAttribute GetObsoleteAttribute ()
7262 return method.GetObsoleteAttribute ();
7265 public override string[] ValidAttributeTargets {
7267 return attribute_targets;
7271 public override Parameters ParameterInfo {
7273 return method.parameters;
7279 const int AllowedModifiers =
7282 Modifiers.PROTECTED |
7283 Modifiers.INTERNAL |
7288 Modifiers.OVERRIDE |
7290 Modifiers.ABSTRACT |
7293 const int AllowedInterfaceModifiers =
7296 public AEventAccessor Add, Remove;
7297 public MyEventBuilder EventBuilder;
7298 public MethodBuilder AddBuilder, RemoveBuilder;
7300 Parameters parameters;
7302 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7303 : base (parent, null, type, mod_flags,
7304 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7309 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7311 if ((a.HasSecurityAttribute)) {
7312 a.Error_InvalidSecurityParent ();
7316 EventBuilder.SetCustomAttribute (cb);
7319 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7321 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7324 public override AttributeTargets AttributeTargets {
7326 return AttributeTargets.Event;
7330 public override bool Define ()
7332 if (!base.Define ())
7335 if (!TypeManager.IsDelegateType (MemberType)) {
7336 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7339 parameters = Parameters.CreateFullyResolved (
7340 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7345 if (TypeManager.delegate_combine_delegate_delegate == null) {
7346 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7347 TypeManager.delegate_type, "Combine", Location,
7348 TypeManager.delegate_type, TypeManager.delegate_type);
7350 if (TypeManager.delegate_remove_delegate_delegate == null) {
7351 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7352 TypeManager.delegate_type, "Remove", Location,
7353 TypeManager.delegate_type, TypeManager.delegate_type);
7357 // Now define the accessors
7360 AddBuilder = Add.Define (Parent);
7361 if (AddBuilder == null)
7364 RemoveBuilder = Remove.Define (Parent);
7365 if (RemoveBuilder == null)
7368 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7369 EventBuilder.SetAddOnMethod (AddBuilder);
7370 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7372 Parent.MemberCache.AddMember (EventBuilder, this);
7373 Parent.MemberCache.AddMember (AddBuilder, Add);
7374 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7379 public override void Emit ()
7381 if (OptAttributes != null) {
7382 OptAttributes.Emit ();
7386 Remove.Emit (Parent);
7391 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7393 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7394 Parent.TypeBuilder, Name);
7399 AParametersCollection pd = TypeManager.GetParameterData (mi);
7400 base_ret_type = pd.Types [0];
7405 // Represents header string for documentation comment.
7407 public override string DocCommentHeader {
7408 get { return "E:"; }
7413 public class Indexer : PropertyBase
7415 public class GetIndexerMethod : GetMethod
7417 Parameters parameters;
7419 public GetIndexerMethod (Indexer method):
7422 this.parameters = method.parameters;
7425 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7426 base (method, accessor)
7428 parameters = accessor.Parameters;
7431 public override MethodBuilder Define (DeclSpace parent)
7433 parameters.Resolve (ResolveContext);
7434 return base.Define (parent);
7437 public override bool EnableOverloadChecks (MemberCore overload)
7439 if (base.EnableOverloadChecks (overload)) {
7440 overload.caching_flags |= Flags.MethodOverloadsExist;
7447 public override Parameters ParameterInfo {
7454 public class SetIndexerMethod: SetMethod
7456 public SetIndexerMethod (Indexer method):
7459 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7462 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7463 base (method, accessor)
7465 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7468 public override bool EnableOverloadChecks (MemberCore overload)
7470 if (base.EnableOverloadChecks (overload)) {
7471 overload.caching_flags |= Flags.MethodOverloadsExist;
7479 const int AllowedModifiers =
7482 Modifiers.PROTECTED |
7483 Modifiers.INTERNAL |
7487 Modifiers.OVERRIDE |
7492 const int AllowedInterfaceModifiers =
7495 public readonly Parameters parameters;
7497 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7498 Parameters parameters, Attributes attrs,
7499 Accessor get_block, Accessor set_block, bool define_set_first)
7500 : base (parent, type, mod,
7501 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7502 name, attrs, define_set_first)
7504 this.parameters = parameters;
7506 if (get_block == null)
7507 Get = new GetIndexerMethod (this);
7509 Get = new GetIndexerMethod (this, get_block);
7511 if (set_block == null)
7512 Set = new SetIndexerMethod (this);
7514 Set = new SetIndexerMethod (this, set_block);
7517 protected override bool CheckForDuplications ()
7519 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7522 public override bool Define ()
7524 if (!base.Define ())
7527 if (!DefineParameters (parameters))
7530 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7531 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7532 if (indexer_attr != null) {
7533 // Remove the attribute from the list because it is not emitted
7534 OptAttributes.Attrs.Remove (indexer_attr);
7536 string name = indexer_attr.GetIndexerAttributeValue ();
7542 if (IsExplicitImpl) {
7543 Report.Error (415, indexer_attr.Location,
7544 "The `IndexerName' attribute is valid only on an " +
7545 "indexer that is not an explicit interface member declaration");
7549 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7550 Report.Error (609, indexer_attr.Location,
7551 "Cannot set the `IndexerName' attribute on an indexer marked override");
7557 if (InterfaceType != null) {
7558 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7559 if (base_IndexerName != Name)
7560 ShortName = base_IndexerName;
7563 if (!Parent.PartialContainer.AddMember (this) ||
7564 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7567 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7569 if (!DefineAccessors ())
7576 // Now name the parameters
7578 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7579 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7582 PropertyBuilder.SetGetMethod (GetBuilder);
7583 Parent.MemberCache.AddMember (GetBuilder, Get);
7587 PropertyBuilder.SetSetMethod (SetBuilder);
7588 Parent.MemberCache.AddMember (SetBuilder, Set);
7591 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7592 Parent.MemberCache.AddMember (PropertyBuilder, this);
7596 public override bool EnableOverloadChecks (MemberCore overload)
7598 if (overload is Indexer) {
7599 caching_flags |= Flags.MethodOverloadsExist;
7603 return base.EnableOverloadChecks (overload);
7606 public override string GetDocCommentName (DeclSpace ds)
7608 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7611 public override string GetSignatureForError ()
7613 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7614 if (MemberName.Left != null) {
7616 sb.Append (MemberName.Left.GetSignatureForError ());
7619 sb.Append (".this");
7620 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7621 return sb.ToString ();
7624 protected override PropertyInfo ResolveBaseProperty ()
7626 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7627 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7630 protected override bool VerifyClsCompliance ()
7632 if (!base.VerifyClsCompliance ())
7635 parameters.VerifyClsCompliance ();
7640 public class Operator : MethodOrOperator {
7642 const int AllowedModifiers =
7648 public enum OpType : byte {
7658 // Unary and Binary operators
7681 // Implicit and Explicit
7685 // Just because of enum
7689 public readonly OpType OperatorType;
7691 static readonly string [] [] names;
7695 names = new string[(int)OpType.TOP][];
7696 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7697 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7698 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7699 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7700 names [(int) OpType.True] = new string [] { "true", "op_True" };
7701 names [(int) OpType.False] = new string [] { "false", "op_False" };
7702 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7703 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7704 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7705 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7706 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7707 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7708 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7709 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7710 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7711 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7712 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7713 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7714 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7715 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7716 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7717 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7718 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7719 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7720 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7721 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7724 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7725 int mod_flags, Parameters parameters,
7726 ToplevelBlock block, Attributes attrs, Location loc)
7727 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7728 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7730 OperatorType = type;
7734 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7736 if (a.Type == TypeManager.conditional_attribute_type) {
7737 Error_ConditionalAttributeIsNotValid ();
7741 base.ApplyAttributeBuilder (a, cb);
7744 public override bool Define ()
7746 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7747 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7748 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7751 if (!base.Define ())
7754 // imlicit and explicit operator of same types are not allowed
7755 if (OperatorType == OpType.Explicit)
7756 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7757 else if (OperatorType == OpType.Implicit)
7758 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7760 Type declaring_type = MethodData.DeclaringType;
7761 Type return_type = MemberType;
7762 Type first_arg_type = ParameterTypes [0];
7764 Type first_arg_type_unwrap = first_arg_type;
7765 if (TypeManager.IsNullableType (first_arg_type))
7766 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7768 Type return_type_unwrap = return_type;
7769 if (TypeManager.IsNullableType (return_type))
7770 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7773 // Rules for conversion operators
7775 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7776 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7777 Report.Error (555, Location,
7778 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7783 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7784 conv_type = first_arg_type;
7785 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7786 conv_type = return_type;
7788 Report.Error (556, Location,
7789 "User-defined conversion must convert to or from the enclosing type");
7794 // Because IsInterface and IsClass are not supported
7796 if (!TypeManager.IsGenericParameter (conv_type)) {
7797 if (conv_type.IsInterface) {
7798 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7799 GetSignatureForError ());
7803 if (conv_type.IsClass) {
7804 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7805 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7806 GetSignatureForError ());
7810 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7811 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7812 GetSignatureForError ());
7817 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7818 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7819 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");
7822 } else if (Parameters.Count == 1) {
7823 // Checks for Unary operators
7825 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7826 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7827 Report.Error (448, Location,
7828 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7831 if (first_arg_type != declaring_type) {
7833 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7838 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7839 Report.Error (562, Location,
7840 "The parameter type of a unary operator must be the containing type");
7844 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7845 if (return_type != TypeManager.bool_type){
7848 "The return type of operator True or False " +
7855 // Checks for Binary operators
7857 if (first_arg_type != declaring_type &&
7858 Parameters.Types [1] != declaring_type){
7861 "One of the parameters of a binary operator must " +
7862 "be the containing type");
7870 protected override bool ResolveMemberType ()
7872 if (!base.ResolveMemberType ())
7875 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7879 // Operator cannot be override
7880 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7885 public static string GetName (OpType ot)
7887 return names [(int) ot] [0];
7890 public static string GetName (string metadata_name)
7892 for (int i = 0; i < names.Length; ++i) {
7893 if (names [i] [1] == metadata_name)
7894 return names [i] [0];
7899 public static string GetMetadataName (OpType ot)
7901 return names [(int) ot] [1];
7904 public static string GetMetadataName (string name)
7906 for (int i = 0; i < names.Length; ++i) {
7907 if (names [i] [0] == name)
7908 return names [i] [1];
7913 public OpType GetMatchingOperator ()
7915 switch (OperatorType) {
7916 case OpType.Equality:
7917 return OpType.Inequality;
7918 case OpType.Inequality:
7919 return OpType.Equality;
7921 return OpType.False;
7924 case OpType.GreaterThan:
7925 return OpType.LessThan;
7926 case OpType.LessThan:
7927 return OpType.GreaterThan;
7928 case OpType.GreaterThanOrEqual:
7929 return OpType.LessThanOrEqual;
7930 case OpType.LessThanOrEqual:
7931 return OpType.GreaterThanOrEqual;
7937 public override string GetSignatureForError ()
7939 StringBuilder sb = new StringBuilder ();
7940 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7941 sb.AppendFormat ("{0}.{1} operator {2}",
7942 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7945 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7948 sb.Append (Parameters.GetSignatureForError ());
7949 return sb.ToString ();
7954 // This is used to compare method signatures
7956 struct MethodSignature {
7958 public Type RetType;
7959 public Type [] Parameters;
7962 /// This delegate is used to extract methods which have the
7963 /// same signature as the argument
7965 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7967 public MethodSignature (string name, Type ret_type, Type [] parameters)
7972 if (parameters == null)
7973 Parameters = Type.EmptyTypes;
7975 Parameters = parameters;
7978 public override string ToString ()
7981 if (Parameters.Length != 0){
7982 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7983 for (int i = 0; i < Parameters.Length; i++){
7984 sb.Append (Parameters [i]);
7985 if (i+1 < Parameters.Length)
7988 pars = sb.ToString ();
7991 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7994 public override int GetHashCode ()
7996 return Name.GetHashCode ();
7999 public override bool Equals (Object o)
8001 MethodSignature other = (MethodSignature) o;
8003 if (other.Name != Name)
8006 if (other.RetType != RetType)
8009 if (Parameters == null){
8010 if (other.Parameters == null)
8015 if (other.Parameters == null)
8018 int c = Parameters.Length;
8019 if (other.Parameters.Length != c)
8022 for (int i = 0; i < c; i++)
8023 if (other.Parameters [i] != Parameters [i])
8029 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8031 MethodSignature sig = (MethodSignature) filter_criteria;
8033 if (m.Name != sig.Name)
8037 MethodInfo mi = m as MethodInfo;
8038 PropertyInfo pi = m as PropertyInfo;
8041 ReturnType = mi.ReturnType;
8042 else if (pi != null)
8043 ReturnType = pi.PropertyType;
8048 // we use sig.RetType == null to mean `do not check the
8049 // method return value.
8051 if (sig.RetType != null) {
8052 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8058 args = TypeManager.GetParameterData (mi).Types;
8060 args = TypeManager.GetParameterData (pi).Types;
8061 Type [] sigp = sig.Parameters;
8063 if (args.Length != sigp.Length)
8066 for (int i = args.Length - 1; i >= 0; i--)
8067 if (!TypeManager.IsEqual (args [i], sigp [i]))