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, ParametersCompiled.EmptyReadOnlyParameters,
2583 new GeneratedBaseInitializer (Location),
2587 c.Block = new ToplevelBlock (ParametersCompiled.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 ParametersCompiled 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, ParametersCompiled 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 ParametersCompiled ParameterInfo {
3164 public ToplevelBlock Block {
3174 protected override bool CheckBase ()
3176 // Check whether arguments were correct.
3177 if (!DefineParameters (Parameters))
3180 return base.CheckBase ();
3184 // Returns a string that represents the signature for this
3185 // member which should be used in XML documentation.
3187 public override string GetDocCommentName (DeclSpace ds)
3189 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3193 // Raised (and passed an XmlElement that contains the comment)
3194 // when GenerateDocComment is writing documentation expectedly.
3196 // FIXME: with a few effort, it could be done with XmlReader,
3197 // that means removal of DOM use.
3199 internal override void OnGenerateDocComment (XmlElement el)
3201 DocUtil.OnMethodGenerateDocComment (this, el);
3205 // Represents header string for documentation comment.
3207 public override string DocCommentHeader
3209 get { return "M:"; }
3212 public override bool EnableOverloadChecks (MemberCore overload)
3214 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3215 caching_flags |= Flags.MethodOverloadsExist;
3219 return base.EnableOverloadChecks (overload);
3222 protected override bool VerifyClsCompliance ()
3224 if (!base.VerifyClsCompliance ())
3227 if (Parameters.HasArglist) {
3228 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3231 if (!AttributeTester.IsClsCompliant (MemberType)) {
3232 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3233 GetSignatureForError ());
3236 Parameters.VerifyClsCompliance ();
3242 public abstract class InterfaceMemberBase : MemberBase {
3244 // Whether this is an interface member.
3246 public bool IsInterface;
3249 // If true, this is an explicit interface implementation
3251 public bool IsExplicitImpl;
3253 protected bool is_external_implementation;
3256 // The interface type we are explicitly implementing
3258 public Type InterfaceType;
3261 // The method we're overriding if this is an override method.
3263 protected MethodInfo base_method;
3265 readonly int explicit_mod_flags;
3266 public MethodAttributes flags;
3268 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3269 FullNamedExpression type, int mod, int allowed_mod,
3270 MemberName name, Attributes attrs)
3271 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3274 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3275 IsExplicitImpl = (MemberName.Left != null);
3276 explicit_mod_flags = mod;
3279 protected override bool CheckBase ()
3281 if (!base.CheckBase ())
3284 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3285 CheckForDuplications ();
3290 // Is null for System.Object while compiling corlib and base interfaces
3291 if (Parent.PartialContainer.BaseCache == null) {
3292 if ((ModFlags & Modifiers.NEW) != 0) {
3293 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3298 Type base_ret_type = null;
3299 base_method = FindOutBaseMethod (ref base_ret_type);
3301 // method is override
3302 if (base_method != null) {
3303 if (!CheckMethodAgainstBase (base_ret_type))
3306 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3307 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3309 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3310 Report.SymbolRelatedToPreviousError (base_method);
3311 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3312 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3315 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3316 Report.SymbolRelatedToPreviousError (base_method);
3317 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3318 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3325 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3326 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3327 if (conflict_symbol != null) {
3328 Report.SymbolRelatedToPreviousError (conflict_symbol);
3330 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3331 else if (this is PropertyBase)
3332 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3334 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3336 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3337 GetSignatureForError (), SimpleName.GetMemberType (this));
3342 if (conflict_symbol == null) {
3343 if ((ModFlags & Modifiers.NEW) != 0) {
3344 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3349 if ((ModFlags & Modifiers.NEW) == 0) {
3350 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3353 Report.SymbolRelatedToPreviousError (conflict_symbol);
3354 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3355 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3361 protected virtual bool CheckForDuplications ()
3363 return Parent.MemberCache.CheckExistingMembersOverloads (
3364 this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters);
3368 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3369 // that have been defined.
3371 // `name' is the user visible name for reporting errors (this is used to
3372 // provide the right name regarding method names and properties)
3374 bool CheckMethodAgainstBase (Type base_method_type)
3378 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3379 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3380 Report.SymbolRelatedToPreviousError (base_method);
3381 Report.Error (506, Location,
3382 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3383 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3387 // Now we check that the overriden method is not final
3389 if (base_method.IsFinal) {
3390 Report.SymbolRelatedToPreviousError (base_method);
3391 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3392 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3396 // Check that the permissions are not being changed
3398 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3399 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3401 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3402 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3406 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3407 Report.SymbolRelatedToPreviousError (base_method);
3408 if (this is PropertyBasedMember) {
3409 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3410 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3413 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3414 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3420 if ((ModFlags & Modifiers.NEW) == 0) {
3421 if ((ModFlags & Modifiers.OVERRIDE) == 0) {
3422 ModFlags |= Modifiers.NEW;
3423 Report.SymbolRelatedToPreviousError (base_method);
3424 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3425 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",
3426 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3428 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3429 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3433 if (base_method.IsAbstract && !IsInterface) {
3434 Report.SymbolRelatedToPreviousError (base_method);
3435 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3436 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3444 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3446 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3448 // when overriding protected internal, the method can be declared
3449 // protected internal only within the same assembly or assembly
3450 // which has InternalsVisibleTo
3452 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3453 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3454 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3456 // if it's not "protected internal", it must be "protected"
3460 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3462 // protected within the same assembly - an error
3465 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3466 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3468 // protected ok, but other attributes differ - report an error
3474 return (thisp == base_classp);
3478 public override bool Define ()
3481 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3482 Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3484 flags = MethodAttributes.Public |
3485 MethodAttributes.Abstract |
3486 MethodAttributes.HideBySig |
3487 MethodAttributes.NewSlot |
3488 MethodAttributes.Virtual;
3490 Parent.PartialContainer.MethodModifiersValid (this);
3492 flags = Modifiers.MethodAttr (ModFlags);
3495 if (IsExplicitImpl) {
3496 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3497 if (iface_texpr == null)
3500 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3501 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3502 GetSignatureForError ());
3505 InterfaceType = iface_texpr.Type;
3507 if (!InterfaceType.IsInterface) {
3508 Report.SymbolRelatedToPreviousError (InterfaceType);
3509 Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3510 TypeManager.CSharpName (InterfaceType));
3512 Parent.PartialContainer.VerifyImplements (this);
3515 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3518 return base.Define ();
3521 protected bool DefineParameters (ParametersCompiled parameters)
3523 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3525 if (!parameters.Resolve (rc))
3529 for (int i = 0; i < parameters.Count; ++i) {
3530 Parameter p = parameters [i];
3531 if (p.CheckAccessibility (this))
3534 Type t = parameters.Types [i];
3535 Report.SymbolRelatedToPreviousError (t);
3536 if (this is Indexer)
3537 Report.Error (55, Location,
3538 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3539 TypeManager.CSharpName (t), GetSignatureForError ());
3540 else if (this is Operator)
3541 Report.Error (57, Location,
3542 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3543 TypeManager.CSharpName (t), GetSignatureForError ());
3545 Report.Error (51, Location,
3546 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3547 TypeManager.CSharpName (t), GetSignatureForError ());
3553 public override void Emit()
3555 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3556 // We are more strict than Microsoft and report CS0626 as error
3557 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3558 Report.Error (626, Location,
3559 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3560 GetSignatureForError ());
3566 public override bool EnableOverloadChecks (MemberCore overload)
3569 // Two members can differ in their explicit interface
3570 // type parameter only
3572 InterfaceMemberBase imb = overload as InterfaceMemberBase;
3573 if (imb != null && imb.IsExplicitImpl) {
3574 if (IsExplicitImpl) {
3575 caching_flags |= Flags.MethodOverloadsExist;
3580 return IsExplicitImpl;
3583 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3585 Report.SymbolRelatedToPreviousError (base_method);
3586 string base_name = TypeManager.GetFullNameSignature (base_method);
3587 string this_name = GetSignatureForError ();
3588 if (suffix != null) {
3589 base_name += suffix;
3590 this_name += suffix;
3593 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3594 this_name, Modifiers.GetDescription (ma), base_name);
3597 protected static string Error722 {
3599 return "`{0}': static types cannot be used as return types";
3604 /// Gets base method and its return type
3606 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3609 // The "short" name of this property / indexer / event. This is the
3610 // name without the explicit interface.
3612 public string ShortName
3614 get { return MemberName.Name; }
3615 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3619 // Returns full metadata method name
3621 public string GetFullName (MemberName name)
3623 if (!IsExplicitImpl)
3627 // When dealing with explicit members a full interface type
3628 // name is added to member name to avoid possible name conflicts
3630 // We use CSharpName which gets us full name with benefit of
3631 // replacing predefined names which saves some space and name
3634 return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3637 protected override bool VerifyClsCompliance ()
3639 if (!base.VerifyClsCompliance ()) {
3640 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3641 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3644 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3645 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3650 if (GenericMethod != null)
3651 GenericMethod.VerifyClsCompliance ();
3656 public override bool IsUsed
3658 get { return IsExplicitImpl || base.IsUsed; }
3663 public abstract class MethodOrOperator : MethodCore, IMethodData
3665 public MethodBuilder MethodBuilder;
3666 ReturnParameter return_attributes;
3667 ListDictionary declarative_security;
3668 protected MethodData MethodData;
3670 static string[] attribute_targets = new string [] { "method", "return" };
3672 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3673 int allowed_mod, MemberName name,
3674 Attributes attrs, ParametersCompiled parameters)
3675 : base (parent, generic, type, mod, allowed_mod, name,
3680 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3682 if (a.Target == AttributeTargets.ReturnValue) {
3683 if (return_attributes == null)
3684 return_attributes = new ReturnParameter (MethodBuilder, Location);
3686 return_attributes.ApplyAttributeBuilder (a, cb);
3690 if (a.IsInternalMethodImplAttribute) {
3691 is_external_implementation = true;
3694 if (a.Type == TypeManager.dllimport_type) {
3695 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3696 if ((ModFlags & extern_static) != extern_static) {
3697 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3699 is_external_implementation = true;
3702 if (a.IsValidSecurityAttribute ()) {
3703 if (declarative_security == null)
3704 declarative_security = new ListDictionary ();
3705 a.ExtractSecurityPermissionSet (declarative_security);
3709 if (MethodBuilder != null)
3710 MethodBuilder.SetCustomAttribute (cb);
3713 public override AttributeTargets AttributeTargets {
3715 return AttributeTargets.Method;
3719 protected override bool CheckForDuplications ()
3721 string name = GetFullName (MemberName);
3722 if (MemberName.IsGeneric)
3723 name = MemberName.MakeName (name, MemberName.TypeArguments);
3725 return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3728 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3730 return new EmitContext (
3731 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3734 protected override bool ResolveMemberType ()
3737 if (GenericMethod != null) {
3738 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3739 if (!GenericMethod.Define (this))
3744 return base.ResolveMemberType ();
3747 public override bool Define ()
3749 if (!base.Define ())
3755 if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3757 // Current method is turned into automatically generated
3758 // wrapper which creates an instance of iterator
3760 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3761 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3764 if (IsPartialDefinition) {
3765 caching_flags &= ~Flags.Excluded_Undetected;
3766 caching_flags |= Flags.Excluded;
3767 // Add to member cache only when a partial method implementation is not there
3768 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3769 MethodBase mb = new PartialMethodDefinitionInfo (this);
3770 Parent.MemberCache.AddMember (mb, this);
3771 TypeManager.AddMethod (mb, this);
3777 MethodData = new MethodData (
3778 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3780 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3783 MethodBuilder = MethodData.MethodBuilder;
3786 if (MethodBuilder.IsGenericMethod)
3787 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3790 Parent.MemberCache.AddMember (MethodBuilder, this);
3795 protected override void DoMemberTypeIndependentChecks ()
3797 base.DoMemberTypeIndependentChecks ();
3799 CheckAbstractAndExtern (block != null);
3801 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3802 for (int i = 0; i < Parameters.Count; ++i) {
3803 if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3804 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3805 GetSignatureForError ());
3812 protected override void DoMemberTypeDependentChecks ()
3814 base.DoMemberTypeDependentChecks ();
3816 if (!TypeManager.IsGenericParameter (MemberType)) {
3817 if (MemberType.IsAbstract && MemberType.IsSealed) {
3818 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3823 public override void Emit ()
3826 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3827 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3828 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3829 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3831 if (OptAttributes != null)
3832 OptAttributes.Emit ();
3834 if (declarative_security != null) {
3835 foreach (DictionaryEntry de in declarative_security) {
3836 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3840 if (MethodData != null)
3841 MethodData.Emit (Parent);
3849 protected void Error_ConditionalAttributeIsNotValid ()
3851 Report.Error (577, Location,
3852 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3853 GetSignatureForError ());
3856 public bool IsPartialDefinition {
3858 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3862 public bool IsPartialImplementation {
3864 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3868 public override string[] ValidAttributeTargets {
3870 return attribute_targets;
3874 #region IMethodData Members
3876 public CallingConventions CallingConventions {
3878 CallingConventions cc = Parameters.CallingConvention;
3880 if ((ModFlags & Modifiers.STATIC) == 0)
3881 cc |= CallingConventions.HasThis;
3883 // FIXME: How is `ExplicitThis' used in C#?
3889 public Type ReturnType {
3895 public MemberName MethodName {
3902 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3904 public bool IsExcluded () {
3905 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3906 return (caching_flags & Flags.Excluded) != 0;
3908 caching_flags &= ~Flags.Excluded_Undetected;
3910 if (base_method == null) {
3911 if (OptAttributes == null)
3914 if (TypeManager.conditional_attribute_type == null)
3917 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3922 foreach (Attribute a in attrs) {
3923 string condition = a.GetConditionalAttributeValue ();
3924 if (condition == null)
3927 if (Location.CompilationUnit.IsConditionalDefined (condition))
3931 caching_flags |= Flags.Excluded;
3935 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3937 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3938 caching_flags |= Flags.Excluded;
3944 if (md.IsExcluded ()) {
3945 caching_flags |= Flags.Excluded;
3951 GenericMethod IMethodData.GenericMethod {
3953 return GenericMethod;
3957 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3964 public class SourceMethod : IMethodDef
3967 SourceMethodBuilder builder;
3969 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3971 this.method = method;
3973 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3976 public string Name {
3977 get { return method.Name; }
3982 if (method is MethodBuilder)
3983 return ((MethodBuilder) method).GetToken ().Token;
3984 else if (method is ConstructorBuilder)
3985 return ((ConstructorBuilder) method).GetToken ().Token;
3987 throw new NotSupportedException ();
3991 public void CloseMethod ()
3993 SymbolWriter.CloseMethod ();
3996 public void SetRealMethodName (string name)
3998 if (builder != null)
3999 builder.SetRealMethodName (name);
4002 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4004 if (!SymbolWriter.HasSymbolWriter)
4009 Location start_loc = block.StartLocation;
4010 if (start_loc.IsNull)
4013 ICompileUnit compile_unit = start_loc.CompilationUnit;
4014 if (compile_unit == null)
4017 return new SourceMethod (parent, method, compile_unit);
4021 public class Method : MethodOrOperator {
4024 /// Modifiers allowed in a class declaration
4026 const int AllowedModifiers =
4029 Modifiers.PROTECTED |
4030 Modifiers.INTERNAL |
4035 Modifiers.OVERRIDE |
4036 Modifiers.ABSTRACT |
4040 const int AllowedInterfaceModifiers =
4041 Modifiers.NEW | Modifiers.UNSAFE;
4043 public Method (DeclSpace parent, GenericMethod generic,
4044 FullNamedExpression return_type, int mod,
4045 MemberName name, ParametersCompiled parameters, Attributes attrs)
4046 : base (parent, generic, return_type, mod,
4047 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4048 name, attrs, parameters)
4052 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4053 MemberName name, ParametersCompiled parameters, Attributes attrs)
4054 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4058 public override string GetSignatureForError()
4060 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4063 static void Error_DuplicateEntryPoint (Method b)
4065 Report.Error (17, b.Location,
4066 "Program `{0}' has more than one entry point defined: `{1}'",
4067 CodeGen.FileName, b.GetSignatureForError ());
4070 bool IsEntryPoint ()
4072 if (ReturnType != TypeManager.void_type &&
4073 ReturnType != TypeManager.int32_type)
4076 if (Parameters.Count == 0)
4079 if (Parameters.Count > 1)
4082 Type t = Parameters.Types [0];
4083 return t.IsArray && t.GetArrayRank () == 1 &&
4084 TypeManager.GetElementType (t) == TypeManager.string_type &&
4085 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4088 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4090 if (a.Type == TypeManager.conditional_attribute_type) {
4091 if (IsExplicitImpl) {
4092 Error_ConditionalAttributeIsNotValid ();
4096 if (ReturnType != TypeManager.void_type) {
4097 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4101 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4102 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4107 Report.Error (582, Location, "Conditional not valid on interface members");
4111 if (MethodData.implementing != null) {
4112 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4113 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4114 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4118 for (int i = 0; i < Parameters.Count; ++i) {
4119 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4120 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4126 if (a.Type == TypeManager.extension_attribute_type) {
4127 a.Error_MisusedExtensionAttribute ();
4131 base.ApplyAttributeBuilder (a, cb);
4134 protected override bool CheckForDuplications ()
4136 if (!base.CheckForDuplications ())
4139 ArrayList ar = Parent.PartialContainer.Properties;
4141 for (int i = 0; i < ar.Count; ++i) {
4142 PropertyBase pb = (PropertyBase) ar [i];
4143 if (pb.AreAccessorsDuplicateImplementation (this))
4148 ar = Parent.PartialContainer.Indexers;
4150 for (int i = 0; i < ar.Count; ++i) {
4151 PropertyBase pb = (PropertyBase) ar [i];
4152 if (pb.AreAccessorsDuplicateImplementation (this))
4160 protected override bool CheckBase ()
4162 if (!base.CheckBase ())
4165 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
4166 Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
4167 TypeManager.CSharpSignature (base_method));
4176 public override bool Define ()
4178 if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
4179 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4182 if (!base.Define ())
4185 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4186 Error1599 (Location, ReturnType);
4190 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4191 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4192 Parent.PartialContainer.Mark_HasEquals ();
4193 else if (Parameters.IsEmpty && Name == "GetHashCode")
4194 Parent.PartialContainer.Mark_HasGetHashCode ();
4197 if ((ModFlags & Modifiers.STATIC) == 0)
4200 if (Parameters.HasExtensionMethodType) {
4201 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4202 if (!Parent.IsTopLevel)
4203 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4204 GetSignatureForError ());
4206 if (TypeManager.extension_attribute_type == null) {
4207 Report.Error (1110, Location,
4208 "`{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",
4209 GetSignatureForError ());
4210 } else if (TypeManager.extension_attribute_attr == null) {
4211 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4212 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4215 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4218 ModFlags |= Modifiers.METHOD_EXTENSION;
4219 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4220 CodeGen.Assembly.HasExtensionMethods = true;
4222 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4223 GetSignatureForError ());
4228 // This is used to track the Entry Point,
4230 if (RootContext.NeedsEntryPoint &&
4232 (RootContext.MainClass == null ||
4233 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4234 if (IsEntryPoint ()) {
4236 if (RootContext.EntryPoint == null) {
4237 if (Parent.IsGeneric || MemberName.IsGeneric) {
4238 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4239 GetSignatureForError ());
4242 RootContext.EntryPoint = this;
4245 Error_DuplicateEntryPoint (RootContext.EntryPoint);
4246 Error_DuplicateEntryPoint (this);
4249 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4250 GetSignatureForError ());
4260 public override void Emit ()
4263 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4264 if (IsPartialDefinition) {
4266 // Do attribute checks only when partial implementation does not exist
4268 if (MethodBuilder == null)
4274 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4275 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4276 GetSignatureForError ());
4281 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4282 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4286 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4287 Location, MethodBuilder);
4292 public override bool EnableOverloadChecks (MemberCore overload)
4294 // TODO: It can be deleted when members will be defined in correct order
4295 if (overload is Operator)
4296 return overload.EnableOverloadChecks (this);
4298 if (overload is Indexer)
4301 return base.EnableOverloadChecks (overload);
4304 public static void Error1599 (Location loc, Type t)
4306 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4309 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4311 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4312 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4317 if (mi.IsSpecialName)
4320 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4324 public void SetPartialDefinition (Method methodDefinition)
4326 caching_flags |= Flags.PartialDefinitionExists;
4327 methodDefinition.MethodBuilder = MethodBuilder;
4328 if (methodDefinition.attributes == null)
4331 if (attributes == null) {
4332 attributes = methodDefinition.attributes;
4334 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4338 protected override bool VerifyClsCompliance ()
4340 if (!base.VerifyClsCompliance ())
4343 if (!Parameters.IsEmpty) {
4344 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4346 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4353 public abstract class ConstructorInitializer : ExpressionStatement
4355 ArrayList argument_list;
4356 MethodGroupExpr base_constructor_group;
4358 public ConstructorInitializer (ArrayList argument_list, Location loc)
4360 this.argument_list = argument_list;
4364 public ArrayList Arguments {
4366 return argument_list;
4370 public override Expression CreateExpressionTree (EmitContext ec)
4372 throw new NotSupportedException ("ET");
4375 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4377 if (argument_list != null){
4378 foreach (Argument a in argument_list){
4379 if (!a.Resolve (ec, loc))
4384 if (this is ConstructorBaseInitializer) {
4385 if (ec.ContainerType.BaseType == null)
4388 type = ec.ContainerType.BaseType;
4389 if (TypeManager.IsStruct (ec.ContainerType)) {
4390 Report.Error (522, loc,
4391 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4396 // It is legal to have "this" initializers that take no arguments
4397 // in structs, they are just no-ops.
4399 // struct D { public D (int a) : this () {}
4401 if (TypeManager.IsStruct (ec.ContainerType) && argument_list == null)
4404 type = ec.ContainerType;
4407 base_constructor_group = MemberLookupFinal (
4408 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4409 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4410 loc) as MethodGroupExpr;
4412 if (base_constructor_group == null)
4415 base_constructor_group = base_constructor_group.OverloadResolve (
4416 ec, ref argument_list, false, loc);
4418 if (base_constructor_group == null)
4421 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4423 if (base_ctor == caller_builder){
4424 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4430 public override Expression DoResolve (EmitContext ec)
4432 throw new NotSupportedException ();
4435 public override void Emit (EmitContext ec)
4437 // It can be null for static initializers
4438 if (base_constructor_group == null)
4443 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4445 base_constructor_group.EmitCall (ec, argument_list);
4448 public override void EmitStatement (EmitContext ec)
4454 public class ConstructorBaseInitializer : ConstructorInitializer {
4455 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4456 base (argument_list, l)
4461 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4462 public GeneratedBaseInitializer (Location loc):
4468 public class ConstructorThisInitializer : ConstructorInitializer {
4469 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4470 base (argument_list, l)
4475 public class Constructor : MethodCore, IMethodData {
4476 public ConstructorBuilder ConstructorBuilder;
4477 public ConstructorInitializer Initializer;
4478 ListDictionary declarative_security;
4479 bool has_compliant_args;
4482 // Modifiers allowed for a constructor.
4484 public const int AllowedModifiers =
4486 Modifiers.PROTECTED |
4487 Modifiers.INTERNAL |
4493 static readonly string[] attribute_targets = new string [] { "method" };
4496 // The spec claims that static is not permitted, but
4497 // my very own code has static constructors.
4499 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, ParametersCompiled args,
4500 ConstructorInitializer init, Location loc)
4501 : base (parent, null, null, mod, AllowedModifiers,
4502 new MemberName (name, loc), attrs, args)
4507 public bool HasCompliantArgs {
4508 get { return has_compliant_args; }
4511 public override AttributeTargets AttributeTargets {
4512 get { return AttributeTargets.Constructor; }
4516 // Returns true if this is a default constructor
4518 public bool IsDefault ()
4520 if ((ModFlags & Modifiers.STATIC) != 0)
4521 return Parameters.IsEmpty;
4523 return Parameters.IsEmpty &&
4524 (Initializer is ConstructorBaseInitializer) &&
4525 (Initializer.Arguments == null);
4528 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4530 if (a.IsValidSecurityAttribute ()) {
4531 if (declarative_security == null) {
4532 declarative_security = new ListDictionary ();
4534 a.ExtractSecurityPermissionSet (declarative_security);
4538 if (a.IsInternalMethodImplAttribute) {
4539 is_external_implementation = true;
4542 ConstructorBuilder.SetCustomAttribute (cb);
4545 protected override bool CheckBase ()
4547 if ((ModFlags & Modifiers.STATIC) != 0) {
4548 if (!Parameters.IsEmpty) {
4549 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4550 GetSignatureForError ());
4554 // the rest can be ignored
4558 // Check whether arguments were correct.
4559 if (!DefineParameters (Parameters))
4562 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4563 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4566 if (Parent.PartialContainer.Kind == Kind.Struct) {
4567 if (Parameters.Count == 0) {
4568 Report.Error (568, Location,
4569 "Structs cannot contain explicit parameterless constructors");
4574 CheckProtectedModifier ();
4580 // Creates the ConstructorBuilder
4582 public override bool Define ()
4584 if (ConstructorBuilder != null)
4587 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4588 MethodAttributes.SpecialName);
4590 if ((ModFlags & Modifiers.STATIC) != 0) {
4591 ca |= MethodAttributes.Static | MethodAttributes.Private;
4593 ca |= MethodAttributes.HideBySig;
4595 if ((ModFlags & Modifiers.PUBLIC) != 0)
4596 ca |= MethodAttributes.Public;
4597 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4598 if ((ModFlags & Modifiers.INTERNAL) != 0)
4599 ca |= MethodAttributes.FamORAssem;
4601 ca |= MethodAttributes.Family;
4602 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4603 ca |= MethodAttributes.Assembly;
4605 ca |= MethodAttributes.Private;
4608 if (!CheckAbstractAndExtern (block != null))
4611 // Check if arguments were correct.
4615 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4616 ca, CallingConventions,
4617 Parameters.GetEmitTypes ());
4619 if (Parent.PartialContainer.IsComImport) {
4620 if (!IsDefault ()) {
4621 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4622 Parent.GetSignatureForError ());
4624 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4627 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4628 TypeManager.AddMethod (ConstructorBuilder, this);
4630 // It's here only to report an error
4631 if (block != null && block.IsIterator) {
4632 member_type = TypeManager.void_type;
4633 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4642 public override void Emit ()
4644 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4645 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4647 if (OptAttributes != null)
4648 OptAttributes.Emit ();
4652 EmitContext ec = CreateEmitContext (null, null);
4655 // If we use a "this (...)" constructor initializer, then
4656 // do not emit field initializers, they are initialized in the other constructor
4658 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4659 !(Initializer is ConstructorThisInitializer);
4661 if (emit_field_initializers)
4662 Parent.PartialContainer.ResolveFieldInitializers (ec);
4664 if (block != null) {
4665 // If this is a non-static `struct' constructor and doesn't have any
4666 // initializer, it must initialize all of the struct's fields.
4667 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4668 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4669 block.AddThisVariable (Parent, Location);
4671 if (!block.ResolveMeta (ec, Parameters))
4674 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4675 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4676 Initializer = new GeneratedBaseInitializer (Location);
4679 // Spec mandates that Initializers will not have `this' access
4681 if (Initializer != null) {
4683 Initializer.Resolve (ConstructorBuilder, ec);
4684 ec.IsStatic = false;
4685 block.AddScopeStatement (new StatementExpression (Initializer));
4690 Parameters.ApplyAttributes (ConstructorBuilder);
4692 SourceMethod source = null;
4694 ec.OmitDebuggingInfo = true;
4696 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4698 bool unreachable = false;
4699 if (block != null) {
4700 if (!ec.ResolveTopBlock (null, block, Parameters, this, out unreachable))
4703 ec.EmitMeta (block);
4705 if (Report.Errors > 0)
4708 ec.EmitResolvedTopBlock (block, unreachable);
4712 source.CloseMethod ();
4714 if (declarative_security != null) {
4715 foreach (DictionaryEntry de in declarative_security) {
4716 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4723 // Is never override
4724 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4729 public override string GetSignatureForError()
4731 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4734 public override string[] ValidAttributeTargets {
4736 return attribute_targets;
4740 protected override bool VerifyClsCompliance ()
4742 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4746 if (!Parameters.IsEmpty) {
4747 ArrayList al = (ArrayList)Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
4749 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4751 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4752 foreach (Type param in Parameters.Types) {
4753 if (param.IsArray) {
4759 has_compliant_args = true;
4763 #region IMethodData Members
4765 public System.Reflection.CallingConventions CallingConventions {
4767 CallingConventions cc = Parameters.CallingConvention;
4769 if (Parent.PartialContainer.Kind == Kind.Class)
4770 if ((ModFlags & Modifiers.STATIC) == 0)
4771 cc |= CallingConventions.HasThis;
4773 // FIXME: How is `ExplicitThis' used in C#?
4779 public MemberName MethodName {
4785 public Type ReturnType {
4791 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4793 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4794 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4795 ec.CurrentBlock = block;
4799 public bool IsExcluded()
4804 GenericMethod IMethodData.GenericMethod {
4810 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4817 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4819 public interface IMethodData
4821 CallingConventions CallingConventions { get; }
4822 Location Location { get; }
4823 MemberName MethodName { get; }
4824 Type ReturnType { get; }
4825 GenericMethod GenericMethod { get; }
4826 ParametersCompiled ParameterInfo { get; }
4828 Attributes OptAttributes { get; }
4829 ToplevelBlock Block { get; set; }
4831 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4832 ObsoleteAttribute GetObsoleteAttribute ();
4833 string GetSignatureForError ();
4835 bool IsClsComplianceRequired ();
4836 void SetMemberIsUsed ();
4837 void EmitExtraSymbolInfo (SourceMethod source);
4841 // Encapsulates most of the Method's state
4843 public class MethodData {
4845 static FieldInfo methodbuilder_attrs_field;
4847 public readonly IMethodData method;
4849 public readonly GenericMethod GenericMethod;
4852 // Are we implementing an interface ?
4854 public MethodInfo implementing;
4859 protected InterfaceMemberBase member;
4860 protected int modifiers;
4861 protected MethodAttributes flags;
4862 protected Type declaring_type;
4863 protected MethodInfo parent_method;
4865 MethodBuilder builder = null;
4866 public MethodBuilder MethodBuilder {
4872 public Type DeclaringType {
4874 return declaring_type;
4878 public MethodData (InterfaceMemberBase member,
4879 int modifiers, MethodAttributes flags, IMethodData method)
4881 this.member = member;
4882 this.modifiers = modifiers;
4885 this.method = method;
4888 public MethodData (InterfaceMemberBase member,
4889 int modifiers, MethodAttributes flags,
4890 IMethodData method, MethodBuilder builder,
4891 GenericMethod generic, MethodInfo parent_method)
4892 : this (member, modifiers, flags, method)
4894 this.builder = builder;
4895 this.GenericMethod = generic;
4896 this.parent_method = parent_method;
4899 public bool Define (DeclSpace parent, string method_full_name)
4901 string name = method.MethodName.Basename;
4903 TypeContainer container = parent.PartialContainer;
4905 PendingImplementation pending = container.PendingImplementations;
4906 if (pending != null){
4907 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4909 if (member.InterfaceType != null){
4910 if (implementing == null){
4911 if (member is PropertyBase) {
4912 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4913 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4914 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4917 Report.Error (539, method.Location,
4918 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4919 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4923 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4924 Report.SymbolRelatedToPreviousError (implementing);
4925 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4926 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4930 if (implementing != null) {
4931 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4932 if (prop_method == null) {
4933 if (TypeManager.IsSpecialMethod (implementing)) {
4934 Report.SymbolRelatedToPreviousError (implementing);
4935 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4936 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4937 implementing.Name.StartsWith ("get_") ? "get" : "set");
4939 } else if (implementing.DeclaringType.IsInterface) {
4940 if (!implementing.IsSpecialName) {
4941 Report.SymbolRelatedToPreviousError (implementing);
4942 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4943 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4946 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4947 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4948 Report.SymbolRelatedToPreviousError (implementing);
4949 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4950 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4959 // For implicit implementations, make sure we are public, for
4960 // explicit implementations, make sure we are private.
4962 if (implementing != null){
4964 // Setting null inside this block will trigger a more
4965 // verbose error reporting for missing interface implementations
4967 // The "candidate" function has been flagged already
4968 // but it wont get cleared
4970 if (member.IsExplicitImpl){
4971 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4972 Report.SymbolRelatedToPreviousError (implementing);
4973 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4974 method.GetSignatureForError ());
4978 if (implementing.DeclaringType.IsInterface) {
4980 // If this is an interface method implementation,
4981 // check for public accessibility
4983 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4985 implementing = null;
4987 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4988 // We may never be private.
4989 implementing = null;
4991 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4993 // We may be protected if we're overriding something.
4995 implementing = null;
5000 // Static is not allowed
5002 if ((modifiers & Modifiers.STATIC) != 0){
5003 implementing = null;
5008 // If implementing is still valid, set flags
5010 if (implementing != null){
5012 // When implementing interface methods, set NewSlot
5013 // unless, we are overwriting a method.
5015 if (implementing.DeclaringType.IsInterface){
5016 if ((modifiers & Modifiers.OVERRIDE) == 0)
5017 flags |= MethodAttributes.NewSlot;
5020 MethodAttributes.Virtual |
5021 MethodAttributes.HideBySig;
5023 // Set Final unless we're virtual, abstract or already overriding a method.
5024 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5025 flags |= MethodAttributes.Final;
5028 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5030 if (builder == null)
5033 if (container.CurrentType != null)
5034 declaring_type = container.CurrentType;
5036 declaring_type = container.TypeBuilder;
5038 if (implementing != null && member.IsExplicitImpl) {
5039 container.TypeBuilder.DefineMethodOverride (builder, implementing);
5042 TypeManager.AddMethod (builder, method);
5044 if (GenericMethod != null) {
5045 bool is_override = member.IsExplicitImpl |
5046 ((modifiers & Modifiers.OVERRIDE) != 0);
5048 if (implementing != null)
5049 parent_method = implementing;
5051 EmitContext ec = method.CreateEmitContext (container, null);
5052 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5061 /// Create the MethodBuilder for the method
5063 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
5065 if (builder == null) {
5066 builder = container.TypeBuilder.DefineMethod (
5067 method_name, flags, method.CallingConventions,
5068 method.ReturnType, param.GetEmitTypes ());
5074 // Generic method has been already defined to resolve method parameters
5075 // correctly when they use type parameters
5077 builder.SetParameters (param.GetEmitTypes ());
5078 builder.SetReturnType (method.ReturnType);
5080 if (builder.Attributes != flags) {
5082 if (methodbuilder_attrs_field == null)
5083 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5084 methodbuilder_attrs_field.SetValue (builder, flags);
5086 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5090 throw new InternalErrorException ();
5097 public void Emit (DeclSpace parent)
5099 ToplevelBlock block = method.Block;
5103 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5105 ec = method.CreateEmitContext (parent, null);
5107 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5109 if (GenericMethod != null)
5110 GenericMethod.EmitAttributes ();
5113 // clear the pending implementation flag
5115 if (implementing != null)
5116 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5117 member.InterfaceType, this, member.IsExplicitImpl);
5119 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5121 ec.EmitTopBlock (method, block);
5123 if (source != null) {
5124 method.EmitExtraSymbolInfo (source);
5125 source.CloseMethod ();
5130 public class Destructor : MethodOrOperator
5132 const int AllowedModifiers =
5136 static readonly string[] attribute_targets = new string [] { "method" };
5138 public static readonly string MetadataName = "Finalize";
5140 public Destructor (DeclSpace parent, int mod, ParametersCompiled parameters, Attributes attrs, Location l)
5141 : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
5142 new MemberName (MetadataName, l), attrs, parameters)
5144 ModFlags &= ~Modifiers.PRIVATE;
5145 ModFlags |= Modifiers.PROTECTED;
5148 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5150 if (a.Type == TypeManager.conditional_attribute_type) {
5151 Error_ConditionalAttributeIsNotValid ();
5155 base.ApplyAttributeBuilder (a, cb);
5158 protected override bool CheckBase ()
5160 flags |= MethodAttributes.Virtual;
5162 if (!base.CheckBase ())
5165 if (Parent.PartialContainer.BaseCache == null)
5168 Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
5169 if (base_type != null && Block != null) {
5170 MethodGroupExpr method_expr = Expression.MethodLookup (Parent.TypeBuilder, base_type, MetadataName, Location);
5171 if (method_expr == null)
5172 throw new NotImplementedException ();
5174 method_expr.IsBase = true;
5175 method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
5177 ToplevelBlock new_block = new ToplevelBlock (Block.StartLocation);
5178 new_block.EndLocation = Block.EndLocation;
5180 Block finaly_block = new ExplicitBlock (new_block, Location, Location);
5181 Block try_block = new Block (new_block, block);
5184 // 0-size arguments to avoid CS0250 error
5185 // TODO: Should use AddScopeStatement or something else which emits correct
5188 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new ArrayList (0))));
5189 new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
5197 public override string GetSignatureForError ()
5199 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5202 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5207 public override string[] ValidAttributeTargets {
5209 return attribute_targets;
5214 public abstract class MemberBase : MemberCore
5216 protected FullNamedExpression type_name;
5217 protected Type member_type;
5219 public readonly DeclSpace ds;
5220 public readonly GenericMethod GenericMethod;
5222 protected MemberBase (DeclSpace parent, GenericMethod generic,
5223 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5224 MemberName name, Attributes attrs)
5225 : base (parent, name, attrs)
5227 this.ds = generic != null ? generic : (DeclSpace) parent;
5228 this.type_name = type;
5229 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5230 GenericMethod = generic;
5231 if (GenericMethod != null)
5232 GenericMethod.ModFlags = ModFlags;
5236 // Main member define entry
5238 public override bool Define ()
5240 DoMemberTypeIndependentChecks ();
5243 // Returns false only when type resolution failed
5245 if (!ResolveMemberType ())
5248 DoMemberTypeDependentChecks ();
5253 // Any type_name independent checks
5255 protected virtual void DoMemberTypeIndependentChecks ()
5257 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5258 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5259 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5260 GetSignatureForError (), Parent.GetSignatureForError ());
5265 // Any type_name dependent checks
5267 protected virtual void DoMemberTypeDependentChecks ()
5269 // verify accessibility
5270 if (!IsAccessibleAs (MemberType)) {
5271 Report.SymbolRelatedToPreviousError (MemberType);
5272 if (this is Property)
5273 Report.Error (53, Location,
5274 "Inconsistent accessibility: property type `" +
5275 TypeManager.CSharpName (MemberType) + "' is less " +
5276 "accessible than property `" + GetSignatureForError () + "'");
5277 else if (this is Indexer)
5278 Report.Error (54, Location,
5279 "Inconsistent accessibility: indexer return type `" +
5280 TypeManager.CSharpName (MemberType) + "' is less " +
5281 "accessible than indexer `" + GetSignatureForError () + "'");
5282 else if (this is MethodCore) {
5283 if (this is Operator)
5284 Report.Error (56, Location,
5285 "Inconsistent accessibility: return type `" +
5286 TypeManager.CSharpName (MemberType) + "' is less " +
5287 "accessible than operator `" + GetSignatureForError () + "'");
5289 Report.Error (50, Location,
5290 "Inconsistent accessibility: return type `" +
5291 TypeManager.CSharpName (MemberType) + "' is less " +
5292 "accessible than method `" + GetSignatureForError () + "'");
5294 Report.Error (52, Location,
5295 "Inconsistent accessibility: field type `" +
5296 TypeManager.CSharpName (MemberType) + "' is less " +
5297 "accessible than field `" + GetSignatureForError () + "'");
5302 protected bool IsTypePermitted ()
5304 if (TypeManager.IsSpecialType (MemberType)) {
5305 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5311 protected virtual bool CheckBase ()
5313 CheckProtectedModifier ();
5318 public Type MemberType {
5319 get { return member_type; }
5322 protected virtual bool ResolveMemberType ()
5324 if (member_type != null)
5325 throw new InternalErrorException ("Multi-resolve");
5327 IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5328 TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5333 // Replace original type name, error reporting can use fully resolved name
5337 member_type = te.Type;
5343 // Abstract class for all fields
5345 abstract public class FieldBase : MemberBase {
5346 public FieldBuilder FieldBuilder;
5347 public Status status;
5348 protected Expression initializer;
5351 public enum Status : byte {
5352 HAS_OFFSET = 4 // Used by FieldMember.
5355 static readonly string[] attribute_targets = new string [] { "field" };
5357 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5358 int allowed_mod, MemberName name, Attributes attrs)
5359 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5362 if ((mod & Modifiers.ABSTRACT) != 0)
5363 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5366 public override AttributeTargets AttributeTargets {
5368 return AttributeTargets.Field;
5372 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5374 if (a.Type == TypeManager.field_offset_attribute_type) {
5375 status |= Status.HAS_OFFSET;
5377 if (!Parent.PartialContainer.HasExplicitLayout) {
5378 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5382 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5383 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5389 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5390 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5396 if (a.Type == TypeManager.marshal_as_attr_type) {
5397 UnmanagedMarshal marshal = a.GetMarshal (this);
5398 if (marshal != null) {
5399 FieldBuilder.SetMarshal (marshal);
5404 if ((a.HasSecurityAttribute)) {
5405 a.Error_InvalidSecurityParent ();
5409 FieldBuilder.SetCustomAttribute (cb);
5412 protected override bool CheckBase ()
5414 if (!base.CheckBase ())
5417 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5418 if (conflict_symbol == null) {
5419 if ((ModFlags & Modifiers.NEW) != 0) {
5420 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5425 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5426 Report.SymbolRelatedToPreviousError (conflict_symbol);
5427 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5428 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5434 protected override void DoMemberTypeDependentChecks ()
5436 base.DoMemberTypeDependentChecks ();
5438 if (TypeManager.IsGenericParameter (MemberType))
5441 if (MemberType.IsSealed && MemberType.IsAbstract) {
5442 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5450 // Represents header string for documentation comment.
5452 public override string DocCommentHeader {
5453 get { return "F:"; }
5456 public override void Emit ()
5459 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5460 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5463 if (OptAttributes != null) {
5464 OptAttributes.Emit ();
5467 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5468 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5474 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5476 Report.SymbolRelatedToPreviousError (static_class);
5477 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5481 public Expression Initializer {
5483 if (value != null) {
5484 this.initializer = value;
5489 protected virtual bool IsFieldClsCompliant {
5491 if (FieldBuilder == null)
5494 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5498 public override string[] ValidAttributeTargets
5501 return attribute_targets;
5505 protected override bool VerifyClsCompliance ()
5507 if (!base.VerifyClsCompliance ())
5510 if (!IsFieldClsCompliant) {
5511 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5512 GetSignatureForError ());
5517 public void SetAssigned ()
5519 caching_flags |= Flags.IsAssigned;
5523 interface IFixedBuffer
5525 FieldInfo Element { get; }
5526 Type ElementType { get; }
5529 public class FixedFieldExternal: IFixedBuffer
5531 FieldInfo element_field;
5533 public FixedFieldExternal (FieldInfo fi)
5535 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5538 #region IFixedField Members
5540 public FieldInfo Element {
5542 return element_field;
5546 public Type ElementType {
5548 return element_field.FieldType;
5556 /// Fixed buffer implementation
5558 public class FixedField : FieldBase, IFixedBuffer
5560 public const string FixedElementName = "FixedElementField";
5561 static int GlobalCounter = 0;
5562 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5563 static FieldInfo[] fi;
5565 TypeBuilder fixed_buffer_type;
5566 FieldBuilder element;
5567 Expression size_expr;
5569 const int AllowedModifiers =
5572 Modifiers.PROTECTED |
5573 Modifiers.INTERNAL |
5576 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5577 Expression size_expr, Attributes attrs, Location loc):
5578 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5580 if (RootContext.Version < LanguageVersion.ISO_2)
5581 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5583 this.size_expr = size_expr;
5586 public override bool Define()
5588 if (!base.Define ())
5591 if (!TypeManager.IsPrimitiveType (MemberType)) {
5592 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",
5593 GetSignatureForError ());
5596 // Create nested fixed buffer container
5597 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5598 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5599 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5601 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5602 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5604 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5605 Parent.MemberCache.AddMember (FieldBuilder, this);
5606 TypeManager.RegisterFieldBase (FieldBuilder, this);
5611 protected override void DoMemberTypeIndependentChecks ()
5613 base.DoMemberTypeIndependentChecks ();
5615 if (!Parent.IsInUnsafeScope)
5616 Expression.UnsafeError (Location);
5618 if (Parent.PartialContainer.Kind != Kind.Struct) {
5619 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5620 GetSignatureForError ());
5624 public override void Emit()
5626 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5627 Constant c = size_expr.ResolveAsConstant (ec, this);
5631 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5632 if (buffer_size_const == null)
5635 int buffer_size = buffer_size_const.Value;
5637 if (buffer_size <= 0) {
5638 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5642 int type_size = Expression.GetTypeSize (MemberType);
5644 if (buffer_size > int.MaxValue / type_size) {
5645 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5646 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5650 buffer_size *= type_size;
5651 EmitFieldSize (buffer_size);
5655 // Emit compiler generated fixed buffer type attribute
5657 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5659 Type attr_type = TypeManager.CoreLookupType (
5660 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5662 if (attr_type != null) {
5663 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5665 cab = new CustomAttributeBuilder (ci, new object [0]);
5666 TypeManager.unsafe_value_type_attr = cab;
5672 fixed_buffer_type.SetCustomAttribute (cab);
5677 void EmitFieldSize (int buffer_size)
5679 if (TypeManager.struct_layout_attribute_type == null) {
5680 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5681 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5683 if (TypeManager.struct_layout_attribute_type == null)
5688 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5690 object [] fi_val = new object [] { buffer_size };
5692 if (TypeManager.struct_layout_attribute_ctor == null) {
5693 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5694 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5695 if (TypeManager.struct_layout_attribute_ctor == null)
5699 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5700 ctor_args, fi, fi_val);
5701 fixed_buffer_type.SetCustomAttribute (cab);
5704 // Don't emit FixedBufferAttribute attribute for private types
5706 if ((ModFlags & Modifiers.PRIVATE) != 0)
5709 if (TypeManager.fixed_buffer_attr_ctor == null) {
5710 if (TypeManager.fixed_buffer_attr_type == null) {
5711 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5712 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5714 if (TypeManager.fixed_buffer_attr_type == null)
5718 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5719 Location, TypeManager.type_type, TypeManager.int32_type);
5721 if (TypeManager.fixed_buffer_attr_ctor == null)
5725 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5726 FieldBuilder.SetCustomAttribute (cab);
5729 protected override bool IsFieldClsCompliant {
5735 public void SetCharSet (TypeAttributes ta)
5737 TypeAttributes cta = fixed_buffer_type.Attributes;
5738 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5739 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5740 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5741 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5742 else if (cta == 0 && ta != 0)
5743 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5746 void SetTypeBuilderCharSet (TypeAttributes ta)
5748 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5750 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5752 mi.Invoke (fixed_buffer_type, new object [] { ta });
5756 #region IFixedField Members
5758 public FieldInfo Element {
5764 public Type ElementType {
5774 // The Field class is used to represents class/struct fields during parsing.
5776 public class Field : FieldBase {
5778 // Modifiers allowed in a class declaration
5780 const int AllowedModifiers =
5783 Modifiers.PROTECTED |
5784 Modifiers.INTERNAL |
5787 Modifiers.VOLATILE |
5791 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5793 : base (parent, type, mod, AllowedModifiers, name, attrs)
5797 bool CanBeVolatile ()
5799 if (TypeManager.IsReferenceType (MemberType))
5802 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5803 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5804 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5805 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5806 MemberType == TypeManager.float_type)
5809 if (TypeManager.IsEnumType (MemberType))
5815 bool CheckStructLayout (Type type, bool isStatic)
5817 if (TypeManager.IsBuiltinType (type))
5821 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5825 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5826 if (!TypeManager.IsGenericType (type))
5829 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5830 if (!CheckStructLayout (t, false))
5836 Report.Error (523, Location,
5837 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5838 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5842 public override bool Define ()
5844 if (!base.Define ())
5849 Type[] required_modifier = null;
5850 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5851 if (TypeManager.isvolatile_type == null)
5852 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5853 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5855 if (TypeManager.isvolatile_type != null)
5856 required_modifier = new Type [] { TypeManager.isvolatile_type };
5859 FieldBuilder = Parent.TypeBuilder.DefineField (
5860 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5862 FieldBuilder = Parent.TypeBuilder.DefineField (
5863 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5865 Parent.MemberCache.AddMember (FieldBuilder, this);
5866 TypeManager.RegisterFieldBase (FieldBuilder, this);
5868 catch (ArgumentException) {
5869 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5873 if (initializer != null) {
5874 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5875 new FieldInitializer (FieldBuilder, initializer, this));
5877 if (Parent.PartialContainer.Kind == Kind.Struct)
5878 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5884 protected override void DoMemberTypeDependentChecks ()
5886 base.DoMemberTypeDependentChecks ();
5888 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5889 if (!CanBeVolatile ()) {
5890 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5891 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5894 if ((ModFlags & Modifiers.READONLY) != 0) {
5895 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5896 GetSignatureForError ());
5901 public override string GetSignatureForError ()
5903 string s = base.GetSignatureForError ();
5904 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5907 // Undecorate name mangling
5908 int l = s.LastIndexOf ('>');
5909 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5912 protected override bool VerifyClsCompliance ()
5914 if (!base.VerifyClsCompliance ())
5917 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5918 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5926 // `set' and `get' accessors are represented with an Accessor.
5928 public class Accessor {
5930 // Null if the accessor is empty, or a Block if not
5932 public const int AllowedModifiers =
5934 Modifiers.PROTECTED |
5935 Modifiers.INTERNAL |
5938 public ToplevelBlock Block;
5939 public Attributes Attributes;
5940 public Location Location;
5941 public int ModFlags;
5942 public ParametersCompiled Parameters;
5944 public Accessor (ToplevelBlock b, int mod, Attributes attrs, ParametersCompiled p, Location loc)
5950 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5954 // Ooouh Martin, templates are missing here.
5955 // When it will be possible move here a lot of child code and template method type.
5956 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5957 protected MethodData method_data;
5958 protected ToplevelBlock block;
5959 protected ListDictionary declarative_security;
5961 // The accessor are created event if they are not wanted.
5962 // But we need them because their names are reserved.
5963 // Field says whether accessor will be emited or not
5964 public readonly bool IsDummy;
5966 protected readonly string prefix;
5968 ReturnParameter return_attributes;
5970 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5971 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5973 this.prefix = prefix;
5977 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5979 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5980 accessor.Attributes)
5982 this.prefix = prefix;
5983 this.block = accessor.Block;
5986 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5988 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5991 public void UpdateName (InterfaceMemberBase member)
5993 SetMemberName (SetupName (prefix, member, Location));
5996 #region IMethodData Members
5998 public ToplevelBlock Block {
6008 public CallingConventions CallingConventions {
6010 return CallingConventions.Standard;
6014 public bool IsExcluded ()
6019 GenericMethod IMethodData.GenericMethod {
6025 public MemberName MethodName {
6031 public Type[] ParameterTypes {
6033 return ParameterInfo.Types;
6037 public abstract ParametersCompiled ParameterInfo { get ; }
6038 public abstract Type ReturnType { get; }
6039 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6043 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6045 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6046 a.Type == TypeManager.conditional_attribute_type) {
6047 Report.Error (1667, a.Location,
6048 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6049 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6053 if (a.IsValidSecurityAttribute ()) {
6054 if (declarative_security == null)
6055 declarative_security = new ListDictionary ();
6056 a.ExtractSecurityPermissionSet (declarative_security);
6060 if (a.Target == AttributeTargets.Method) {
6061 method_data.MethodBuilder.SetCustomAttribute (cb);
6065 if (a.Target == AttributeTargets.ReturnValue) {
6066 if (return_attributes == null)
6067 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6069 return_attributes.ApplyAttributeBuilder (a, cb);
6073 ApplyToExtraTarget (a, cb);
6076 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6078 throw new NotSupportedException ("You forgot to define special attribute target handling");
6081 // It is not supported for the accessors
6082 public sealed override bool Define()
6084 throw new NotSupportedException ();
6087 public void Emit (DeclSpace parent)
6089 EmitMethod (parent);
6092 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6093 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6094 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6095 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6097 if (OptAttributes != null)
6098 OptAttributes.Emit ();
6100 if (declarative_security != null) {
6101 foreach (DictionaryEntry de in declarative_security) {
6102 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6109 protected virtual void EmitMethod (DeclSpace parent)
6111 method_data.Emit (parent);
6114 public override bool EnableOverloadChecks (MemberCore overload)
6116 // This can only happen with indexers and it will
6117 // be catched as indexer difference
6118 if (overload is AbstractPropertyEventMethod)
6121 if (overload is MethodCore) {
6122 caching_flags |= Flags.MethodOverloadsExist;
6128 public override bool IsClsComplianceRequired()
6133 public bool IsDuplicateImplementation (MethodCore method)
6135 if (!MemberName.Equals (method.MemberName))
6138 Type[] param_types = method.ParameterTypes;
6140 if (param_types == null || param_types.Length != ParameterTypes.Length)
6143 for (int i = 0; i < param_types.Length; i++)
6144 if (param_types [i] != ParameterTypes [i])
6147 Report.SymbolRelatedToPreviousError (method);
6148 Report.Error (82, Location, "A member `{0}' is already reserved",
6149 method.GetSignatureForError ());
6153 public override bool IsUsed
6164 // Represents header string for documentation comment.
6166 public override string DocCommentHeader {
6167 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6170 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6175 // Properties and Indexers both generate PropertyBuilders, we use this to share
6176 // their common bits.
6178 abstract public class PropertyBase : PropertyBasedMember {
6180 public class GetMethod : PropertyMethod
6182 static string[] attribute_targets = new string [] { "method", "return" };
6184 public GetMethod (PropertyBase method):
6185 base (method, "get_")
6189 public GetMethod (PropertyBase method, Accessor accessor):
6190 base (method, accessor, "get_")
6194 public override MethodBuilder Define (DeclSpace parent)
6196 base.Define (parent);
6201 method_data = new MethodData (method, ModFlags, flags, this);
6203 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6206 return method_data.MethodBuilder;
6209 public override Type ReturnType {
6211 return method.MemberType;
6215 public override ParametersCompiled ParameterInfo {
6217 return ParametersCompiled.EmptyReadOnlyParameters;
6221 public override string[] ValidAttributeTargets {
6223 return attribute_targets;
6228 public class SetMethod : PropertyMethod {
6230 static string[] attribute_targets = new string [] { "method", "param", "return" };
6231 ImplicitParameter param_attr;
6232 protected ParametersCompiled parameters;
6234 public SetMethod (PropertyBase method) :
6235 base (method, "set_")
6237 parameters = new ParametersCompiled (
6238 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6241 public SetMethod (PropertyBase method, Accessor accessor):
6242 base (method, accessor, "set_")
6244 this.parameters = accessor.Parameters;
6247 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6249 if (a.Target == AttributeTargets.Parameter) {
6250 if (param_attr == null)
6251 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6253 param_attr.ApplyAttributeBuilder (a, cb);
6257 base.ApplyAttributeBuilder (a, cb);
6260 public override ParametersCompiled ParameterInfo {
6266 public override MethodBuilder Define (DeclSpace parent)
6268 parameters.Resolve (ResolveContext);
6269 base.Define (parent);
6274 method_data = new MethodData (method, ModFlags, flags, this);
6276 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6279 return method_data.MethodBuilder;
6282 public override Type ReturnType {
6284 return TypeManager.void_type;
6288 public override string[] ValidAttributeTargets {
6290 return attribute_targets;
6295 static string[] attribute_targets = new string [] { "property" };
6297 public abstract class PropertyMethod : AbstractPropertyEventMethod
6299 protected readonly PropertyBase method;
6300 protected MethodAttributes flags;
6302 public PropertyMethod (PropertyBase method, string prefix)
6303 : base (method, prefix)
6305 this.method = method;
6306 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6309 public PropertyMethod (PropertyBase method, Accessor accessor,
6311 : base (method, accessor, prefix)
6313 this.method = method;
6314 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6316 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6317 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6321 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6323 if (a.IsInternalMethodImplAttribute) {
6324 method.is_external_implementation = true;
6327 base.ApplyAttributeBuilder (a, cb);
6330 public override AttributeTargets AttributeTargets {
6332 return AttributeTargets.Method;
6336 public override bool IsClsComplianceRequired ()
6338 return method.IsClsComplianceRequired ();
6341 public virtual MethodBuilder Define (DeclSpace parent)
6343 CheckForDuplications ();
6346 if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6347 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6348 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6350 Report.SymbolRelatedToPreviousError (mi);
6351 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6352 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6358 TypeContainer container = parent.PartialContainer;
6361 // Check for custom access modifier
6363 if ((ModFlags & Modifiers.Accessibility) == 0) {
6364 ModFlags |= method.ModFlags;
6365 flags = method.flags;
6367 if (container.Kind == Kind.Interface)
6368 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6369 GetSignatureForError ());
6371 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6372 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6375 CheckModifiers (ModFlags);
6376 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6377 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6378 flags = Modifiers.MethodAttr (ModFlags);
6379 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6382 CheckAbstractAndExtern (block != null);
6384 if (block != null && block.IsIterator)
6385 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6390 public bool HasCustomAccessModifier {
6392 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6396 public PropertyBase Property {
6402 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6404 return new EmitContext (this,
6405 ds, method.ds, method.Location, ig, ReturnType,
6406 method.ModFlags, false);
6409 public override ObsoleteAttribute GetObsoleteAttribute ()
6411 return method.GetObsoleteAttribute ();
6414 public override string GetSignatureForError()
6416 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6419 void CheckModifiers (int modflags)
6421 modflags &= Modifiers.Accessibility;
6423 int mflags = method.ModFlags & Modifiers.Accessibility;
6425 if ((mflags & Modifiers.PUBLIC) != 0) {
6426 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6428 else if ((mflags & Modifiers.PROTECTED) != 0) {
6429 if ((mflags & Modifiers.INTERNAL) != 0)
6430 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6432 flags |= Modifiers.PRIVATE;
6434 else if ((mflags & Modifiers.INTERNAL) != 0)
6435 flags |= Modifiers.PRIVATE;
6437 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6438 Report.Error (273, Location,
6439 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6440 GetSignatureForError (), method.GetSignatureForError ());
6444 protected bool CheckForDuplications ()
6446 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6449 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6453 public PropertyMethod Get, Set;
6454 public PropertyBuilder PropertyBuilder;
6455 public MethodBuilder GetBuilder, SetBuilder;
6457 protected bool define_set_first = false;
6459 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6460 int allowed_mod, MemberName name,
6461 Attributes attrs, bool define_set_first)
6462 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6464 this.define_set_first = define_set_first;
6467 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6469 if (a.HasSecurityAttribute) {
6470 a.Error_InvalidSecurityParent ();
6474 PropertyBuilder.SetCustomAttribute (cb);
6477 public override AttributeTargets AttributeTargets {
6479 return AttributeTargets.Property;
6483 protected override void DoMemberTypeDependentChecks ()
6485 base.DoMemberTypeDependentChecks ();
6489 if (MemberType.IsGenericParameter)
6493 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6494 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6498 protected override void DoMemberTypeIndependentChecks ()
6500 base.DoMemberTypeIndependentChecks ();
6503 // Accessors modifiers check
6505 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6506 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6507 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6508 GetSignatureForError ());
6511 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6512 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6513 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6514 Report.Error (276, Location,
6515 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6516 GetSignatureForError ());
6522 GetBuilder = Get.Define (Parent);
6523 return (Get.IsDummy) ? true : GetBuilder != null;
6526 bool DefineSet (bool define)
6531 SetBuilder = Set.Define (Parent);
6532 return (Set.IsDummy) ? true : SetBuilder != null;
6535 protected bool DefineAccessors ()
6537 return DefineSet (define_set_first) &&
6539 DefineSet (!define_set_first);
6542 protected abstract PropertyInfo ResolveBaseProperty ();
6544 // TODO: rename to Resolve......
6545 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6547 PropertyInfo base_property = ResolveBaseProperty ();
6548 if (base_property == null)
6551 base_ret_type = base_property.PropertyType;
6552 MethodInfo get_accessor = base_property.GetGetMethod (true);
6553 MethodInfo set_accessor = base_property.GetSetMethod (true);
6554 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6557 // Check base property accessors conflict
6559 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6560 if (get_accessor == null) {
6561 if (Get != null && !Get.IsDummy) {
6562 Report.SymbolRelatedToPreviousError (base_property);
6563 Report.Error (545, Location,
6564 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6565 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6568 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6570 if (!Get.IsDummy && !CheckAccessModifiers (
6571 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6572 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6575 if (set_accessor == null) {
6576 if (Set != null && !Set.IsDummy) {
6577 Report.SymbolRelatedToPreviousError (base_property);
6578 Report.Error (546, Location,
6579 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6580 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6583 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6585 if (!Set.IsDummy && !CheckAccessModifiers (
6586 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6587 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6591 // When one accessor does not exist and property hides base one
6592 // we need to propagate this upwards
6593 if (set_accessor == null)
6594 set_accessor = get_accessor;
6597 // Get the less restrictive access
6599 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6602 public override void Emit ()
6605 // The PropertyBuilder can be null for explicit implementations, in that
6606 // case, we do not actually emit the ".property", so there is nowhere to
6607 // put the attribute
6609 if (PropertyBuilder != null && OptAttributes != null)
6610 OptAttributes.Emit ();
6622 /// Tests whether accessors are not in collision with some method (CS0111)
6624 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6626 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6629 public override bool IsUsed
6635 return Get.IsUsed | Set.IsUsed;
6639 protected override void SetMemberName (MemberName new_name)
6641 base.SetMemberName (new_name);
6643 Get.UpdateName (this);
6644 Set.UpdateName (this);
6647 public override string[] ValidAttributeTargets {
6649 return attribute_targets;
6654 // Represents header string for documentation comment.
6656 public override string DocCommentHeader {
6657 get { return "P:"; }
6661 public class Property : PropertyBase {
6662 const int AllowedModifiers =
6665 Modifiers.PROTECTED |
6666 Modifiers.INTERNAL |
6670 Modifiers.OVERRIDE |
6671 Modifiers.ABSTRACT |
6676 const int AllowedInterfaceModifiers =
6679 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6680 MemberName name, Attributes attrs, Accessor get_block,
6681 Accessor set_block, bool define_set_first)
6682 : this (parent, type, mod, name, attrs, get_block, set_block,
6683 define_set_first, null)
6687 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6688 MemberName name, Attributes attrs, Accessor get_block,
6689 Accessor set_block, bool define_set_first, Block current_block)
6690 : base (parent, type, mod,
6691 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6692 name, attrs, define_set_first)
6694 if (get_block == null)
6695 Get = new GetMethod (this);
6697 Get = new GetMethod (this, get_block);
6699 if (set_block == null)
6700 Set = new SetMethod (this);
6702 Set = new SetMethod (this, set_block);
6704 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6705 get_block != null && get_block.Block == null &&
6706 set_block != null && set_block.Block == null) {
6707 if (RootContext.Version <= LanguageVersion.ISO_2)
6708 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6710 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
6711 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
6715 void CreateAutomaticProperty ()
6717 // Create backing field
6718 Field field = new Field (
6720 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6721 new MemberName ("<" + GetFullName (MemberName) + ">k__BackingField", Location), null);
6722 if (!field.Define ())
6725 Parent.PartialContainer.AddField (field);
6728 Get.Block = new ToplevelBlock (ParametersCompiled.EmptyReadOnlyParameters, Location);
6729 Return r = new Return (new SimpleName (field.Name, Location), Location);
6730 Get.Block.AddStatement (r);
6733 Set.Block = new ToplevelBlock (Set.ParameterInfo, Location);
6734 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6735 Set.Block.AddStatement (new StatementExpression (a));
6738 public override bool Define ()
6740 if (!base.Define ())
6743 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6745 if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6746 CreateAutomaticProperty ();
6748 if (!DefineAccessors ())
6754 // FIXME - PropertyAttributes.HasDefault ?
6756 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6757 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6760 PropertyBuilder.SetGetMethod (GetBuilder);
6761 Parent.MemberCache.AddMember (GetBuilder, Get);
6765 PropertyBuilder.SetSetMethod (SetBuilder);
6766 Parent.MemberCache.AddMember (SetBuilder, Set);
6769 TypeManager.RegisterProperty (PropertyBuilder, this);
6770 Parent.MemberCache.AddMember (PropertyBuilder, this);
6774 public override void Emit ()
6776 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6777 Report.Error (842, Location,
6778 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6779 GetSignatureForError ());
6785 protected override PropertyInfo ResolveBaseProperty ()
6787 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6788 Parent.TypeBuilder, Name, ParametersCompiled.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6793 /// Gigantic workaround for lameness in SRE follows :
6794 /// This class derives from EventInfo and attempts to basically
6795 /// wrap around the EventBuilder so that FindMembers can quickly
6796 /// return this in it search for members
6798 public class MyEventBuilder : EventInfo {
6801 // We use this to "point" to our Builder which is
6802 // not really a MemberInfo
6804 EventBuilder MyBuilder;
6807 // We "catch" and wrap these methods
6809 MethodInfo raise, remove, add;
6811 EventAttributes attributes;
6812 Type declaring_type, reflected_type, event_type;
6817 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6819 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6821 // And now store the values in our own fields.
6823 declaring_type = type_builder;
6825 reflected_type = type_builder;
6827 attributes = event_attr;
6830 this.event_type = event_type;
6834 // Methods that you have to override. Note that you only need
6835 // to "implement" the variants that take the argument (those are
6836 // the "abstract" methods, the others (GetAddMethod()) are
6839 public override MethodInfo GetAddMethod (bool nonPublic)
6844 public override MethodInfo GetRemoveMethod (bool nonPublic)
6849 public override MethodInfo GetRaiseMethod (bool nonPublic)
6855 // These methods make "MyEventInfo" look like a Builder
6857 public void SetRaiseMethod (MethodBuilder raiseMethod)
6859 raise = raiseMethod;
6860 MyBuilder.SetRaiseMethod (raiseMethod);
6863 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6865 remove = removeMethod;
6866 MyBuilder.SetRemoveOnMethod (removeMethod);
6869 public void SetAddOnMethod (MethodBuilder addMethod)
6872 MyBuilder.SetAddOnMethod (addMethod);
6875 public void SetCustomAttribute (CustomAttributeBuilder cb)
6877 MyBuilder.SetCustomAttribute (cb);
6880 public override object [] GetCustomAttributes (bool inherit)
6882 // FIXME : There's nothing which can be seemingly done here because
6883 // we have no way of getting at the custom attribute objects of the
6888 public override object [] GetCustomAttributes (Type t, bool inherit)
6890 // FIXME : Same here !
6894 public override bool IsDefined (Type t, bool b)
6899 public override EventAttributes Attributes {
6905 public override string Name {
6911 public override Type DeclaringType {
6913 return declaring_type;
6917 public override Type ReflectedType {
6919 return reflected_type;
6923 public Type EventType {
6929 public void SetUsed ()
6931 if (my_event != null) {
6932 // my_event.SetAssigned ();
6933 my_event.SetMemberIsUsed ();
6939 /// For case when event is declared like property (with add and remove accessors).
6941 public class EventProperty: Event {
6942 abstract class AEventPropertyAccessor : AEventAccessor
6944 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6945 base (method, accessor, prefix)
6949 public override MethodBuilder Define (DeclSpace ds)
6951 CheckAbstractAndExtern (block != null);
6952 return base.Define (ds);
6955 public override string GetSignatureForError ()
6957 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6961 sealed class AddDelegateMethod: AEventPropertyAccessor
6963 public AddDelegateMethod (Event method, Accessor accessor):
6964 base (method, accessor, "add_")
6968 protected override MethodInfo DelegateMethodInfo {
6970 return TypeManager.delegate_combine_delegate_delegate;
6975 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6977 public RemoveDelegateMethod (Event method, Accessor accessor):
6978 base (method, accessor, "remove_")
6982 protected override MethodInfo DelegateMethodInfo {
6984 return TypeManager.delegate_remove_delegate_delegate;
6990 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6992 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6994 Attributes attrs, Accessor add, Accessor remove)
6995 : base (parent, type, mod_flags, name, attrs)
6997 Add = new AddDelegateMethod (this, add);
6998 Remove = new RemoveDelegateMethod (this, remove);
7001 public override bool Define()
7003 if (!base.Define ())
7010 public override string[] ValidAttributeTargets {
7012 return attribute_targets;
7018 /// Event is declared like field.
7020 public class EventField : Event {
7021 abstract class EventFieldAccessor : AEventAccessor
7023 protected EventFieldAccessor (Event method, string prefix)
7024 : base (method, prefix)
7028 protected override void EmitMethod(DeclSpace parent)
7030 if (method_data.implementing != null)
7031 parent.PartialContainer.PendingImplementations.ImplementMethod (
7032 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
7034 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7037 MethodBuilder mb = method_data.MethodBuilder;
7038 ILGenerator ig = mb.GetILGenerator ();
7040 // TODO: because we cannot use generics yet
7041 FieldInfo field_info = ((EventField)method).FieldBuilder;
7043 if (parent is Class) {
7044 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7047 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7048 ig.Emit (OpCodes.Ldsfld, field_info);
7049 ig.Emit (OpCodes.Ldarg_0);
7050 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7051 ig.Emit (OpCodes.Castclass, method.MemberType);
7052 ig.Emit (OpCodes.Stsfld, field_info);
7054 ig.Emit (OpCodes.Ldarg_0);
7055 ig.Emit (OpCodes.Ldarg_0);
7056 ig.Emit (OpCodes.Ldfld, field_info);
7057 ig.Emit (OpCodes.Ldarg_1);
7058 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7059 ig.Emit (OpCodes.Castclass, method.MemberType);
7060 ig.Emit (OpCodes.Stfld, field_info);
7062 ig.Emit (OpCodes.Ret);
7066 sealed class AddDelegateMethod: EventFieldAccessor
7068 public AddDelegateMethod (Event method):
7069 base (method, "add_")
7073 protected override MethodInfo DelegateMethodInfo {
7075 return TypeManager.delegate_combine_delegate_delegate;
7080 sealed class RemoveDelegateMethod: EventFieldAccessor
7082 public RemoveDelegateMethod (Event method):
7083 base (method, "remove_")
7087 protected override MethodInfo DelegateMethodInfo {
7089 return TypeManager.delegate_remove_delegate_delegate;
7095 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7096 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7098 public FieldBuilder FieldBuilder;
7099 public Expression Initializer;
7101 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7102 : base (parent, type, mod_flags, name, attrs)
7104 Add = new AddDelegateMethod (this);
7105 Remove = new RemoveDelegateMethod (this);
7108 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7110 if (a.Target == AttributeTargets.Field) {
7111 FieldBuilder.SetCustomAttribute (cb);
7115 if (a.Target == AttributeTargets.Method) {
7116 int errors = Report.Errors;
7117 Add.ApplyAttributeBuilder (a, cb);
7118 if (errors == Report.Errors)
7119 Remove.ApplyAttributeBuilder (a, cb);
7123 base.ApplyAttributeBuilder (a, cb);
7126 public override bool Define()
7128 if (!base.Define ())
7134 // FIXME: We are unable to detect whether generic event is used because
7135 // we are using FieldExpr instead of EventExpr for event access in that
7136 // case. When this issue will be fixed this hack can be removed.
7137 if (TypeManager.IsGenericType (MemberType))
7140 if (Add.IsInterfaceImplementation)
7143 FieldBuilder = Parent.TypeBuilder.DefineField (
7145 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7146 TypeManager.RegisterEventField (EventBuilder, this);
7148 if (Initializer != null) {
7149 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7150 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7151 GetSignatureForError ());
7155 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7156 new FieldInitializer (FieldBuilder, Initializer, this));
7162 public override string[] ValidAttributeTargets
7165 return IsInterface ? attribute_targets_interface : attribute_targets;
7170 public abstract class Event : PropertyBasedMember {
7171 public abstract class AEventAccessor : AbstractPropertyEventMethod
7173 protected readonly Event method;
7174 ImplicitParameter param_attr;
7176 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7178 protected AEventAccessor (Event method, string prefix)
7179 : base (method, prefix)
7181 this.method = method;
7182 this.ModFlags = method.ModFlags;
7185 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7186 : base (method, accessor, prefix)
7188 this.method = method;
7189 this.ModFlags = method.ModFlags;
7192 public bool IsInterfaceImplementation {
7193 get { return method_data.implementing != null; }
7196 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7198 if (a.IsInternalMethodImplAttribute) {
7199 method.is_external_implementation = true;
7202 base.ApplyAttributeBuilder (a, cb);
7205 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7207 if (a.Target == AttributeTargets.Parameter) {
7208 if (param_attr == null)
7209 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7211 param_attr.ApplyAttributeBuilder (a, cb);
7215 base.ApplyAttributeBuilder (a, cb);
7218 public override AttributeTargets AttributeTargets {
7220 return AttributeTargets.Method;
7224 public override bool IsClsComplianceRequired ()
7226 return method.IsClsComplianceRequired ();
7229 public virtual MethodBuilder Define (DeclSpace parent)
7231 method_data = new MethodData (method, method.ModFlags,
7232 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7234 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7237 MethodBuilder mb = method_data.MethodBuilder;
7238 ParameterInfo.ApplyAttributes (mb);
7242 protected abstract MethodInfo DelegateMethodInfo { get; }
7244 public override Type ReturnType {
7246 return TypeManager.void_type;
7250 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7252 return new EmitContext (
7253 this, method.Parent, Location, ig, ReturnType,
7254 method.ModFlags, false);
7257 public override ObsoleteAttribute GetObsoleteAttribute ()
7259 return method.GetObsoleteAttribute ();
7262 public override string[] ValidAttributeTargets {
7264 return attribute_targets;
7268 public override ParametersCompiled ParameterInfo {
7270 return method.parameters;
7276 const int AllowedModifiers =
7279 Modifiers.PROTECTED |
7280 Modifiers.INTERNAL |
7285 Modifiers.OVERRIDE |
7287 Modifiers.ABSTRACT |
7290 const int AllowedInterfaceModifiers =
7293 public AEventAccessor Add, Remove;
7294 public MyEventBuilder EventBuilder;
7295 public MethodBuilder AddBuilder, RemoveBuilder;
7297 ParametersCompiled parameters;
7299 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7300 : base (parent, null, type, mod_flags,
7301 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7306 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7308 if ((a.HasSecurityAttribute)) {
7309 a.Error_InvalidSecurityParent ();
7313 EventBuilder.SetCustomAttribute (cb);
7316 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7318 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7321 public override AttributeTargets AttributeTargets {
7323 return AttributeTargets.Event;
7327 public override bool Define ()
7329 if (!base.Define ())
7332 if (!TypeManager.IsDelegateType (MemberType)) {
7333 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7336 parameters = ParametersCompiled.CreateFullyResolved (
7337 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7342 if (TypeManager.delegate_combine_delegate_delegate == null) {
7343 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7344 TypeManager.delegate_type, "Combine", Location,
7345 TypeManager.delegate_type, TypeManager.delegate_type);
7347 if (TypeManager.delegate_remove_delegate_delegate == null) {
7348 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7349 TypeManager.delegate_type, "Remove", Location,
7350 TypeManager.delegate_type, TypeManager.delegate_type);
7354 // Now define the accessors
7357 AddBuilder = Add.Define (Parent);
7358 if (AddBuilder == null)
7361 RemoveBuilder = Remove.Define (Parent);
7362 if (RemoveBuilder == null)
7365 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7366 EventBuilder.SetAddOnMethod (AddBuilder);
7367 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7369 Parent.MemberCache.AddMember (EventBuilder, this);
7370 Parent.MemberCache.AddMember (AddBuilder, Add);
7371 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7376 public override void Emit ()
7378 if (OptAttributes != null) {
7379 OptAttributes.Emit ();
7383 Remove.Emit (Parent);
7388 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7390 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7391 Parent.TypeBuilder, Name);
7396 AParametersCollection pd = TypeManager.GetParameterData (mi);
7397 base_ret_type = pd.Types [0];
7402 // Represents header string for documentation comment.
7404 public override string DocCommentHeader {
7405 get { return "E:"; }
7410 public class Indexer : PropertyBase
7412 public class GetIndexerMethod : GetMethod
7414 ParametersCompiled parameters;
7416 public GetIndexerMethod (Indexer method):
7419 this.parameters = method.parameters;
7422 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7423 base (method, accessor)
7425 parameters = accessor.Parameters;
7428 public override MethodBuilder Define (DeclSpace parent)
7430 parameters.Resolve (ResolveContext);
7431 return base.Define (parent);
7434 public override bool EnableOverloadChecks (MemberCore overload)
7436 if (base.EnableOverloadChecks (overload)) {
7437 overload.caching_flags |= Flags.MethodOverloadsExist;
7444 public override ParametersCompiled ParameterInfo {
7451 public class SetIndexerMethod: SetMethod
7453 public SetIndexerMethod (Indexer method):
7456 parameters = ParametersCompiled.MergeGenerated (method.parameters, false, parameters [0], null);
7459 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7460 base (method, accessor)
7462 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7465 public override bool EnableOverloadChecks (MemberCore overload)
7467 if (base.EnableOverloadChecks (overload)) {
7468 overload.caching_flags |= Flags.MethodOverloadsExist;
7476 const int AllowedModifiers =
7479 Modifiers.PROTECTED |
7480 Modifiers.INTERNAL |
7484 Modifiers.OVERRIDE |
7489 const int AllowedInterfaceModifiers =
7492 public readonly ParametersCompiled parameters;
7494 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7495 ParametersCompiled parameters, Attributes attrs,
7496 Accessor get_block, Accessor set_block, bool define_set_first)
7497 : base (parent, type, mod,
7498 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7499 name, attrs, define_set_first)
7501 this.parameters = parameters;
7503 if (get_block == null)
7504 Get = new GetIndexerMethod (this);
7506 Get = new GetIndexerMethod (this, get_block);
7508 if (set_block == null)
7509 Set = new SetIndexerMethod (this);
7511 Set = new SetIndexerMethod (this, set_block);
7514 protected override bool CheckForDuplications ()
7516 return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7519 public override bool Define ()
7521 if (!base.Define ())
7524 if (!DefineParameters (parameters))
7527 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7528 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7529 if (indexer_attr != null) {
7530 // Remove the attribute from the list because it is not emitted
7531 OptAttributes.Attrs.Remove (indexer_attr);
7533 string name = indexer_attr.GetIndexerAttributeValue ();
7539 if (IsExplicitImpl) {
7540 Report.Error (415, indexer_attr.Location,
7541 "The `IndexerName' attribute is valid only on an " +
7542 "indexer that is not an explicit interface member declaration");
7546 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7547 Report.Error (609, indexer_attr.Location,
7548 "Cannot set the `IndexerName' attribute on an indexer marked override");
7554 if (InterfaceType != null) {
7555 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7556 if (base_IndexerName != Name)
7557 ShortName = base_IndexerName;
7560 if (!Parent.PartialContainer.AddMember (this) ||
7561 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7564 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7566 if (!DefineAccessors ())
7573 // Now name the parameters
7575 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7576 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7579 PropertyBuilder.SetGetMethod (GetBuilder);
7580 Parent.MemberCache.AddMember (GetBuilder, Get);
7584 PropertyBuilder.SetSetMethod (SetBuilder);
7585 Parent.MemberCache.AddMember (SetBuilder, Set);
7588 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7589 Parent.MemberCache.AddMember (PropertyBuilder, this);
7593 public override bool EnableOverloadChecks (MemberCore overload)
7595 if (overload is Indexer) {
7596 caching_flags |= Flags.MethodOverloadsExist;
7600 return base.EnableOverloadChecks (overload);
7603 public override string GetDocCommentName (DeclSpace ds)
7605 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7608 public override string GetSignatureForError ()
7610 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7611 if (MemberName.Left != null) {
7613 sb.Append (MemberName.Left.GetSignatureForError ());
7616 sb.Append (".this");
7617 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7618 return sb.ToString ();
7621 protected override PropertyInfo ResolveBaseProperty ()
7623 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7624 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7627 protected override bool VerifyClsCompliance ()
7629 if (!base.VerifyClsCompliance ())
7632 parameters.VerifyClsCompliance ();
7637 public class Operator : MethodOrOperator {
7639 const int AllowedModifiers =
7645 public enum OpType : byte {
7655 // Unary and Binary operators
7678 // Implicit and Explicit
7682 // Just because of enum
7686 public readonly OpType OperatorType;
7688 static readonly string [] [] names;
7692 names = new string[(int)OpType.TOP][];
7693 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7694 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7695 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7696 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7697 names [(int) OpType.True] = new string [] { "true", "op_True" };
7698 names [(int) OpType.False] = new string [] { "false", "op_False" };
7699 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7700 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7701 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7702 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7703 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7704 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7705 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7706 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7707 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7708 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7709 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7710 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7711 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7712 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7713 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7714 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7715 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7716 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7717 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7718 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7721 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7722 int mod_flags, ParametersCompiled parameters,
7723 ToplevelBlock block, Attributes attrs, Location loc)
7724 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7725 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7727 OperatorType = type;
7731 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7733 if (a.Type == TypeManager.conditional_attribute_type) {
7734 Error_ConditionalAttributeIsNotValid ();
7738 base.ApplyAttributeBuilder (a, cb);
7741 public override bool Define ()
7743 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7744 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7745 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7748 if (!base.Define ())
7751 // imlicit and explicit operator of same types are not allowed
7752 if (OperatorType == OpType.Explicit)
7753 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7754 else if (OperatorType == OpType.Implicit)
7755 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7757 Type declaring_type = MethodData.DeclaringType;
7758 Type return_type = MemberType;
7759 Type first_arg_type = ParameterTypes [0];
7761 Type first_arg_type_unwrap = first_arg_type;
7762 if (TypeManager.IsNullableType (first_arg_type))
7763 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7765 Type return_type_unwrap = return_type;
7766 if (TypeManager.IsNullableType (return_type))
7767 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7770 // Rules for conversion operators
7772 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7773 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7774 Report.Error (555, Location,
7775 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7780 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7781 conv_type = first_arg_type;
7782 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7783 conv_type = return_type;
7785 Report.Error (556, Location,
7786 "User-defined conversion must convert to or from the enclosing type");
7791 // Because IsInterface and IsClass are not supported
7793 if (!TypeManager.IsGenericParameter (conv_type)) {
7794 if (conv_type.IsInterface) {
7795 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7796 GetSignatureForError ());
7800 if (conv_type.IsClass) {
7801 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7802 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7803 GetSignatureForError ());
7807 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7808 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7809 GetSignatureForError ());
7814 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7815 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7816 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");
7819 } else if (Parameters.Count == 1) {
7820 // Checks for Unary operators
7822 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7823 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7824 Report.Error (448, Location,
7825 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7828 if (first_arg_type != declaring_type) {
7830 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7835 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7836 Report.Error (562, Location,
7837 "The parameter type of a unary operator must be the containing type");
7841 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7842 if (return_type != TypeManager.bool_type){
7845 "The return type of operator True or False " +
7852 // Checks for Binary operators
7854 if (first_arg_type != declaring_type &&
7855 Parameters.Types [1] != declaring_type){
7858 "One of the parameters of a binary operator must " +
7859 "be the containing type");
7867 protected override bool ResolveMemberType ()
7869 if (!base.ResolveMemberType ())
7872 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7876 // Operator cannot be override
7877 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7882 public static string GetName (OpType ot)
7884 return names [(int) ot] [0];
7887 public static string GetName (string metadata_name)
7889 for (int i = 0; i < names.Length; ++i) {
7890 if (names [i] [1] == metadata_name)
7891 return names [i] [0];
7896 public static string GetMetadataName (OpType ot)
7898 return names [(int) ot] [1];
7901 public static string GetMetadataName (string name)
7903 for (int i = 0; i < names.Length; ++i) {
7904 if (names [i] [0] == name)
7905 return names [i] [1];
7910 public OpType GetMatchingOperator ()
7912 switch (OperatorType) {
7913 case OpType.Equality:
7914 return OpType.Inequality;
7915 case OpType.Inequality:
7916 return OpType.Equality;
7918 return OpType.False;
7921 case OpType.GreaterThan:
7922 return OpType.LessThan;
7923 case OpType.LessThan:
7924 return OpType.GreaterThan;
7925 case OpType.GreaterThanOrEqual:
7926 return OpType.LessThanOrEqual;
7927 case OpType.LessThanOrEqual:
7928 return OpType.GreaterThanOrEqual;
7934 public override string GetSignatureForError ()
7936 StringBuilder sb = new StringBuilder ();
7937 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7938 sb.AppendFormat ("{0}.{1} operator {2}",
7939 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7942 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7945 sb.Append (Parameters.GetSignatureForError ());
7946 return sb.ToString ();
7951 // This is used to compare method signatures
7953 struct MethodSignature {
7955 public Type RetType;
7956 public Type [] Parameters;
7959 /// This delegate is used to extract methods which have the
7960 /// same signature as the argument
7962 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7964 public MethodSignature (string name, Type ret_type, Type [] parameters)
7969 if (parameters == null)
7970 Parameters = Type.EmptyTypes;
7972 Parameters = parameters;
7975 public override string ToString ()
7978 if (Parameters.Length != 0){
7979 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7980 for (int i = 0; i < Parameters.Length; i++){
7981 sb.Append (Parameters [i]);
7982 if (i+1 < Parameters.Length)
7985 pars = sb.ToString ();
7988 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7991 public override int GetHashCode ()
7993 return Name.GetHashCode ();
7996 public override bool Equals (Object o)
7998 MethodSignature other = (MethodSignature) o;
8000 if (other.Name != Name)
8003 if (other.RetType != RetType)
8006 if (Parameters == null){
8007 if (other.Parameters == null)
8012 if (other.Parameters == null)
8015 int c = Parameters.Length;
8016 if (other.Parameters.Length != c)
8019 for (int i = 0; i < c; i++)
8020 if (other.Parameters [i] != Parameters [i])
8026 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8028 MethodSignature sig = (MethodSignature) filter_criteria;
8030 if (m.Name != sig.Name)
8034 MethodInfo mi = m as MethodInfo;
8035 PropertyInfo pi = m as PropertyInfo;
8038 ReturnType = mi.ReturnType;
8039 else if (pi != null)
8040 ReturnType = pi.PropertyType;
8045 // we use sig.RetType == null to mean `do not check the
8046 // method return value.
8048 if (sig.RetType != null) {
8049 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8055 args = TypeManager.GetParameterData (mi).Types;
8057 args = TypeManager.GetParameterData (pi).Types;
8058 Type [] sigp = sig.Parameters;
8060 if (args.Length != sigp.Length)
8063 for (int i = args.Length - 1; i >= 0; i--)
8064 if (!TypeManager.IsEqual (args [i], sigp [i]))