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
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
34 using System.Collections;
35 using System.Collections.Specialized;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Security;
41 using System.Security.Permissions;
44 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
45 using XmlElement = System.Object;
50 using Mono.CompilerServices.SymbolWriter;
52 namespace Mono.CSharp {
64 /// This is the base class for structs and classes.
66 public abstract class TypeContainer : DeclSpace, IMemberContainer {
68 public class MemberCoreArrayList: ArrayList
71 /// Defines the MemberCore objects that are in this array
73 public virtual void DefineContainerMembers ()
75 foreach (MemberCore mc in this) {
78 } catch (Exception e) {
79 throw new InternalErrorException (mc, e);
84 public virtual void Emit ()
86 foreach (MemberCore mc in this)
91 public class OperatorArrayList: MemberCoreArrayList
93 TypeContainer container;
95 public OperatorArrayList (TypeContainer container)
97 this.container = container;
101 // Checks that some operators come in pairs:
107 // They are matched based on the return type and the argument types
109 void CheckPairedOperators ()
111 bool has_equality_or_inequality = false;
112 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
113 bool [] has_pair = new bool [operators.Length];
115 for (int i = 0; i < Count; ++i) {
116 if (operators [i] == null)
119 Operator o_a = operators [i];
120 Operator.OpType o_type = o_a.OperatorType;
121 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
122 has_equality_or_inequality = true;
124 Operator.OpType matching_type = o_a.GetMatchingOperator ();
125 if (matching_type == Operator.OpType.TOP) {
126 operators [i] = null;
130 for (int ii = 0; ii < Count; ++ii) {
131 Operator o_b = operators [ii];
132 if (o_b == null || o_b.OperatorType != matching_type)
135 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
138 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
141 operators [i] = null;
144 // Used to ignore duplicate user conversions
146 has_pair [ii] = true;
150 for (int i = 0; i < Count; ++i) {
151 if (operators [i] == null || has_pair [i])
154 Operator o = operators [i];
155 Report.Error (216, o.Location,
156 "The operator `{0}' requires a matching operator `{1}' to also be defined",
157 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
160 if (has_equality_or_inequality && Report.WarningLevel > 2) {
161 if (container.Methods == null || !container.HasEquals)
162 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
164 if (container.Methods == null || !container.HasGetHashCode)
165 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
169 public override void DefineContainerMembers ()
171 base.DefineContainerMembers ();
172 CheckPairedOperators ();
180 GetHashCode = 1 << 1,
181 HasStaticFieldInitializer = 1 << 2
185 // Whether this is a struct, class or interface
186 public readonly Kind Kind;
188 // Holds a list of classes and structures
189 protected ArrayList types;
191 MemberCoreArrayList ordered_explicit_member_list;
192 MemberCoreArrayList ordered_member_list;
194 // Holds the list of properties
195 MemberCoreArrayList properties;
197 // Holds the list of delegates
198 MemberCoreArrayList delegates;
200 // Holds the list of constructors
201 protected MemberCoreArrayList instance_constructors;
203 // Holds the list of fields
204 MemberCoreArrayList fields;
206 // Holds a list of fields that have initializers
207 protected ArrayList initialized_fields;
209 // Holds a list of static fields that have initializers
210 protected ArrayList initialized_static_fields;
212 // Holds the list of constants
213 protected MemberCoreArrayList constants;
215 // Holds the methods.
216 MemberCoreArrayList methods;
219 protected MemberCoreArrayList events;
221 // Holds the indexers
224 // Holds the operators
225 MemberCoreArrayList operators;
227 // Holds the compiler generated classes
228 ArrayList compiler_generated;
231 // Pointers to the default constructor and the default static constructor
233 protected Constructor default_constructor;
234 protected Constructor default_static_constructor;
237 // Points to the first non-static field added to the container.
239 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
240 // and the first one's as good as any.
242 FieldBase first_nonstatic_field = null;
245 // This one is computed after we can distinguish interfaces
246 // from classes from the arraylist `type_bases'
249 TypeExpr[] iface_exprs;
252 protected ArrayList type_bases;
254 bool members_resolved;
255 bool members_resolved_ok;
256 protected bool members_defined;
257 bool members_defined_ok;
259 // The interfaces we implement.
260 protected Type[] ifaces;
262 // The base member cache and our member cache
263 MemberCache base_cache;
264 protected MemberCache member_cache;
266 public const string DefaultIndexerName = "Item";
268 private bool seen_normal_indexers = false;
269 private string indexer_name = DefaultIndexerName;
271 private CachedMethods cached_method;
273 ArrayList partial_parts;
276 /// The pending methods that need to be implemented
277 // (interfaces or abstract methods)
279 PendingImplementation pending;
281 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
282 Attributes attrs, Kind kind)
283 : base (ns, parent, name, attrs)
285 if (parent != null && parent.NamespaceEntry != ns)
286 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
289 this.PartialContainer = this;
292 public bool AddMember (MemberCore symbol)
294 return AddToContainer (symbol, symbol.MemberName.MethodName);
297 protected virtual bool AddMemberType (DeclSpace ds)
299 return AddToContainer (ds, ds.Basename);
302 protected virtual void RemoveMemberType (DeclSpace ds)
304 RemoveFromContainer (ds.Basename);
307 public void AddConstant (Const constant)
309 if (!AddMember (constant))
312 if (constants == null)
313 constants = new MemberCoreArrayList ();
315 constants.Add (constant);
318 public TypeContainer AddTypeContainer (TypeContainer tc)
320 if (!AddMemberType (tc))
324 types = new MemberCoreArrayList ();
330 public virtual TypeContainer AddPartial (TypeContainer next_part)
332 return AddPartial (next_part, next_part.Basename);
335 protected TypeContainer AddPartial (TypeContainer next_part, string name)
337 next_part.ModFlags |= Modifiers.PARTIAL;
338 TypeContainer tc = defined_names [name] as TypeContainer;
341 return AddTypeContainer (next_part);
343 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
344 Report.SymbolRelatedToPreviousError (next_part);
345 Error_MissingPartialModifier (tc);
348 if (tc.Kind != next_part.Kind) {
349 Report.SymbolRelatedToPreviousError (tc);
350 Report.Error (261, next_part.Location,
351 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
352 next_part.GetSignatureForError ());
355 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
356 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
357 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
358 Report.SymbolRelatedToPreviousError (tc);
359 Report.Error (262, next_part.Location,
360 "Partial declarations of `{0}' have conflicting accessibility modifiers",
361 next_part.GetSignatureForError ());
364 if (tc.partial_parts == null)
365 tc.partial_parts = new ArrayList (1);
367 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
368 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
369 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
370 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
371 tc.ModFlags |= next_part.ModFlags;
373 tc.ModFlags |= next_part.ModFlags;
376 if (next_part.attributes != null) {
377 if (tc.attributes == null)
378 tc.attributes = next_part.attributes;
380 tc.attributes.AddAttributes (next_part.attributes.Attrs);
383 next_part.PartialContainer = tc;
384 tc.partial_parts.Add (next_part);
388 public virtual void RemoveTypeContainer (TypeContainer next_part)
391 types.Remove (next_part);
392 RemoveMemberType (next_part);
395 public void AddDelegate (Delegate d)
397 if (!AddMemberType (d))
400 if (delegates == null)
401 delegates = new MemberCoreArrayList ();
406 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
408 if (ordered_explicit_member_list == null) {
409 ordered_explicit_member_list = new MemberCoreArrayList ();
410 ordered_member_list = new MemberCoreArrayList ();
414 if (Kind == Kind.Interface) {
415 Report.Error (541, mc.Location,
416 "`{0}': explicit interface declaration can only be declared in a class or struct",
417 mc.GetSignatureForError ());
420 ordered_explicit_member_list.Add (mc);
421 alist.Insert (0, mc);
423 ordered_member_list.Add (mc);
429 public void AddMethod (Method method)
431 MemberName mn = method.MemberName;
432 if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
436 methods = new MemberCoreArrayList ();
438 if (method.MemberName.Left != null)
439 AddMemberToList (method, methods, true);
441 AddMemberToList (method, methods, false);
444 public void AddConstructor (Constructor c)
446 if (c.Name != MemberName.Name) {
447 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
450 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
451 if (!AddToContainer (c, is_static ?
452 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
455 if (is_static && c.Parameters.IsEmpty){
456 if (default_static_constructor != null) {
457 Report.SymbolRelatedToPreviousError (default_static_constructor);
458 Report.Error (111, c.Location,
459 "A member `{0}' is already defined. Rename this member or use different parameter types",
460 c.GetSignatureForError ());
464 default_static_constructor = c;
466 if (c.Parameters.IsEmpty)
467 default_constructor = c;
469 if (instance_constructors == null)
470 instance_constructors = new MemberCoreArrayList ();
472 instance_constructors.Add (c);
476 public bool AddField (FieldBase field)
478 if (!AddMember (field))
482 fields = new MemberCoreArrayList ();
486 if ((field.ModFlags & Modifiers.STATIC) != 0)
489 if (first_nonstatic_field == null) {
490 first_nonstatic_field = field;
494 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
495 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
496 Report.Warning (282, 3, field.Location,
497 "struct instance field `{0}' found in different declaration from instance field `{1}'",
498 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
503 public void AddProperty (Property prop)
505 if (!AddMember (prop) ||
506 !AddMember (prop.Get) || !AddMember (prop.Set))
509 if (properties == null)
510 properties = new MemberCoreArrayList ();
512 if (prop.MemberName.Left != null)
513 AddMemberToList (prop, properties, true);
515 AddMemberToList (prop, properties, false);
518 public void AddEvent (Event e)
523 if (e is EventProperty) {
524 if (!AddMember (e.Add))
527 if (!AddMember (e.Remove))
532 events = new MemberCoreArrayList ();
538 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
540 public void AddIndexer (Indexer i)
542 if (indexers == null)
543 indexers = new ArrayList ();
545 if (i.IsExplicitImpl)
546 AddMemberToList (i, indexers, true);
548 AddMemberToList (i, indexers, false);
551 public void AddOperator (Operator op)
556 if (operators == null)
557 operators = new OperatorArrayList (this);
562 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
564 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
566 if (compiler_generated == null)
567 compiler_generated = new ArrayList ();
569 compiler_generated.Add (c);
572 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
574 if (a.Type == TypeManager.default_member_type) {
575 if (Indexers != null) {
576 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
581 base.ApplyAttributeBuilder (a, cb);
584 public override AttributeTargets AttributeTargets {
586 throw new NotSupportedException ();
590 public ArrayList Types {
596 public MemberCoreArrayList Methods {
602 public ArrayList Constants {
608 protected Type BaseType {
610 return TypeBuilder.BaseType;
614 public ArrayList Fields {
620 public ArrayList InstanceConstructors {
622 return instance_constructors;
626 public ArrayList Properties {
632 public ArrayList Events {
638 public ArrayList Indexers {
644 public ArrayList Operators {
650 public ArrayList Delegates {
656 protected override TypeAttributes TypeAttr {
658 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
662 public string IndexerName {
664 return indexers == null ? DefaultIndexerName : indexer_name;
668 public bool IsComImport {
670 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
673 return OptAttributes.Contains (TypeManager.comimport_attr_type);
677 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
679 if ((field.ModFlags & Modifiers.STATIC) != 0){
680 if (initialized_static_fields == null) {
681 PartialContainer.HasStaticFieldInitializer = true;
682 initialized_static_fields = new ArrayList (4);
685 initialized_static_fields.Add (expression);
687 if (initialized_fields == null)
688 initialized_fields = new ArrayList (4);
690 initialized_fields.Add (expression);
694 public void ResolveFieldInitializers (EmitContext ec)
696 // Field initializers are tricky for partial classes. They have to
697 // share same costructor (block) but they have they own resolve scope.
698 DeclSpace orig = ec.DeclContainer;
700 if (partial_parts != null) {
701 foreach (TypeContainer part in partial_parts) {
702 ec.DeclContainer = part;
703 part.DoResolveFieldInitializers (ec);
706 ec.DeclContainer = PartialContainer;
707 DoResolveFieldInitializers (ec);
708 ec.DeclContainer = orig;
711 void DoResolveFieldInitializers (EmitContext ec)
714 if (initialized_static_fields == null)
717 bool has_complex_initializer = !RootContext.Optimize;
718 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
720 ExpressionStatement[] init = new ExpressionStatement [initialized_static_fields.Count];
721 for (i = 0; i < initialized_static_fields.Count; ++i) {
722 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
723 ExpressionStatement s = fi.ResolveStatement (ec);
725 s = EmptyExpressionStatement.Instance;
726 } else if (fi.IsComplexInitializer) {
727 has_complex_initializer |= true;
733 for (i = 0; i < initialized_static_fields.Count; ++i) {
734 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
736 // Need special check to not optimize code like this
737 // static int a = b = 5;
740 if (!has_complex_initializer && fi.IsDefaultInitializer)
743 ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
750 if (initialized_fields == null)
753 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
754 for (int i = 0; i < initialized_fields.Count; ++i) {
755 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
756 ExpressionStatement s = fi.ResolveStatement (ec);
761 // Field is re-initialized to its default value => removed
763 if (fi.IsDefaultInitializer && RootContext.Optimize)
766 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
772 // Emits the instance field initializers
774 public bool EmitFieldInitializers (EmitContext ec)
776 if (partial_parts != null) {
777 foreach (TypeContainer part in partial_parts)
778 part.EmitFieldInitializers (ec);
784 fields = initialized_static_fields;
786 fields = initialized_fields;
792 foreach (FieldInitializer f in fields) {
793 f.EmitStatement (ec);
798 public override string DocComment {
810 public PendingImplementation PendingImplementations {
811 get { return pending; }
814 public override bool GetClsCompliantAttributeValue ()
816 if (PartialContainer != this)
817 return PartialContainer.GetClsCompliantAttributeValue ();
819 return base.GetClsCompliantAttributeValue ();
822 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
824 // FIXME: get rid of partial_parts and store lists of bases of each part here
825 // assumed, not verified: 'part' is in 'partial_parts'
826 ((TypeContainer) part).type_bases = bases;
830 /// This function computes the Base class and also the
831 /// list of interfaces that the class or struct @c implements.
833 /// The return value is an array (might be null) of
834 /// interfaces implemented (as Types).
836 /// The @base_class argument is set to the base object or null
837 /// if this is `System.Object'.
839 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
842 if (type_bases == null)
845 int count = type_bases.Count;
846 TypeExpr [] ifaces = null;
847 for (int i = 0, j = 0; i < count; i++){
848 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
851 // Standard ResolveAsTypeTerminal cannot be used in this case because
852 // it does ObsoleteAttribute and constraint checks which require
853 // base type to be set
855 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
856 if (fne_resolved == null)
859 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
860 base_class = fne_resolved;
865 ifaces = new TypeExpr [count - i];
867 if (fne_resolved.Type.IsInterface) {
868 for (int ii = 0; ii < j; ++ii) {
869 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
870 Report.Error (528, Location, "`{0}' is already listed in interface list",
871 fne_resolved.GetSignatureForError ());
876 if (Kind == Kind.Interface && !fne_resolved.AsAccessible (this)) {
877 Report.Error (61, fne.Location,
878 "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
879 fne_resolved.GetSignatureForError (), GetSignatureForError ());
882 Report.SymbolRelatedToPreviousError (fne_resolved.Type);
883 if (Kind != Kind.Class) {
884 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
885 } else if (base_class != null)
886 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
887 GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
889 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
890 GetSignatureForError (), fne_resolved.GetSignatureForError ());
894 ifaces [j++] = fne_resolved;
900 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
902 ArrayList ifaces = new ArrayList (0);
903 if (iface_exprs != null)
904 ifaces.AddRange (iface_exprs);
906 foreach (TypeContainer part in partial_parts) {
907 TypeExpr new_base_class;
908 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
909 if (new_base_class != TypeManager.system_object_expr) {
910 if (base_class == TypeManager.system_object_expr)
911 base_class = new_base_class;
913 if (new_base_class != null && !new_base_class.Equals (base_class)) {
914 Report.SymbolRelatedToPreviousError (base_class.Location, "");
915 Report.Error (263, part.Location,
916 "Partial declarations of `{0}' must not specify different base classes",
917 part.GetSignatureForError ());
924 if (new_ifaces == null)
927 foreach (TypeExpr iface in new_ifaces) {
928 if (ifaces.Contains (iface))
935 if (ifaces.Count == 0)
938 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
941 bool CheckGenericInterfaces (Type[] ifaces)
944 ArrayList already_checked = new ArrayList ();
946 for (int i = 0; i < ifaces.Length; i++) {
947 Type iface = ifaces [i];
948 foreach (Type t in already_checked) {
952 Type[] inferred = new Type [CountTypeParameters];
953 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
956 Report.Error (695, Location,
957 "`{0}' cannot implement both `{1}' and `{2}' " +
958 "because they may unify for some type parameter substitutions",
959 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
960 TypeManager.CSharpName (t));
964 already_checked.Add (iface);
973 bool CreateTypeBuilder ()
976 Type default_parent = null;
977 if (Kind == Kind.Struct)
978 default_parent = TypeManager.value_type;
979 else if (Kind == Kind.Enum)
980 default_parent = TypeManager.enum_type;
983 // Sets .size to 1 for structs with no instance fields
985 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
988 if (TypeManager.NamespaceClash (Name, Location)) {
992 ModuleBuilder builder = CodeGen.Module.Builder;
993 TypeBuilder = builder.DefineType (
994 Name, TypeAttr, default_parent, type_size);
996 TypeBuilder builder = Parent.TypeBuilder;
998 TypeBuilder = builder.DefineNestedType (
999 Basename, TypeAttr, default_parent, type_size);
1001 } catch (ArgumentException) {
1002 Report.RuntimeMissingSupport (Location, "static classes");
1006 TypeManager.AddUserType (this);
1010 string[] param_names = new string [TypeParameters.Length];
1011 for (int i = 0; i < TypeParameters.Length; i++)
1012 param_names [i] = TypeParameters [i].Name;
1014 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
1016 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1017 for (int i = offset; i < gen_params.Length; i++)
1018 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1025 bool DefineBaseTypes ()
1027 iface_exprs = ResolveBaseTypes (out base_type);
1028 if (partial_parts != null) {
1029 iface_exprs = GetNormalPartialBases (ref base_type);
1033 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1034 // which in turn should have called DefineType()s on base types if necessary.
1036 // None of the code below should trigger DefineType()s on classes that we depend on.
1037 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1039 // Let's do it as soon as possible, since code below can call DefineType() on classes
1040 // that depend on us to be populated before they are.
1042 if (!(this is CompilerGeneratedClass))
1043 RootContext.RegisterOrder (this);
1045 if (!CheckRecursiveDefinition (this))
1048 if (base_type != null && base_type.Type != null) {
1049 TypeBuilder.SetParent (base_type.Type);
1052 // add interfaces that were not added at type creation
1053 if (iface_exprs != null) {
1054 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1058 foreach (Type itype in ifaces)
1059 TypeBuilder.AddInterfaceImplementation (itype);
1061 if (!CheckGenericInterfaces (ifaces))
1064 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1071 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1073 public TypeBuilder CreateType ()
1075 if (TypeBuilder != null)
1081 if (!CreateTypeBuilder ()) {
1086 if (partial_parts != null) {
1087 foreach (TypeContainer part in partial_parts)
1088 part.TypeBuilder = TypeBuilder;
1091 if (Types != null) {
1092 foreach (TypeContainer tc in Types) {
1093 if (tc.CreateType () == null) {
1105 public override TypeBuilder DefineType ()
1112 type_defined = true;
1114 if (CreateType () == null) {
1119 if (!DefineBaseTypes ()) {
1124 if (!ResolveMembers ()) {
1129 if (!DefineNestedTypes ()) {
1137 bool ResolveMembers ()
1139 if (members_resolved)
1140 return members_resolved_ok;
1142 members_resolved_ok = DoResolveMembers ();
1143 members_resolved = true;
1145 return members_resolved_ok;
1148 protected virtual bool DoResolveMembers ()
1150 if (methods != null) {
1151 foreach (Method method in methods) {
1152 if (!method.ResolveMembers ())
1157 // TODO: this is not really needed
1158 if (operators != null) {
1159 foreach (Operator o in operators) {
1160 if (!o.ResolveMembers ())
1168 public override void SetParameterInfo (ArrayList constraints_list)
1170 base.SetParameterInfo (constraints_list);
1172 if (!is_generic || PartialContainer == this)
1175 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1176 for (int i = 0; i < tc_names.Length; ++i) {
1177 if (tc_names [i].Name != type_params [i].Name) {
1178 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1179 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1180 GetSignatureForError ());
1186 void UpdateTypeParameterConstraints (TypeContainer part)
1188 TypeParameter[] current_params = CurrentTypeParameters;
1189 for (int i = 0; i < current_params.Length; i++) {
1190 Constraints c = part.CurrentTypeParameters [i].Constraints;
1194 if (current_params [i].UpdateConstraints (part, c))
1197 Report.SymbolRelatedToPreviousError (Location, "");
1198 Report.Error (265, part.Location,
1199 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1200 GetSignatureForError (), current_params [i].GetSignatureForError ());
1204 public bool ResolveType ()
1206 if (!DoResolveType ())
1209 if (compiler_generated != null) {
1210 foreach (CompilerGeneratedClass c in compiler_generated)
1211 if (!c.ResolveType ())
1218 protected virtual bool DoResolveType ()
1220 if ((base_type != null) &&
1221 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1229 if (PartialContainer != this)
1230 throw new InternalErrorException ();
1232 TypeExpr current_type = null;
1234 foreach (TypeParameter type_param in CurrentTypeParameters) {
1235 if (!type_param.Resolve (this)) {
1241 if (partial_parts != null && is_generic) {
1242 foreach (TypeContainer part in partial_parts)
1243 UpdateTypeParameterConstraints (part);
1246 foreach (TypeParameter type_param in TypeParameters) {
1247 if (!type_param.DefineType (this)) {
1253 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1254 current_type = current_type.ResolveAsTypeTerminal (this, false);
1255 if (current_type == null) {
1260 CurrentType = current_type.Type;
1264 protected virtual bool DefineNestedTypes ()
1266 if (Types != null) {
1267 foreach (TypeContainer tc in Types)
1268 if (tc.DefineType () == null)
1272 if (Delegates != null) {
1273 foreach (Delegate d in Delegates)
1274 if (d.DefineType () == null)
1281 TypeContainer InTransit;
1283 protected bool CheckRecursiveDefinition (TypeContainer tc)
1285 if (InTransit != null) {
1286 Report.SymbolRelatedToPreviousError (this);
1287 if (this is Interface)
1289 529, tc.Location, "Inherited interface `{0}' causes a " +
1290 "cycle in the interface hierarchy of `{1}'",
1291 GetSignatureForError (), tc.GetSignatureForError ());
1294 146, tc.Location, "Circular base class dependency " +
1295 "involving `{0}' and `{1}'",
1296 tc.GetSignatureForError (), GetSignatureForError ());
1302 if (base_type != null && base_type.Type != null) {
1303 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1304 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1305 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1309 if (iface_exprs != null) {
1310 foreach (TypeExpr iface in iface_exprs) {
1311 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1312 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1313 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1318 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1325 public static void Error_KeywordNotAllowed (Location loc)
1327 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1331 /// Populates our TypeBuilder with fields and methods
1333 public override bool DefineMembers ()
1335 if (members_defined)
1336 return members_defined_ok;
1338 if (!base.DefineMembers ())
1341 members_defined_ok = DoDefineMembers ();
1342 members_defined = true;
1344 return members_defined_ok;
1347 protected virtual bool DoDefineMembers ()
1349 if (iface_exprs != null) {
1350 foreach (TypeExpr iface in iface_exprs) {
1351 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1352 if ((oa != null) && !IsInObsoleteScope)
1353 AttributeTester.Report_ObsoleteMessage (
1354 oa, iface.GetSignatureForError (), Location);
1356 ConstructedType ct = iface as ConstructedType;
1357 if ((ct != null) && !ct.CheckConstraints (this))
1362 if (base_type != null) {
1363 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1364 if (obsolete_attr != null && !IsInObsoleteScope)
1365 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1367 ConstructedType ct = base_type as ConstructedType;
1368 if ((ct != null) && !ct.CheckConstraints (this))
1371 member_cache = new MemberCache (base_type.Type, this);
1372 } else if (Kind == Kind.Interface) {
1373 member_cache = new MemberCache (null, this);
1374 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1375 for (int i = 0; i < ifaces.Length; ++i)
1376 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1378 member_cache = new MemberCache (null, this);
1382 foreach (TypeContainer tc in types)
1383 member_cache.AddNestedType (tc);
1385 if (delegates != null)
1386 foreach (Delegate d in delegates)
1387 member_cache.AddNestedType (d);
1389 if (partial_parts != null) {
1390 foreach (TypeContainer part in partial_parts)
1391 part.member_cache = member_cache;
1395 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1396 if (conflict_symbol == null) {
1397 if ((ModFlags & Modifiers.NEW) != 0)
1398 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1400 if ((ModFlags & Modifiers.NEW) == 0) {
1401 Report.SymbolRelatedToPreviousError (conflict_symbol);
1402 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1403 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1408 DefineContainerMembers (constants);
1409 DefineContainerMembers (fields);
1411 if (Kind == Kind.Struct || Kind == Kind.Class) {
1412 pending = PendingImplementation.GetPendingImplementations (this);
1416 // Constructors are not in the defined_names array
1418 DefineContainerMembers (instance_constructors);
1420 DefineContainerMembers (events);
1421 DefineContainerMembers (ordered_explicit_member_list);
1422 DefineContainerMembers (ordered_member_list);
1424 DefineContainerMembers (operators);
1425 DefineContainerMembers (delegates);
1427 ComputeIndexerName();
1428 CheckEqualsAndGetHashCode();
1430 if (CurrentType != null) {
1431 GenericType = CurrentType;
1436 // FIXME: This hack is needed because member cache does not work
1437 // with generic types, we rely on runtime to inflate dynamic types.
1438 // TODO: This hack requires member cache refactoring to be removed
1440 if (TypeBuilder.IsGenericType)
1441 member_cache = new MemberCache (this);
1447 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1450 mcal.DefineContainerMembers ();
1453 protected virtual void ComputeIndexerName ()
1455 if (indexers == null)
1458 string class_indexer_name = null;
1461 // If there's both an explicit and an implicit interface implementation, the
1462 // explicit one actually implements the interface while the other one is just
1463 // a normal indexer. See bug #37714.
1466 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1467 foreach (Indexer i in indexers) {
1468 if (i.InterfaceType != null) {
1469 if (seen_normal_indexers)
1470 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1474 seen_normal_indexers = true;
1476 if (class_indexer_name == null) {
1477 class_indexer_name = i.ShortName;
1481 if (i.ShortName != class_indexer_name)
1482 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");
1485 if (class_indexer_name != null)
1486 indexer_name = class_indexer_name;
1489 protected virtual void EmitIndexerName ()
1491 if (!seen_normal_indexers)
1494 if (TypeManager.default_member_ctor == null) {
1495 if (TypeManager.default_member_type == null) {
1496 TypeManager.default_member_type = TypeManager.CoreLookupType (
1497 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1499 if (TypeManager.default_member_type == null)
1503 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1504 TypeManager.default_member_type, Location, TypeManager.string_type);
1506 if (TypeManager.default_member_ctor == null)
1510 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1511 TypeBuilder.SetCustomAttribute (cb);
1514 protected virtual void CheckEqualsAndGetHashCode ()
1516 if (methods == null)
1519 if (HasEquals && !HasGetHashCode) {
1520 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1524 public override bool Define ()
1526 CheckProtectedModifier ();
1530 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1532 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1536 /// This function is based by a delegate to the FindMembers routine
1538 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1544 /// This filter is used by FindMembers, and we just keep
1545 /// a global for the filter to `AlwaysAccept'
1547 static MemberFilter accepting_filter;
1550 static TypeContainer ()
1552 accepting_filter = new MemberFilter (AlwaysAccept);
1555 public MethodInfo[] GetMethods ()
1557 ArrayList members = new ArrayList ();
1561 if (methods != null) {
1562 int len = methods.Count;
1563 for (int i = 0; i < len; i++) {
1564 Method m = (Method) methods [i];
1566 members.Add (m.MethodBuilder);
1570 if (operators != null) {
1571 int len = operators.Count;
1572 for (int i = 0; i < len; i++) {
1573 Operator o = (Operator) operators [i];
1575 members.Add (o.MethodBuilder);
1579 if (properties != null) {
1580 int len = properties.Count;
1581 for (int i = 0; i < len; i++) {
1582 Property p = (Property) properties [i];
1584 if (p.GetBuilder != null)
1585 members.Add (p.GetBuilder);
1586 if (p.SetBuilder != null)
1587 members.Add (p.SetBuilder);
1591 if (indexers != null) {
1592 int len = indexers.Count;
1593 for (int i = 0; i < len; i++) {
1594 Indexer ix = (Indexer) indexers [i];
1596 if (ix.GetBuilder != null)
1597 members.Add (ix.GetBuilder);
1598 if (ix.SetBuilder != null)
1599 members.Add (ix.SetBuilder);
1603 if (events != null) {
1604 int len = events.Count;
1605 for (int i = 0; i < len; i++) {
1606 Event e = (Event) events [i];
1608 if (e.AddBuilder != null)
1609 members.Add (e.AddBuilder);
1610 if (e.RemoveBuilder != null)
1611 members.Add (e.RemoveBuilder);
1615 MethodInfo[] retMethods = new MethodInfo [members.Count];
1616 members.CopyTo (retMethods, 0);
1620 // Indicated whether container has StructLayout attribute set Explicit
1621 public bool HasExplicitLayout {
1622 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1623 set { caching_flags |= Flags.HasExplicitLayout; }
1626 public bool HasStructLayout {
1627 get { return (caching_flags & Flags.HasStructLayout) != 0; }
1628 set { caching_flags |= Flags.HasStructLayout; }
1632 // Return the nested type with name @name. Ensures that the nested type
1633 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1635 public Type FindNestedType (string name)
1637 if (PartialContainer != this)
1638 throw new InternalErrorException ("should not happen");
1640 ArrayList [] lists = { types, delegates };
1642 for (int j = 0; j < lists.Length; ++j) {
1643 ArrayList list = lists [j];
1647 int len = list.Count;
1648 for (int i = 0; i < len; ++i) {
1649 DeclSpace ds = (DeclSpace) list [i];
1650 if (ds.Basename == name) {
1651 return ds.DefineType ();
1659 private void FindMembers_NestedTypes (int modflags,
1660 BindingFlags bf, MemberFilter filter, object criteria,
1661 ref ArrayList members)
1663 ArrayList [] lists = { types, delegates };
1665 for (int j = 0; j < lists.Length; ++j) {
1666 ArrayList list = lists [j];
1670 int len = list.Count;
1671 for (int i = 0; i < len; i++) {
1672 DeclSpace ds = (DeclSpace) list [i];
1674 if ((ds.ModFlags & modflags) == 0)
1677 TypeBuilder tb = ds.TypeBuilder;
1679 if (!(criteria is string) || ds.Basename.Equals (criteria))
1680 tb = ds.DefineType ();
1683 if (tb != null && (filter (tb, criteria) == true)) {
1684 if (members == null)
1685 members = new ArrayList ();
1694 /// This method returns the members of this type just like Type.FindMembers would
1695 /// Only, we need to use this for types which are _being_ defined because MS'
1696 /// implementation can't take care of that.
1699 // FIXME: return an empty static array instead of null, that cleans up
1700 // some code and is consistent with some coding conventions I just found
1704 // Notice that in various cases we check if our field is non-null,
1705 // something that would normally mean that there was a bug elsewhere.
1707 // The problem happens while we are defining p-invoke methods, as those
1708 // will trigger a FindMembers, but this happens before things are defined
1710 // Since the whole process is a no-op, it is fine to check for null here.
1712 // TODO: This approach will be one day completely removed, it's already
1713 // used at few places only
1716 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1717 MemberFilter filter, object criteria)
1719 ArrayList members = null;
1722 if ((bf & BindingFlags.Public) != 0)
1723 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1725 if ((bf & BindingFlags.NonPublic) != 0)
1726 modflags |= Modifiers.PRIVATE;
1728 int static_mask = 0, static_flags = 0;
1729 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1730 case BindingFlags.Static:
1731 static_mask = static_flags = Modifiers.STATIC;
1734 case BindingFlags.Instance:
1735 static_mask = Modifiers.STATIC;
1740 static_mask = static_flags = 0;
1744 Timer.StartTimer (TimerType.TcFindMembers);
1747 filter = accepting_filter;
1749 if ((mt & MemberTypes.Field) != 0) {
1750 if (fields != null) {
1751 int len = fields.Count;
1752 for (int i = 0; i < len; i++) {
1753 FieldBase f = (FieldBase) fields [i];
1755 if ((f.ModFlags & modflags) == 0)
1757 if ((f.ModFlags & static_mask) != static_flags)
1760 FieldBuilder fb = f.FieldBuilder;
1761 if (fb != null && filter (fb, criteria) == true) {
1762 if (members == null)
1763 members = new ArrayList ();
1770 if (constants != null) {
1771 int len = constants.Count;
1772 for (int i = 0; i < len; i++) {
1773 Const con = (Const) constants [i];
1775 if ((con.ModFlags & modflags) == 0)
1777 if ((con.ModFlags & static_mask) != static_flags)
1780 FieldBuilder fb = con.FieldBuilder;
1783 fb = con.FieldBuilder;
1785 if (fb != null && filter (fb, criteria) == true) {
1786 if (members == null)
1787 members = new ArrayList ();
1795 if ((mt & MemberTypes.Method) != 0) {
1796 if (methods != null) {
1797 int len = methods.Count;
1798 for (int i = 0; i < len; i++) {
1799 Method m = (Method) methods [i];
1801 if ((m.ModFlags & modflags) == 0)
1803 if ((m.ModFlags & static_mask) != static_flags)
1806 MethodBuilder mb = m.MethodBuilder;
1808 if (mb != null && filter (mb, criteria) == true) {
1809 if (members == null)
1810 members = new ArrayList ();
1817 if (operators != null) {
1818 int len = operators.Count;
1819 for (int i = 0; i < len; i++) {
1820 Operator o = (Operator) operators [i];
1822 if ((o.ModFlags & modflags) == 0)
1824 if ((o.ModFlags & static_mask) != static_flags)
1827 MethodBuilder ob = o.MethodBuilder;
1828 if (ob != null && filter (ob, criteria) == true) {
1829 if (members == null)
1830 members = new ArrayList ();
1837 if (events != null) {
1838 foreach (Event e in events) {
1839 if ((e.ModFlags & modflags) == 0)
1841 if ((e.ModFlags & static_mask) != static_flags)
1844 MethodBuilder b = e.AddBuilder;
1845 if (b != null && filter (b, criteria)) {
1846 if (members == null)
1847 members = new ArrayList (4);
1852 b = e.RemoveBuilder;
1853 if (b != null && filter (b, criteria)) {
1854 if (members == null)
1855 members = new ArrayList (4);
1862 if (properties != null) {
1863 int len = properties.Count;
1864 for (int i = 0; i < len; i++) {
1865 Property p = (Property) properties [i];
1867 if ((p.ModFlags & modflags) == 0)
1869 if ((p.ModFlags & static_mask) != static_flags)
1875 if (b != null && filter (b, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1883 if (b != null && filter (b, criteria) == true) {
1884 if (members == null)
1885 members = new ArrayList ();
1892 if (indexers != null) {
1893 int len = indexers.Count;
1894 for (int i = 0; i < len; i++) {
1895 Indexer ix = (Indexer) indexers [i];
1897 if ((ix.ModFlags & modflags) == 0)
1899 if ((ix.ModFlags & static_mask) != static_flags)
1905 if (b != null && filter (b, criteria) == true) {
1906 if (members == null)
1907 members = new ArrayList ();
1913 if (b != null && filter (b, criteria) == true) {
1914 if (members == null)
1915 members = new ArrayList ();
1923 if ((mt & MemberTypes.Event) != 0) {
1924 if (events != null) {
1925 int len = events.Count;
1926 for (int i = 0; i < len; i++) {
1927 Event e = (Event) events [i];
1929 if ((e.ModFlags & modflags) == 0)
1931 if ((e.ModFlags & static_mask) != static_flags)
1934 MemberInfo eb = e.EventBuilder;
1935 if (eb != null && filter (eb, criteria) == true) {
1936 if (members == null)
1937 members = new ArrayList ();
1939 members.Add (e.EventBuilder);
1945 if ((mt & MemberTypes.Property) != 0){
1946 if (properties != null) {
1947 int len = properties.Count;
1948 for (int i = 0; i < len; i++) {
1949 Property p = (Property) properties [i];
1951 if ((p.ModFlags & modflags) == 0)
1953 if ((p.ModFlags & static_mask) != static_flags)
1956 MemberInfo pb = p.PropertyBuilder;
1957 if (pb != null && filter (pb, criteria) == true) {
1958 if (members == null)
1959 members = new ArrayList ();
1961 members.Add (p.PropertyBuilder);
1966 if (indexers != null) {
1967 int len = indexers.Count;
1968 for (int i = 0; i < len; i++) {
1969 Indexer ix = (Indexer) indexers [i];
1971 if ((ix.ModFlags & modflags) == 0)
1973 if ((ix.ModFlags & static_mask) != static_flags)
1976 MemberInfo ib = ix.PropertyBuilder;
1977 if (ib != null && filter (ib, criteria) == true) {
1978 if (members == null)
1979 members = new ArrayList ();
1981 members.Add (ix.PropertyBuilder);
1987 if ((mt & MemberTypes.NestedType) != 0)
1988 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1990 if ((mt & MemberTypes.Constructor) != 0){
1991 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1992 int len = instance_constructors.Count;
1993 for (int i = 0; i < len; i++) {
1994 Constructor c = (Constructor) instance_constructors [i];
1996 ConstructorBuilder cb = c.ConstructorBuilder;
1997 if (cb != null && filter (cb, criteria) == true) {
1998 if (members == null)
1999 members = new ArrayList ();
2006 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2007 ConstructorBuilder cb =
2008 default_static_constructor.ConstructorBuilder;
2010 if (cb != null && filter (cb, criteria) == true) {
2011 if (members == null)
2012 members = new ArrayList ();
2020 // Lookup members in base if requested.
2022 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2023 if (TypeBuilder.BaseType != null) {
2024 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2025 if (list.Count > 0) {
2026 if (members == null)
2027 members = new ArrayList ();
2029 members.AddRange (list);
2034 Timer.StopTimer (TimerType.TcFindMembers);
2036 if (members == null)
2037 return MemberList.Empty;
2039 return new MemberList (members);
2042 public override MemberCache MemberCache {
2044 return member_cache;
2048 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2049 MemberFilter filter, object criteria)
2051 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2054 return ds.FindMembers (mt, bf, filter, criteria);
2056 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2060 /// Emits the values for the constants
2062 public void EmitConstants ()
2064 if (constants != null)
2065 foreach (Const con in constants)
2070 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2075 foreach (MemberCore mc in al) {
2076 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2079 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2080 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2085 public virtual void VerifyMembers ()
2088 // Check for internal or private fields that were never assigned
2090 if (Report.WarningLevel >= 3) {
2091 CheckMemberUsage (properties, "property");
2092 CheckMemberUsage (methods, "method");
2093 CheckMemberUsage (constants, "constant");
2095 if (fields != null){
2096 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2097 foreach (FieldBase f in fields) {
2098 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2099 if (is_type_exposed)
2102 f.SetMemberIsUsed ();
2106 if ((f.caching_flags & Flags.IsAssigned) == 0)
2107 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2110 const int error_code = 414;
2112 const int error_code = 169;
2114 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2115 f.GetSignatureForError ());
2121 // Only report 649 on level 4
2123 if (Report.WarningLevel < 4)
2126 if ((f.caching_flags & Flags.IsAssigned) != 0)
2130 // Don't be pendatic over serializable attributes
2132 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2135 Constant c = New.Constantify (f.MemberType);
2136 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2137 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2143 // TODO: move to ClassOrStruct
2144 void EmitConstructors ()
2146 if (instance_constructors == null)
2149 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2150 bool has_compliant_args = false;
2152 foreach (Constructor c in instance_constructors) {
2156 catch (Exception e) {
2157 throw new InternalErrorException (c, e);
2160 if (has_compliant_args)
2163 has_compliant_args = c.HasCompliantArgs;
2165 if (!has_compliant_args)
2166 Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2168 foreach (Constructor c in instance_constructors) {
2172 catch (Exception e) {
2173 throw new InternalErrorException (c, e);
2180 /// Emits the code, this step is performed after all
2181 /// the types, enumerations, constructors
2183 public virtual void EmitType ()
2185 if (OptAttributes != null)
2186 OptAttributes.Emit ();
2190 EmitConstructors ();
2192 // Can not continue if constants are broken
2194 if (Report.Errors > 0)
2197 if (default_static_constructor != null)
2198 default_static_constructor.Emit ();
2200 if (operators != null)
2201 foreach (Operator o in operators)
2204 if (properties != null)
2205 foreach (Property p in properties)
2208 if (indexers != null) {
2209 foreach (Indexer indx in indexers)
2214 if (events != null){
2215 foreach (Event e in Events)
2219 if (methods != null) {
2220 for (int i = 0; i < methods.Count; ++i)
2221 ((Method) methods [i]).Emit ();
2225 foreach (FieldBase f in fields)
2228 if (delegates != null) {
2229 foreach (Delegate d in Delegates) {
2234 if (pending != null)
2235 pending.VerifyPendingMethods ();
2237 if (Report.Errors > 0)
2240 if (compiler_generated != null) {
2241 for (int i = 0; i < compiler_generated.Count; ++i)
2242 ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2246 public override void CloseType ()
2248 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2252 caching_flags |= Flags.CloseTypeCreated;
2253 TypeBuilder.CreateType ();
2254 } catch (TypeLoadException){
2256 // This is fine, the code still created the type
2258 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2259 // Console.WriteLine (e.Message);
2260 } catch (Exception e) {
2261 throw new InternalErrorException (this, e);
2265 foreach (TypeContainer tc in Types)
2266 if (tc.Kind == Kind.Struct)
2269 foreach (TypeContainer tc in Types)
2270 if (tc.Kind != Kind.Struct)
2274 if (Delegates != null)
2275 foreach (Delegate d in Delegates)
2278 if (compiler_generated != null)
2279 foreach (CompilerGeneratedClass c in compiler_generated)
2286 initialized_fields = null;
2287 initialized_static_fields = null;
2289 ordered_explicit_member_list = null;
2290 ordered_member_list = null;
2295 compiler_generated = null;
2296 default_constructor = null;
2297 default_static_constructor = null;
2299 OptAttributes = null;
2302 member_cache = null;
2306 // Performs the validation on a Method's modifiers (properties have
2307 // the same properties).
2309 public bool MethodModifiersValid (MemberCore mc)
2311 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2312 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2313 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2315 int flags = mc.ModFlags;
2318 // At most one of static, virtual or override
2320 if ((flags & Modifiers.STATIC) != 0){
2321 if ((flags & vao) != 0){
2322 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2323 mc.GetSignatureForError ());
2328 if (Kind == Kind.Struct){
2329 if ((flags & va) != 0){
2330 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2335 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2336 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2337 mc.GetSignatureForError ());
2342 // If the declaration includes the abstract modifier, then the
2343 // declaration does not include static, virtual or extern
2345 if ((flags & Modifiers.ABSTRACT) != 0){
2346 if ((flags & Modifiers.EXTERN) != 0){
2348 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2352 if ((flags & Modifiers.SEALED) != 0) {
2353 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2357 if ((flags & Modifiers.VIRTUAL) != 0){
2358 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2362 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2363 Report.SymbolRelatedToPreviousError (this);
2364 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2365 mc.GetSignatureForError (), GetSignatureForError ());
2370 if ((flags & Modifiers.PRIVATE) != 0){
2371 if ((flags & vao) != 0){
2372 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2377 if ((flags & Modifiers.SEALED) != 0){
2378 if ((flags & Modifiers.OVERRIDE) == 0){
2379 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2387 public Constructor DefaultStaticConstructor {
2388 get { return default_static_constructor; }
2391 protected override bool VerifyClsCompliance ()
2393 if (!base.VerifyClsCompliance ())
2398 Type base_type = TypeBuilder.BaseType;
2399 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2400 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2407 /// Checks whether container name is CLS Compliant
2409 void VerifyClsName ()
2411 Hashtable base_members = base_cache == null ?
2413 base_cache.GetPublicMembers ();
2414 Hashtable this_members = new Hashtable ();
2416 foreach (DictionaryEntry entry in defined_names) {
2417 MemberCore mc = (MemberCore)entry.Value;
2418 if (!mc.IsClsComplianceRequired ())
2421 string name = (string) entry.Key;
2422 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2424 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2425 object found = base_members [lcase];
2426 if (found == null) {
2427 found = this_members [lcase];
2428 if (found == null) {
2429 this_members.Add (lcase, mc);
2434 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2437 if (found is MemberInfo) {
2438 if (basename == ((MemberInfo) found).Name)
2440 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2442 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2445 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2451 /// Performs checks for an explicit interface implementation. First it
2452 /// checks whether the `interface_type' is a base inteface implementation.
2453 /// Then it checks whether `name' exists in the interface type.
2455 public bool VerifyImplements (InterfaceMemberBase mb)
2457 if (ifaces != null) {
2458 foreach (Type t in ifaces){
2459 if (TypeManager.IsEqual (t, mb.InterfaceType))
2464 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2465 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2466 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2470 public override Type LookupAnyGeneric (string typeName)
2472 if (types != null) {
2473 foreach (TypeContainer tc in types) {
2477 int pos = tc.Basename.LastIndexOf ('`');
2478 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2479 return tc.TypeBuilder;
2483 return base.LookupAnyGeneric (typeName);
2486 public void Mark_HasEquals ()
2488 cached_method |= CachedMethods.Equals;
2491 public void Mark_HasGetHashCode ()
2493 cached_method |= CachedMethods.GetHashCode;
2497 /// Method container contains Equals method
2499 public bool HasEquals {
2501 return (cached_method & CachedMethods.Equals) != 0;
2506 /// Method container contains GetHashCode method
2508 public bool HasGetHashCode {
2510 return (cached_method & CachedMethods.GetHashCode) != 0;
2514 public bool HasStaticFieldInitializer {
2516 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2520 cached_method |= CachedMethods.HasStaticFieldInitializer;
2522 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2530 string IMemberContainer.Name {
2536 Type IMemberContainer.Type {
2542 bool IMemberContainer.IsInterface {
2544 return Kind == Kind.Interface;
2548 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2550 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2552 if (GenericType != null)
2553 return TypeManager.FindMembers (GenericType, mt, new_bf,
2556 return FindMembers (mt, new_bf, null, null);
2560 // Generates xml doc comments (if any), and if required,
2561 // handle warning report.
2563 internal override void GenerateDocComment (DeclSpace ds)
2565 DocUtil.GenerateTypeDocComment (this, ds);
2568 public override string DocCommentHeader {
2569 get { return "T:"; }
2572 public MemberCache BaseCache {
2574 if (base_cache != null)
2576 if (TypeBuilder.BaseType != null)
2577 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2578 if (TypeBuilder.IsInterface)
2579 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2585 public abstract class ClassOrStruct : TypeContainer {
2586 ListDictionary declarative_security;
2588 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2589 MemberName name, Attributes attrs, Kind kind)
2590 : base (ns, parent, name, attrs, kind)
2594 protected override bool AddToContainer (MemberCore symbol, string name)
2596 if (name == MemberName.Name) {
2597 if (symbol is TypeParameter) {
2598 Report.Error (694, symbol.Location,
2599 "Type parameter `{0}' has same name as " +
2600 "containing type, or method", name);
2604 Report.SymbolRelatedToPreviousError (this);
2605 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2606 symbol.GetSignatureForError ());
2610 return base.AddToContainer (symbol, name);
2613 public override void VerifyMembers ()
2615 base.VerifyMembers ();
2617 if ((events != null) && Report.WarningLevel >= 3) {
2618 foreach (Event e in events){
2619 // Note: The event can be assigned from same class only, so we can report
2620 // this warning for all accessibility modes
2621 if ((e.caching_flags & Flags.IsUsed) == 0)
2622 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2627 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2629 if (a.IsValidSecurityAttribute ()) {
2630 if (declarative_security == null)
2631 declarative_security = new ListDictionary ();
2633 a.ExtractSecurityPermissionSet (declarative_security);
2637 if (a.Type == TypeManager.struct_layout_attribute_type) {
2638 PartialContainer.HasStructLayout = true;
2640 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2641 PartialContainer.HasExplicitLayout = true;
2644 base.ApplyAttributeBuilder (a, cb);
2648 /// Defines the default constructors
2650 protected void DefineDefaultConstructor (bool is_static)
2652 // The default instance constructor is public
2653 // If the class is abstract, the default constructor is protected
2654 // The default static constructor is private
2658 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2660 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2663 Constructor c = new Constructor (this, MemberName.Name, mods,
2664 Parameters.EmptyReadOnlyParameters,
2665 new GeneratedBaseInitializer (Location),
2669 c.Block = new ToplevelBlock (null, Location);
2672 public override bool Define ()
2674 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2675 DefineDefaultConstructor (true);
2677 if (default_static_constructor != null)
2678 default_static_constructor.Define ();
2680 return base.Define ();
2683 public override void Emit ()
2687 if (declarative_security != null) {
2688 foreach (DictionaryEntry de in declarative_security) {
2689 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2694 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2696 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2699 protected override TypeAttributes TypeAttr {
2701 if (default_static_constructor == null)
2702 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2704 return base.TypeAttr;
2710 // TODO: should be sealed
2711 public class Class : ClassOrStruct {
2712 const int AllowedModifiers =
2715 Modifiers.PROTECTED |
2716 Modifiers.INTERNAL |
2718 Modifiers.ABSTRACT |
2723 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2725 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2727 : base (ns, parent, name, attrs, Kind.Class)
2729 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2730 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2732 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2733 Report.FeatureIsNotAvailable (Location, "static classes");
2737 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2739 if (part.Name == "System.Object")
2740 Report.Error (537, part.Location,
2741 "The class System.Object cannot have a base class or implement an interface.");
2742 base.AddBasesForPart (part, bases);
2745 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2747 if (a.Type == TypeManager.attribute_usage_type) {
2748 if (!TypeManager.IsAttributeType (BaseType) &&
2749 TypeBuilder.FullName != "System.Attribute") {
2750 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2754 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2755 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2759 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2760 !attributes.Contains (TypeManager.guid_attr_type)) {
2761 a.Error_MissingGuidAttribute ();
2765 if (a.Type == TypeManager.extension_attribute_type) {
2766 a.Error_MisusedExtensionAttribute ();
2770 if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2773 base.ApplyAttributeBuilder (a, cb);
2776 public override AttributeTargets AttributeTargets {
2778 return AttributeTargets.Class;
2782 protected override void DefineContainerMembers (MemberCoreArrayList list)
2788 base.DefineContainerMembers (list);
2792 foreach (MemberCore m in list) {
2793 if (m is Operator) {
2794 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2798 if (m is Destructor) {
2799 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2803 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2804 m.CheckProtectedModifier ();
2809 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2813 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2816 if (m is Constructor) {
2817 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2821 Method method = m as Method;
2822 if (method != null && method.Parameters.HasExtensionMethodType) {
2823 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2827 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2830 base.DefineContainerMembers (list);
2833 public override TypeBuilder DefineType ()
2835 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2836 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2840 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2841 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2845 return base.DefineType ();
2848 protected override bool DoDefineMembers ()
2850 if (InstanceConstructors == null && !IsStatic)
2851 DefineDefaultConstructor (false);
2853 return base.DoDefineMembers ();
2856 public override void Emit ()
2861 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2862 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2866 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2868 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2870 if (base_class == null) {
2871 if (RootContext.StdLib)
2872 base_class = TypeManager.system_object_expr;
2873 else if (Name != "System.Object")
2874 base_class = TypeManager.system_object_expr;
2876 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2878 689, base_class.Location,
2879 "Cannot derive from `{0}' because it is a type parameter",
2880 base_class.GetSignatureForError ());
2884 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2885 Report.Error (698, base_class.Location,
2886 "A generic type cannot derive from `{0}' because it is an attribute class",
2887 base_class.GetSignatureForError ());
2890 if (base_class.IsSealed){
2891 Report.SymbolRelatedToPreviousError (base_class.Type);
2892 if (base_class.Type.IsAbstract) {
2893 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2894 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2896 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2897 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2902 if (!base_class.CanInheritFrom ()){
2903 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2904 GetSignatureForError (), base_class.GetSignatureForError ());
2908 if (!base_class.AsAccessible (this)) {
2909 Report.SymbolRelatedToPreviousError (base_class.Type);
2910 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2911 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2915 if (PartialContainer.IsStaticClass) {
2916 if (base_class.Type != TypeManager.object_type) {
2917 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2918 GetSignatureForError (), base_class.GetSignatureForError ());
2922 if (ifaces != null) {
2923 foreach (TypeExpr t in ifaces)
2924 Report.SymbolRelatedToPreviousError (t.Type);
2925 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2932 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2933 /// Valid only for attribute classes.
2934 public bool IsExcluded ()
2936 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2937 return (caching_flags & Flags.Excluded) != 0;
2939 caching_flags &= ~Flags.Excluded_Undetected;
2941 if (OptAttributes == null)
2944 if (TypeManager.conditional_attribute_type == null)
2947 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2952 foreach (Attribute a in attrs) {
2953 string condition = a.GetConditionalAttributeValue ();
2954 if (Location.CompilationUnit.IsConditionalDefined (condition))
2958 caching_flags |= Flags.Excluded;
2964 return (ModFlags & Modifiers.STATIC) != 0;
2969 // FIXME: How do we deal with the user specifying a different
2972 protected override TypeAttributes TypeAttr {
2974 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2976 ta |= StaticClassAttribute;
2982 public sealed class Struct : ClassOrStruct {
2984 // Modifiers allowed in a struct declaration
2986 const int AllowedModifiers =
2989 Modifiers.PROTECTED |
2990 Modifiers.INTERNAL |
2994 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2995 int mod, Attributes attrs)
2996 : base (ns, parent, name, attrs, Kind.Struct)
3000 if (parent.Parent == null)
3001 accmods = Modifiers.INTERNAL;
3003 accmods = Modifiers.PRIVATE;
3005 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3007 this.ModFlags |= Modifiers.SEALED;
3010 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3012 base.ApplyAttributeBuilder (a, cb);
3015 // When struct constains fixed fixed and struct layout has explicitly
3016 // set CharSet, its value has to be propagated to compiler generated
3017 // fixed field types
3019 if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
3020 for (int i = 0; i < Fields.Count; ++i) {
3021 FixedField ff = Fields [i] as FixedField;
3023 ff.SetCharSet (TypeBuilder.Attributes);
3028 public override AttributeTargets AttributeTargets {
3030 return AttributeTargets.Struct;
3034 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
3036 TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
3038 // If we are compiling our runtime,
3039 // and we are defining ValueType, then our
3040 // base is `System.Object'.
3042 if (base_class == null) {
3043 if (!RootContext.StdLib && Name == "System.ValueType")
3044 base_class = TypeManager.system_object_expr;
3046 base_class = TypeManager.system_valuetype_expr;
3053 // FIXME: Allow the user to specify a different set of attributes
3054 // in some cases (Sealed for example is mandatory for a class,
3055 // but what SequentialLayout can be changed
3057 protected override TypeAttributes TypeAttr {
3059 const TypeAttributes DefaultTypeAttributes =
3060 TypeAttributes.SequentialLayout |
3061 TypeAttributes.Sealed |
3062 TypeAttributes.BeforeFieldInit;
3064 return base.TypeAttr | DefaultTypeAttributes;
3068 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3070 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3071 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3072 field.GetSignatureForError ());
3075 base.RegisterFieldForInitialization (field, expression);
3083 public sealed class Interface : TypeContainer, IMemberContainer {
3086 /// Modifiers allowed in a class declaration
3088 public const int AllowedModifiers =
3091 Modifiers.PROTECTED |
3092 Modifiers.INTERNAL |
3096 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3098 : base (ns, parent, name, attrs, Kind.Interface)
3102 if (parent.Parent == null)
3103 accmods = Modifiers.INTERNAL;
3105 accmods = Modifiers.PRIVATE;
3107 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3110 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3112 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3113 !attributes.Contains (TypeManager.guid_attr_type)) {
3114 a.Error_MissingGuidAttribute ();
3117 base.ApplyAttributeBuilder (a, cb);
3121 public override AttributeTargets AttributeTargets {
3123 return AttributeTargets.Interface;
3127 const TypeAttributes DefaultTypeAttributes =
3128 TypeAttributes.AutoLayout |
3129 TypeAttributes.Abstract |
3130 TypeAttributes.Interface;
3132 protected override TypeAttributes TypeAttr {
3134 return base.TypeAttr | DefaultTypeAttributes;
3138 protected override bool VerifyClsCompliance ()
3140 if (!base.VerifyClsCompliance ())
3143 if (ifaces != null) {
3144 foreach (Type t in ifaces) {
3145 if (AttributeTester.IsClsCompliant (t))
3148 Report.SymbolRelatedToPreviousError (t);
3149 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3150 GetSignatureForError (), TypeManager.CSharpName (t));
3158 // It is used as a base class for all property based members
3159 // This includes properties, indexers, and events
3160 public abstract class PropertyBasedMember : InterfaceMemberBase
3162 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3163 FullNamedExpression type, int mod, int allowed_mod,
3164 MemberName name, Attributes attrs)
3165 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3169 protected override bool VerifyClsCompliance ()
3171 if (!base.VerifyClsCompliance ())
3174 if (!AttributeTester.IsClsCompliant (MemberType)) {
3175 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3176 GetSignatureForError ());
3184 public abstract class MethodCore : InterfaceMemberBase
3186 public readonly Parameters Parameters;
3187 protected ToplevelBlock block;
3189 public MethodCore (DeclSpace parent, GenericMethod generic,
3190 FullNamedExpression type, int mod, int allowed_mod,
3191 MemberName name, Attributes attrs, Parameters parameters)
3192 : base (parent, generic, type, mod, allowed_mod, name, attrs)
3194 Parameters = parameters;
3198 // Returns the System.Type array for the parameters of this method
3200 public Type [] ParameterTypes {
3202 return Parameters.Types;
3206 public Parameters ParameterInfo
3213 public ToplevelBlock Block {
3223 protected override bool CheckBase ()
3225 // Check whether arguments were correct.
3226 if (!DefineParameters (Parameters))
3229 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3230 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3231 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3234 // TODO: Find a better way how to check reserved accessors collision
3235 Method m = this as Method;
3237 if (!m.CheckForDuplications ())
3242 if (!base.CheckBase ())
3249 // Returns a string that represents the signature for this
3250 // member which should be used in XML documentation.
3252 public override string GetDocCommentName (DeclSpace ds)
3254 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3258 // Raised (and passed an XmlElement that contains the comment)
3259 // when GenerateDocComment is writing documentation expectedly.
3261 // FIXME: with a few effort, it could be done with XmlReader,
3262 // that means removal of DOM use.
3264 internal override void OnGenerateDocComment (XmlElement el)
3266 DocUtil.OnMethodGenerateDocComment (this, el);
3270 // Represents header string for documentation comment.
3272 public override string DocCommentHeader
3274 get { return "M:"; }
3277 public override bool EnableOverloadChecks (MemberCore overload)
3279 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3280 caching_flags |= Flags.MethodOverloadsExist;
3287 protected override bool VerifyClsCompliance ()
3289 if (!base.VerifyClsCompliance ())
3292 if (Parameters.HasArglist) {
3293 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3296 if (!AttributeTester.IsClsCompliant (MemberType)) {
3297 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3298 GetSignatureForError ());
3301 Parameters.VerifyClsCompliance ();
3307 public abstract class InterfaceMemberBase : MemberBase {
3309 // Whether this is an interface member.
3311 public bool IsInterface;
3314 // If true, this is an explicit interface implementation
3316 public bool IsExplicitImpl;
3318 protected bool is_external_implementation;
3321 // The interface type we are explicitly implementing
3323 public Type InterfaceType;
3326 // The method we're overriding if this is an override method.
3328 protected MethodInfo base_method;
3330 readonly int explicit_mod_flags;
3331 public MethodAttributes flags;
3333 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3334 FullNamedExpression type, int mod, int allowed_mod,
3335 MemberName name, Attributes attrs)
3336 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3339 IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3340 IsExplicitImpl = (MemberName.Left != null);
3341 explicit_mod_flags = mod;
3344 protected override bool CheckBase ()
3346 if (!base.CheckBase ())
3352 // Is null for System.Object while compiling corlib and base interfaces
3353 if (Parent.PartialContainer.BaseCache == null) {
3354 if ((ModFlags & Modifiers.NEW) != 0) {
3355 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3360 Type base_ret_type = null;
3361 base_method = FindOutBaseMethod (ref base_ret_type);
3363 // method is override
3364 if (base_method != null) {
3365 if (!CheckMethodAgainstBase (base_ret_type))
3368 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3369 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3371 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3372 Report.SymbolRelatedToPreviousError (base_method);
3373 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3374 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3377 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3378 Report.SymbolRelatedToPreviousError (base_method);
3379 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3380 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3387 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3388 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3389 if (conflict_symbol != null) {
3390 Report.SymbolRelatedToPreviousError (conflict_symbol);
3392 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3393 else if (this is PropertyBase)
3394 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3396 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3398 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3399 GetSignatureForError (), SimpleName.GetMemberType (this));
3404 if (conflict_symbol == null) {
3405 if ((ModFlags & Modifiers.NEW) != 0) {
3406 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3411 if ((ModFlags & Modifiers.NEW) == 0) {
3412 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3415 Report.SymbolRelatedToPreviousError (conflict_symbol);
3416 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3417 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3424 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3425 // that have been defined.
3427 // `name' is the user visible name for reporting errors (this is used to
3428 // provide the right name regarding method names and properties)
3430 bool CheckMethodAgainstBase (Type base_method_type)
3434 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3435 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3436 Report.Error (506, Location,
3437 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3438 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3442 // Now we check that the overriden method is not final
3444 if (base_method.IsFinal) {
3445 Report.SymbolRelatedToPreviousError (base_method);
3446 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3447 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3451 // Check that the permissions are not being changed
3453 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3454 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3456 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3457 Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3461 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3462 Report.SymbolRelatedToPreviousError (base_method);
3463 if (this is PropertyBasedMember) {
3464 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3465 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3468 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3469 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3475 if ((ModFlags & Modifiers.NEW) == 0) {
3476 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3477 ModFlags |= Modifiers.NEW;
3478 Report.SymbolRelatedToPreviousError (base_method);
3479 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3480 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",
3481 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3483 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3484 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3488 if (base_method.IsAbstract && !IsInterface) {
3489 Report.SymbolRelatedToPreviousError (base_method);
3490 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3491 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3499 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3501 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3503 // when overriding protected internal, the method can be declared
3504 // protected internal only within the same assembly or assembly
3505 // which has InternalsVisibleTo
3507 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3508 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3509 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3511 // if it's not "protected internal", it must be "protected"
3515 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3517 // protected within the same assembly - an error
3520 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3521 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3523 // protected ok, but other attributes differ - report an error
3529 return (thisp == base_classp);
3533 protected bool DefineParameters (Parameters parameters)
3535 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3537 if (!parameters.Resolve (rc))
3541 for (int i = 0; i < parameters.Count; ++i) {
3542 Parameter p = parameters [i];
3543 if (p.CheckAccessibility (this))
3546 Type t = parameters.Types [i];
3547 Report.SymbolRelatedToPreviousError (t);
3548 if (this is Indexer)
3549 Report.Error (55, Location,
3550 "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3551 TypeManager.CSharpName (t), GetSignatureForError ());
3552 else if (this is Operator)
3553 Report.Error (57, Location,
3554 "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3555 TypeManager.CSharpName (t), GetSignatureForError ());
3557 Report.Error (51, Location,
3558 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3559 TypeManager.CSharpName (t), GetSignatureForError ());
3565 protected override bool DoDefine()
3567 if (!base.DoDefine ())
3570 if (IsExplicitImpl) {
3571 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3575 InterfaceType = texpr.Type;
3577 if (!InterfaceType.IsInterface) {
3578 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3582 if (!Parent.PartialContainer.VerifyImplements (this))
3589 protected bool DoDefineBase ()
3592 throw new InternalErrorException ();
3595 ModFlags = Modifiers.PUBLIC |
3596 Modifiers.ABSTRACT |
3597 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3599 flags = MethodAttributes.Public |
3600 MethodAttributes.Abstract |
3601 MethodAttributes.HideBySig |
3602 MethodAttributes.NewSlot |
3603 MethodAttributes.Virtual;
3605 if (!Parent.PartialContainer.MethodModifiersValid (this))
3608 flags = Modifiers.MethodAttr (ModFlags);
3611 if (IsExplicitImpl) {
3612 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3613 if (iface_texpr == null)
3616 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3617 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3618 GetSignatureForError ());
3622 InterfaceType = iface_texpr.Type;
3624 if (!InterfaceType.IsInterface) {
3625 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3629 if (!Parent.PartialContainer.VerifyImplements (this))
3632 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3638 public override void Emit()
3640 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3641 // We are more strict than Microsoft and report CS0626 as error
3642 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3643 Report.Error (626, Location,
3644 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3645 GetSignatureForError ());
3651 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3653 Report.SymbolRelatedToPreviousError (base_method);
3654 string base_name = TypeManager.GetFullNameSignature (base_method);
3655 string this_name = GetSignatureForError ();
3656 if (suffix != null) {
3657 base_name += suffix;
3658 this_name += suffix;
3661 Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3662 this_name, Modifiers.GetDescription (ma), base_name);
3665 protected static string Error722 {
3667 return "`{0}': static types cannot be used as return types";
3672 /// Gets base method and its return type
3674 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3677 // The "short" name of this property / indexer / event. This is the
3678 // name without the explicit interface.
3680 public string ShortName
3682 get { return MemberName.Name; }
3683 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3686 public string GetFullName (MemberName name)
3688 if (!IsExplicitImpl)
3691 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3694 protected override bool VerifyClsCompliance ()
3696 if (!base.VerifyClsCompliance ()) {
3697 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3698 Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3701 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3702 Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3707 if (GenericMethod != null)
3708 GenericMethod.VerifyClsCompliance ();
3713 public override bool IsUsed
3715 get { return IsExplicitImpl || base.IsUsed; }
3720 public abstract class MethodOrOperator : MethodCore, IMethodData
3722 public MethodBuilder MethodBuilder;
3723 ReturnParameter return_attributes;
3724 ListDictionary declarative_security;
3725 protected MethodData MethodData;
3727 static string[] attribute_targets = new string [] { "method", "return" };
3729 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3730 int allowed_mod, MemberName name,
3731 Attributes attrs, Parameters parameters)
3732 : base (parent, generic, type, mod, allowed_mod, name,
3737 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3739 if (a.Target == AttributeTargets.ReturnValue) {
3740 if (return_attributes == null)
3741 return_attributes = new ReturnParameter (MethodBuilder, Location);
3743 return_attributes.ApplyAttributeBuilder (a, cb);
3747 if (a.IsInternalMethodImplAttribute) {
3748 is_external_implementation = true;
3751 if (a.Type == TypeManager.dllimport_type) {
3752 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3753 if ((ModFlags & extern_static) != extern_static) {
3754 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3756 is_external_implementation = true;
3759 if (a.IsValidSecurityAttribute ()) {
3760 if (declarative_security == null)
3761 declarative_security = new ListDictionary ();
3762 a.ExtractSecurityPermissionSet (declarative_security);
3766 if (MethodBuilder != null)
3767 MethodBuilder.SetCustomAttribute (cb);
3770 public override AttributeTargets AttributeTargets {
3772 return AttributeTargets.Method;
3776 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3778 return new EmitContext (
3779 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3782 protected bool DefineGenericMethod ()
3784 if (!DoDefineBase ())
3788 if (GenericMethod != null) {
3789 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3790 if (!GenericMethod.Define (MethodBuilder))
3798 public bool ResolveMembers ()
3800 if (!DefineGenericMethod ())
3806 public override bool Define ()
3811 if (!CheckAbstractAndExtern (block != null))
3814 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3815 for (int i = 0; i < Parameters.Count; ++i ) {
3816 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
3817 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3818 GetSignatureForError ());
3827 if (block != null && block.IsIterator && !(Parent is IteratorStorey))
3828 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3830 if (IsPartialDefinition) {
3831 caching_flags &= ~Flags.Excluded_Undetected;
3832 caching_flags |= Flags.Excluded;
3833 // Add to member cache only when a partial method implementation is not there
3834 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3835 MethodBase mb = new PartialMethodDefinitionInfo (this);
3836 Parent.MemberCache.AddMember (mb, this);
3837 TypeManager.AddMethod (mb, this);
3843 MethodData = new MethodData (
3844 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3846 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3849 MethodBuilder = MethodData.MethodBuilder;
3852 if (MethodBuilder.IsGenericMethod)
3853 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3856 Parent.MemberCache.AddMember (MethodBuilder, this);
3858 if (!TypeManager.IsGenericParameter (MemberType)) {
3859 if (MemberType.IsAbstract && MemberType.IsSealed) {
3860 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3868 public override void Emit ()
3871 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3872 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3873 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3874 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3876 if (OptAttributes != null)
3877 OptAttributes.Emit ();
3879 if (declarative_security != null) {
3880 foreach (DictionaryEntry de in declarative_security) {
3881 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3888 protected void Error_ConditionalAttributeIsNotValid ()
3890 Report.Error (577, Location,
3891 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3892 GetSignatureForError ());
3895 public bool IsPartialDefinition {
3897 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3901 public bool IsPartialImplementation {
3903 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3907 public override string[] ValidAttributeTargets {
3909 return attribute_targets;
3913 #region IMethodData Members
3915 public CallingConventions CallingConventions {
3917 CallingConventions cc = Parameters.CallingConvention;
3919 if ((ModFlags & Modifiers.STATIC) == 0)
3920 cc |= CallingConventions.HasThis;
3922 // FIXME: How is `ExplicitThis' used in C#?
3928 public Type ReturnType {
3934 public MemberName MethodName {
3940 protected override bool CheckBase ()
3942 if (!base.CheckBase ())
3945 // TODO: Destructor should derive from MethodCore
3946 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3947 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3948 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3956 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3958 public bool IsExcluded () {
3959 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3960 return (caching_flags & Flags.Excluded) != 0;
3962 caching_flags &= ~Flags.Excluded_Undetected;
3964 if (base_method == null) {
3965 if (OptAttributes == null)
3968 if (TypeManager.conditional_attribute_type == null)
3971 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3976 foreach (Attribute a in attrs) {
3977 string condition = a.GetConditionalAttributeValue ();
3978 if (condition == null)
3981 if (Location.CompilationUnit.IsConditionalDefined (condition))
3985 caching_flags |= Flags.Excluded;
3989 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3991 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3992 caching_flags |= Flags.Excluded;
3998 if (md.IsExcluded ()) {
3999 caching_flags |= Flags.Excluded;
4005 GenericMethod IMethodData.GenericMethod {
4007 return GenericMethod;
4011 public virtual void EmitExtraSymbolInfo (SourceMethod source)
4018 public class SourceMethod : IMethodDef
4021 SourceMethodBuilder builder;
4023 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
4025 this.method = method;
4027 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
4030 public string Name {
4031 get { return method.Name; }
4036 if (method is MethodBuilder)
4037 return ((MethodBuilder) method).GetToken ().Token;
4038 else if (method is ConstructorBuilder)
4039 return ((ConstructorBuilder) method).GetToken ().Token;
4041 throw new NotSupportedException ();
4045 public void CloseMethod ()
4047 SymbolWriter.CloseMethod ();
4050 public void SetRealMethodName (string name)
4052 if (builder != null)
4053 builder.SetRealMethodName (name);
4056 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4058 if (!SymbolWriter.HasSymbolWriter)
4063 Location start_loc = block.StartLocation;
4064 if (start_loc.IsNull)
4067 ICompileUnit compile_unit = start_loc.CompilationUnit;
4068 if (compile_unit == null)
4071 return new SourceMethod (parent, method, compile_unit);
4075 public class Method : MethodOrOperator {
4078 /// Modifiers allowed in a class declaration
4080 const int AllowedModifiers =
4083 Modifiers.PROTECTED |
4084 Modifiers.INTERNAL |
4089 Modifiers.OVERRIDE |
4090 Modifiers.ABSTRACT |
4094 const int AllowedInterfaceModifiers =
4095 Modifiers.NEW | Modifiers.UNSAFE;
4097 public Method (DeclSpace parent, GenericMethod generic,
4098 FullNamedExpression return_type, int mod,
4099 MemberName name, Parameters parameters, Attributes attrs)
4100 : base (parent, generic, return_type, mod,
4101 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4102 name, attrs, parameters)
4106 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4107 MemberName name, Parameters parameters, Attributes attrs)
4108 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4112 public override string GetSignatureForError()
4114 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4117 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4119 Report.Error (17, location,
4120 "Program `{0}' has more than one entry point defined: `{1}'",
4121 CodeGen.FileName, TypeManager.CSharpSignature(b));
4124 bool IsEntryPoint ()
4126 if (ReturnType != TypeManager.void_type &&
4127 ReturnType != TypeManager.int32_type)
4130 if (Parameters.Count == 0)
4133 if (Parameters.Count > 1)
4136 Type t = Parameters.Types [0];
4137 return t.IsArray && t.GetArrayRank () == 1 &&
4138 TypeManager.GetElementType (t) == TypeManager.string_type &&
4139 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4142 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4144 if (a.Type == TypeManager.conditional_attribute_type) {
4145 if (IsExplicitImpl) {
4146 Error_ConditionalAttributeIsNotValid ();
4150 if (ReturnType != TypeManager.void_type) {
4151 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4155 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4156 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4161 Report.Error (582, Location, "Conditional not valid on interface members");
4165 if (MethodData.implementing != null) {
4166 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4167 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4168 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4172 for (int i = 0; i < Parameters.Count; ++i) {
4173 if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4174 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4180 if (a.Type == TypeManager.extension_attribute_type) {
4181 a.Error_MisusedExtensionAttribute ();
4185 base.ApplyAttributeBuilder (a, cb);
4188 public bool CheckForDuplications ()
4190 ArrayList ar = Parent.PartialContainer.Properties;
4192 for (int i = 0; i < ar.Count; ++i) {
4193 PropertyBase pb = (PropertyBase) ar [i];
4194 if (pb.AreAccessorsDuplicateImplementation (this))
4199 ar = Parent.PartialContainer.Indexers;
4201 for (int i = 0; i < ar.Count; ++i) {
4202 PropertyBase pb = (PropertyBase) ar [i];
4203 if (pb.AreAccessorsDuplicateImplementation (this))
4214 public override bool Define ()
4216 if (!base.Define ())
4219 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4220 Error1599 (Location, ReturnType);
4224 if (ReturnType == TypeManager.void_type && Parameters.Count == 0 &&
4225 Name == "Finalize" && !(this is Destructor)) {
4226 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4229 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4230 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4231 Parent.PartialContainer.Mark_HasEquals ();
4232 else if (Parameters.IsEmpty && Name == "GetHashCode")
4233 Parent.PartialContainer.Mark_HasGetHashCode ();
4236 if ((ModFlags & Modifiers.STATIC) == 0)
4239 if (Parameters.HasExtensionMethodType) {
4240 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4241 if (!Parent.IsTopLevel)
4242 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4243 GetSignatureForError ());
4245 if (TypeManager.extension_attribute_type == null) {
4246 Report.Error (1110, Location,
4247 "`{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",
4248 GetSignatureForError ());
4249 } else if (TypeManager.extension_attribute_attr == null) {
4250 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4251 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4254 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4257 ModFlags |= Modifiers.METHOD_EXTENSION;
4258 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4259 CodeGen.Assembly.HasExtensionMethods = true;
4261 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4262 GetSignatureForError ());
4267 // This is used to track the Entry Point,
4269 if (RootContext.NeedsEntryPoint &&
4271 (RootContext.MainClass == null ||
4272 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4273 if (IsEntryPoint ()) {
4275 if (RootContext.EntryPoint == null) {
4276 if (Parent.IsGeneric || MemberName.IsGeneric) {
4277 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4278 GetSignatureForError ());
4280 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4281 md.SetMemberIsUsed ();
4283 RootContext.EntryPoint = MethodBuilder;
4284 RootContext.EntryPointLocation = Location;
4287 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4288 Error_DuplicateEntryPoint (MethodBuilder, Location);
4291 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4292 GetSignatureForError ());
4302 public override void Emit ()
4305 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4306 if (IsPartialDefinition) {
4308 // Do attribute checks only when partial implementation does not exist
4310 if (MethodBuilder == null)
4316 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4317 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4318 GetSignatureForError ());
4320 MethodData.Emit (Parent);
4324 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4325 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4331 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4332 Location, MethodBuilder);
4337 public override bool EnableOverloadChecks (MemberCore overload)
4339 // TODO: It can be deleted when members will be defined in correct order
4340 if (overload is Operator)
4341 return overload.EnableOverloadChecks (this);
4343 if (overload is Indexer)
4346 return base.EnableOverloadChecks (overload);
4349 public static void Error1599 (Location loc, Type t)
4351 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4354 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4356 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4357 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4362 if (mi.IsSpecialName)
4365 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4369 public void SetPartialDefinition (Method methodDefinition)
4371 caching_flags |= Flags.PartialDefinitionExists;
4372 methodDefinition.MethodBuilder = MethodBuilder;
4373 if (methodDefinition.attributes == null)
4376 if (attributes == null) {
4377 attributes = methodDefinition.attributes;
4379 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4383 protected override bool VerifyClsCompliance ()
4385 if (!base.VerifyClsCompliance ())
4388 if (ParameterInfo.Count > 0) {
4389 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4391 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4398 public abstract class ConstructorInitializer : ExpressionStatement
4400 ArrayList argument_list;
4401 MethodGroupExpr base_constructor_group;
4403 public ConstructorInitializer (ArrayList argument_list, Location loc)
4405 this.argument_list = argument_list;
4409 public ArrayList Arguments {
4411 return argument_list;
4415 public override Expression CreateExpressionTree (EmitContext ec)
4417 throw new NotSupportedException ("ET");
4420 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4422 if (argument_list != null){
4423 foreach (Argument a in argument_list){
4424 if (!a.Resolve (ec, loc))
4429 if (this is ConstructorBaseInitializer) {
4430 if (ec.ContainerType.BaseType == null)
4433 type = ec.ContainerType.BaseType;
4434 if (ec.ContainerType.IsValueType) {
4435 Report.Error (522, loc,
4436 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4441 // It is legal to have "this" initializers that take no arguments
4442 // in structs, they are just no-ops.
4444 // struct D { public D (int a) : this () {}
4446 if (ec.ContainerType.IsValueType && argument_list == null)
4449 type = ec.ContainerType;
4452 base_constructor_group = MemberLookupFinal (
4453 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4454 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4455 loc) as MethodGroupExpr;
4457 if (base_constructor_group == null)
4460 base_constructor_group = base_constructor_group.OverloadResolve (
4461 ec, ref argument_list, false, loc);
4463 if (base_constructor_group == null)
4466 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4468 if (base_ctor == caller_builder){
4469 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4475 public override Expression DoResolve (EmitContext ec)
4477 throw new NotSupportedException ();
4480 public override void Emit (EmitContext ec)
4482 // It can be null for static initializers
4483 if (base_constructor_group == null)
4488 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4490 base_constructor_group.EmitCall (ec, argument_list);
4493 public override void EmitStatement (EmitContext ec)
4499 public class ConstructorBaseInitializer : ConstructorInitializer {
4500 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4501 base (argument_list, l)
4506 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4507 public GeneratedBaseInitializer (Location loc):
4513 public class ConstructorThisInitializer : ConstructorInitializer {
4514 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4515 base (argument_list, l)
4520 public class Constructor : MethodCore, IMethodData {
4521 public ConstructorBuilder ConstructorBuilder;
4522 public ConstructorInitializer Initializer;
4523 ListDictionary declarative_security;
4524 bool has_compliant_args;
4527 // Modifiers allowed for a constructor.
4529 public const int AllowedModifiers =
4531 Modifiers.PROTECTED |
4532 Modifiers.INTERNAL |
4538 static readonly string[] attribute_targets = new string [] { "method" };
4541 // The spec claims that static is not permitted, but
4542 // my very own code has static constructors.
4544 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4545 ConstructorInitializer init, Location loc)
4546 : base (parent, null, null, mod, AllowedModifiers,
4547 new MemberName (name, loc), null, args)
4552 public bool HasCompliantArgs {
4553 get { return has_compliant_args; }
4556 public override AttributeTargets AttributeTargets {
4557 get { return AttributeTargets.Constructor; }
4561 // Returns true if this is a default constructor
4563 public bool IsDefault ()
4565 if ((ModFlags & Modifiers.STATIC) != 0)
4566 return Parameters.IsEmpty;
4568 return Parameters.IsEmpty &&
4569 (Initializer is ConstructorBaseInitializer) &&
4570 (Initializer.Arguments == null);
4573 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4575 if (a.IsValidSecurityAttribute ()) {
4576 if (declarative_security == null) {
4577 declarative_security = new ListDictionary ();
4579 a.ExtractSecurityPermissionSet (declarative_security);
4583 if (a.IsInternalMethodImplAttribute) {
4584 is_external_implementation = true;
4587 ConstructorBuilder.SetCustomAttribute (cb);
4590 protected override bool CheckBase ()
4592 if ((ModFlags & Modifiers.STATIC) != 0) {
4593 if (!Parameters.IsEmpty) {
4594 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4595 GetSignatureForError ());
4599 // the rest can be ignored
4603 // Check whether arguments were correct.
4604 if (!DefineParameters (Parameters))
4607 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4608 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4611 if (Parent.PartialContainer.Kind == Kind.Struct) {
4612 if (Parameters.Count == 0) {
4613 Report.Error (568, Location,
4614 "Structs cannot contain explicit parameterless constructors");
4619 CheckProtectedModifier ();
4625 // Creates the ConstructorBuilder
4627 public override bool Define ()
4629 if (ConstructorBuilder != null)
4632 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4633 MethodAttributes.SpecialName);
4635 if ((ModFlags & Modifiers.STATIC) != 0) {
4636 ca |= MethodAttributes.Static | MethodAttributes.Private;
4638 ca |= MethodAttributes.HideBySig;
4640 if ((ModFlags & Modifiers.PUBLIC) != 0)
4641 ca |= MethodAttributes.Public;
4642 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4643 if ((ModFlags & Modifiers.INTERNAL) != 0)
4644 ca |= MethodAttributes.FamORAssem;
4646 ca |= MethodAttributes.Family;
4647 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4648 ca |= MethodAttributes.Assembly;
4650 ca |= MethodAttributes.Private;
4653 if (!CheckAbstractAndExtern (block != null))
4656 // Check if arguments were correct.
4660 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4661 ca, CallingConventions,
4662 Parameters.GetEmitTypes ());
4664 if (Parent.PartialContainer.IsComImport) {
4665 if (!IsDefault ()) {
4666 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4667 Parent.GetSignatureForError ());
4670 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4673 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4674 TypeManager.AddMethod (ConstructorBuilder, this);
4676 // It's here only to report an error
4677 if (block != null && block.IsIterator) {
4678 member_type = TypeManager.void_type;
4679 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4688 public override void Emit ()
4690 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4691 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4693 if (OptAttributes != null)
4694 OptAttributes.Emit ();
4698 EmitContext ec = CreateEmitContext (null, null);
4701 // If we use a "this (...)" constructor initializer, then
4702 // do not emit field initializers, they are initialized in the other constructor
4704 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4705 !(Initializer is ConstructorThisInitializer);
4707 if (emit_field_initializers)
4708 Parent.PartialContainer.ResolveFieldInitializers (ec);
4710 if (block != null) {
4711 // If this is a non-static `struct' constructor and doesn't have any
4712 // initializer, it must initialize all of the struct's fields.
4713 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4714 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4715 block.AddThisVariable (Parent, Location);
4717 if (!block.ResolveMeta (ec, ParameterInfo))
4720 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4721 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4722 Initializer = new GeneratedBaseInitializer (Location);
4725 // Spec mandates that Initializers will not have `this' access
4727 if (Initializer != null) {
4729 Initializer.Resolve (ConstructorBuilder, ec);
4730 ec.IsStatic = false;
4731 block.AddScopeStatement (new StatementExpression (Initializer));
4736 Parameters.ApplyAttributes (ConstructorBuilder);
4738 SourceMethod source = null;
4740 ec.OmitDebuggingInfo = true;
4742 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4744 bool unreachable = false;
4745 if (block != null) {
4746 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4749 ec.EmitMeta (block);
4751 if (Report.Errors > 0)
4754 ec.EmitResolvedTopBlock (block, unreachable);
4758 source.CloseMethod ();
4760 if (declarative_security != null) {
4761 foreach (DictionaryEntry de in declarative_security) {
4762 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4769 // Is never override
4770 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4775 public override string GetSignatureForError()
4777 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4780 public override string[] ValidAttributeTargets {
4782 return attribute_targets;
4786 protected override bool VerifyClsCompliance ()
4788 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4792 if (ParameterInfo.Count > 0) {
4793 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4795 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4797 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4798 foreach (Type param in Parameters.Types) {
4799 if (param.IsArray) {
4805 has_compliant_args = true;
4809 #region IMethodData Members
4811 public System.Reflection.CallingConventions CallingConventions {
4813 CallingConventions cc = Parameters.CallingConvention;
4815 if (Parent.PartialContainer.Kind == Kind.Class)
4816 if ((ModFlags & Modifiers.STATIC) == 0)
4817 cc |= CallingConventions.HasThis;
4819 // FIXME: How is `ExplicitThis' used in C#?
4825 public MemberName MethodName {
4831 public Type ReturnType {
4837 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4839 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4840 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4841 ec.CurrentBlock = block;
4845 public bool IsExcluded()
4850 GenericMethod IMethodData.GenericMethod {
4856 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4863 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4865 public interface IMethodData
4867 CallingConventions CallingConventions { get; }
4868 Location Location { get; }
4869 MemberName MethodName { get; }
4870 Type ReturnType { get; }
4871 GenericMethod GenericMethod { get; }
4872 Parameters ParameterInfo { get; }
4874 Attributes OptAttributes { get; }
4875 ToplevelBlock Block { get; set; }
4877 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4878 ObsoleteAttribute GetObsoleteAttribute ();
4879 string GetSignatureForError ();
4881 bool IsClsComplianceRequired ();
4882 void SetMemberIsUsed ();
4883 void EmitExtraSymbolInfo (SourceMethod source);
4887 // Encapsulates most of the Method's state
4889 public class MethodData {
4891 static FieldInfo methodbuilder_attrs_field;
4893 public readonly IMethodData method;
4895 public readonly GenericMethod GenericMethod;
4898 // Are we implementing an interface ?
4900 public MethodInfo implementing;
4905 protected InterfaceMemberBase member;
4906 protected int modifiers;
4907 protected MethodAttributes flags;
4908 protected Type declaring_type;
4909 protected MethodInfo parent_method;
4911 MethodBuilder builder = null;
4912 public MethodBuilder MethodBuilder {
4918 public Type DeclaringType {
4920 return declaring_type;
4924 public MethodData (InterfaceMemberBase member,
4925 int modifiers, MethodAttributes flags, IMethodData method)
4927 this.member = member;
4928 this.modifiers = modifiers;
4931 this.method = method;
4934 public MethodData (InterfaceMemberBase member,
4935 int modifiers, MethodAttributes flags,
4936 IMethodData method, MethodBuilder builder,
4937 GenericMethod generic, MethodInfo parent_method)
4938 : this (member, modifiers, flags, method)
4940 this.builder = builder;
4941 this.GenericMethod = generic;
4942 this.parent_method = parent_method;
4945 public bool Define (DeclSpace parent, string method_full_name)
4947 string name = method.MethodName.Basename;
4949 TypeContainer container = parent.PartialContainer;
4951 PendingImplementation pending = container.PendingImplementations;
4952 if (pending != null){
4953 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4955 if (member.InterfaceType != null){
4956 if (implementing == null){
4957 if (member is PropertyBase) {
4958 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4959 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4960 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4963 Report.Error (539, method.Location,
4964 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4965 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4969 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4970 Report.SymbolRelatedToPreviousError (implementing);
4971 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4972 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4976 if (implementing != null) {
4977 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4978 if (prop_method == null) {
4979 if (TypeManager.IsSpecialMethod (implementing)) {
4980 Report.SymbolRelatedToPreviousError (implementing);
4981 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4982 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4983 implementing.Name.StartsWith ("get_") ? "get" : "set");
4985 } else if (implementing.DeclaringType.IsInterface) {
4986 if (!implementing.IsSpecialName) {
4987 Report.SymbolRelatedToPreviousError (implementing);
4988 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4989 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4992 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4993 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4994 Report.SymbolRelatedToPreviousError (implementing);
4995 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4996 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5005 // For implicit implementations, make sure we are public, for
5006 // explicit implementations, make sure we are private.
5008 if (implementing != null){
5010 // Setting null inside this block will trigger a more
5011 // verbose error reporting for missing interface implementations
5013 // The "candidate" function has been flagged already
5014 // but it wont get cleared
5016 if (member.IsExplicitImpl){
5017 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5018 Report.SymbolRelatedToPreviousError (implementing);
5019 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5020 method.GetSignatureForError ());
5024 if (implementing.DeclaringType.IsInterface) {
5026 // If this is an interface method implementation,
5027 // check for public accessibility
5029 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5031 implementing = null;
5033 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5034 // We may never be private.
5035 implementing = null;
5037 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5039 // We may be protected if we're overriding something.
5041 implementing = null;
5046 // Static is not allowed
5048 if ((modifiers & Modifiers.STATIC) != 0){
5049 implementing = null;
5054 // If implementing is still valid, set flags
5056 if (implementing != null){
5058 // When implementing interface methods, set NewSlot
5059 // unless, we are overwriting a method.
5061 if (implementing.DeclaringType.IsInterface){
5062 if ((modifiers & Modifiers.OVERRIDE) == 0)
5063 flags |= MethodAttributes.NewSlot;
5066 MethodAttributes.Virtual |
5067 MethodAttributes.HideBySig;
5069 // Set Final unless we're virtual, abstract or already overriding a method.
5070 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5071 flags |= MethodAttributes.Final;
5074 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5076 if (builder == null)
5079 if (container.CurrentType != null)
5080 declaring_type = container.CurrentType;
5082 declaring_type = container.TypeBuilder;
5084 if (implementing != null){
5086 // clear the pending implemntation flag
5088 pending.ImplementMethod (name, member.InterfaceType, this, member.IsExplicitImpl);
5090 if (member.IsExplicitImpl)
5091 container.TypeBuilder.DefineMethodOverride (
5092 builder, implementing);
5095 TypeManager.AddMethod (builder, method);
5097 if (GenericMethod != null) {
5098 bool is_override = member.IsExplicitImpl |
5099 ((modifiers & Modifiers.OVERRIDE) != 0);
5101 if (implementing != null)
5102 parent_method = implementing;
5104 EmitContext ec = method.CreateEmitContext (container, null);
5105 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5114 /// Create the MethodBuilder for the method
5116 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5118 if (builder == null) {
5119 builder = container.TypeBuilder.DefineMethod (
5120 method_name, flags, method.CallingConventions,
5121 method.ReturnType, param.GetEmitTypes ());
5127 // Generic method has been already defined to resolve method parameters
5128 // correctly when they use type parameters
5130 builder.SetParameters (param.GetEmitTypes ());
5131 builder.SetReturnType (method.ReturnType);
5133 if (builder.Attributes != flags) {
5135 if (methodbuilder_attrs_field == null)
5136 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5137 methodbuilder_attrs_field.SetValue (builder, flags);
5139 Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5143 throw new InternalErrorException ();
5150 public void Emit (DeclSpace parent)
5152 ToplevelBlock block = method.Block;
5156 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5158 ec = method.CreateEmitContext (parent, null);
5160 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5162 if (GenericMethod != null)
5163 GenericMethod.EmitAttributes ();
5165 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5168 // Handle destructors specially
5170 // FIXME: This code generates buggy code
5172 if (member is Destructor)
5173 EmitDestructor (ec, block);
5175 ec.EmitTopBlock (method, block);
5177 if (source != null) {
5178 method.EmitExtraSymbolInfo (source);
5179 source.CloseMethod ();
5183 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5185 ILGenerator ig = ec.ig;
5187 Label finish = ig.DefineLabel ();
5189 block.SetDestructor ();
5191 ig.BeginExceptionBlock ();
5192 ec.ReturnLabel = finish;
5193 ec.HasReturnLabel = true;
5194 ec.EmitTopBlock (method, block);
5196 // ig.MarkLabel (finish);
5197 ig.BeginFinallyBlock ();
5199 if (ec.ContainerType.BaseType != null) {
5200 Expression member_lookup = Expression.MemberLookup (
5201 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5202 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5204 if (member_lookup != null){
5205 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5207 ig.Emit (OpCodes.Ldarg_0);
5208 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5212 ig.EndExceptionBlock ();
5213 //ig.MarkLabel (ec.ReturnLabel);
5214 ig.Emit (OpCodes.Ret);
5218 // TODO: Should derive from MethodCore
5219 public class Destructor : Method
5221 const int AllowedModifiers =
5225 static string[] attribute_targets = new string [] { "method" };
5227 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5228 string name, Parameters parameters, Attributes attrs,
5230 : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
5233 ModFlags &= ~Modifiers.PRIVATE;
5234 if (!RootContext.StdLib && parent.Name == "System.Object")
5235 ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
5237 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
5240 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5242 if (a.Type == TypeManager.conditional_attribute_type) {
5243 Error_ConditionalAttributeIsNotValid ();
5247 base.ApplyAttributeBuilder (a, cb);
5250 public override string GetSignatureForError ()
5252 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5255 public override string[] ValidAttributeTargets {
5257 return attribute_targets;
5262 abstract public class MemberBase : MemberCore {
5263 protected FullNamedExpression type_name;
5264 public readonly DeclSpace ds;
5265 public readonly GenericMethod GenericMethod;
5268 // The type of this property / indexer / event
5270 protected Type member_type;
5271 public Type MemberType {
5273 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5274 if (member_type == null && type_name != null) {
5275 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5276 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5277 if (type_name != null) {
5278 member_type = type_name.Type;
5286 // The constructor is only exposed to our children
5288 protected MemberBase (DeclSpace parent, GenericMethod generic,
5289 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5290 MemberName name, Attributes attrs)
5291 : base (parent, name, attrs)
5293 this.ds = generic != null ? generic : (DeclSpace) parent;
5294 this.type_name = type;
5295 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5296 GenericMethod = generic;
5297 if (GenericMethod != null)
5298 GenericMethod.ModFlags = ModFlags;
5301 protected virtual bool CheckBase ()
5303 CheckProtectedModifier ();
5308 protected virtual bool DoDefine ()
5310 if (MemberType == null)
5313 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5314 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5315 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5316 GetSignatureForError (), Parent.GetSignatureForError ());
5320 // verify accessibility
5321 if (!IsAccessibleAs (MemberType)) {
5322 Report.SymbolRelatedToPreviousError (MemberType);
5323 if (this is Property)
5324 Report.Error (53, Location,
5325 "Inconsistent accessibility: property type `" +
5326 TypeManager.CSharpName (MemberType) + "' is less " +
5327 "accessible than property `" + GetSignatureForError () + "'");
5328 else if (this is Indexer)
5329 Report.Error (54, Location,
5330 "Inconsistent accessibility: indexer return type `" +
5331 TypeManager.CSharpName (MemberType) + "' is less " +
5332 "accessible than indexer `" + GetSignatureForError () + "'");
5333 else if (this is MethodCore) {
5334 if (this is Operator)
5335 Report.Error (56, Location,
5336 "Inconsistent accessibility: return type `" +
5337 TypeManager.CSharpName (MemberType) + "' is less " +
5338 "accessible than operator `" + GetSignatureForError () + "'");
5340 Report.Error (50, Location,
5341 "Inconsistent accessibility: return type `" +
5342 TypeManager.CSharpName (MemberType) + "' is less " +
5343 "accessible than method `" + GetSignatureForError () + "'");
5345 Report.Error (52, Location,
5346 "Inconsistent accessibility: field type `" +
5347 TypeManager.CSharpName (MemberType) + "' is less " +
5348 "accessible than field `" + GetSignatureForError () + "'");
5356 protected bool IsTypePermitted ()
5358 if (TypeManager.IsSpecialType (MemberType)) {
5359 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5367 // Abstract class for all fields
5369 abstract public class FieldBase : MemberBase {
5370 public FieldBuilder FieldBuilder;
5371 public Status status;
5372 protected Expression initializer;
5375 public enum Status : byte {
5376 HAS_OFFSET = 4 // Used by FieldMember.
5379 static readonly string[] attribute_targets = new string [] { "field" };
5381 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5382 int allowed_mod, MemberName name, Attributes attrs)
5383 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5386 if ((mod & Modifiers.ABSTRACT) != 0)
5387 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5390 public override AttributeTargets AttributeTargets {
5392 return AttributeTargets.Field;
5396 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5398 if (a.Type == TypeManager.field_offset_attribute_type) {
5399 status |= Status.HAS_OFFSET;
5401 if (!Parent.PartialContainer.HasExplicitLayout) {
5402 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5406 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5407 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5413 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5414 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5420 if (a.Type == TypeManager.marshal_as_attr_type) {
5421 UnmanagedMarshal marshal = a.GetMarshal (this);
5422 if (marshal != null) {
5423 FieldBuilder.SetMarshal (marshal);
5428 if ((a.HasSecurityAttribute)) {
5429 a.Error_InvalidSecurityParent ();
5433 FieldBuilder.SetCustomAttribute (cb);
5436 protected override bool CheckBase ()
5438 if (!base.CheckBase ())
5441 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5442 if (conflict_symbol == null) {
5443 if ((ModFlags & Modifiers.NEW) != 0) {
5444 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5449 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5450 Report.SymbolRelatedToPreviousError (conflict_symbol);
5451 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5452 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5458 public override bool Define()
5460 if (MemberType == null || member_type == null)
5463 if (TypeManager.IsGenericParameter (MemberType))
5466 if (MemberType == TypeManager.void_type) {
5467 // TODO: wrong location
5468 Expression.Error_VoidInvalidInTheContext (Location);
5472 if (MemberType.IsSealed && MemberType.IsAbstract) {
5473 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5483 if (!IsTypePermitted ())
5490 // Represents header string for documentation comment.
5492 public override string DocCommentHeader {
5493 get { return "F:"; }
5496 public override void Emit ()
5499 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5500 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5503 if (OptAttributes != null) {
5504 OptAttributes.Emit ();
5507 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5508 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5514 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5516 Report.SymbolRelatedToPreviousError (static_class);
5517 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5521 public Expression Initializer {
5523 if (value != null) {
5524 this.initializer = value;
5529 protected virtual bool IsFieldClsCompliant {
5531 if (FieldBuilder == null)
5534 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5538 public override string[] ValidAttributeTargets
5541 return attribute_targets;
5545 protected override bool VerifyClsCompliance ()
5547 if (!base.VerifyClsCompliance ())
5550 if (!IsFieldClsCompliant) {
5551 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5552 GetSignatureForError ());
5557 public void SetAssigned ()
5559 caching_flags |= Flags.IsAssigned;
5563 interface IFixedBuffer
5565 FieldInfo Element { get; }
5566 Type ElementType { get; }
5569 public class FixedFieldExternal: IFixedBuffer
5571 FieldInfo element_field;
5573 public FixedFieldExternal (FieldInfo fi)
5575 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5578 #region IFixedField Members
5580 public FieldInfo Element {
5582 return element_field;
5586 public Type ElementType {
5588 return element_field.FieldType;
5596 /// Fixed buffer implementation
5598 public class FixedField : FieldBase, IFixedBuffer
5600 public const string FixedElementName = "FixedElementField";
5601 static int GlobalCounter = 0;
5602 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5603 static FieldInfo[] fi;
5605 TypeBuilder fixed_buffer_type;
5606 FieldBuilder element;
5607 Expression size_expr;
5609 const int AllowedModifiers =
5612 Modifiers.PROTECTED |
5613 Modifiers.INTERNAL |
5616 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5617 Expression size_expr, Attributes attrs, Location loc):
5618 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5620 if (RootContext.Version == LanguageVersion.ISO_1)
5621 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5623 this.size_expr = size_expr;
5626 public override bool Define()
5628 if (!Parent.IsInUnsafeScope)
5629 Expression.UnsafeError (Location);
5631 if (!base.Define ())
5634 if (!TypeManager.IsPrimitiveType (MemberType)) {
5635 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",
5636 GetSignatureForError ());
5639 // Create nested fixed buffer container
5640 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5641 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5642 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5644 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5645 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5647 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5648 Parent.MemberCache.AddMember (FieldBuilder, this);
5649 TypeManager.RegisterFieldBase (FieldBuilder, this);
5654 public override void Emit()
5656 if (Parent.PartialContainer.Kind != Kind.Struct) {
5657 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5658 GetSignatureForError ());
5661 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5662 Constant c = size_expr.ResolveAsConstant (ec, this);
5666 IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5667 if (buffer_size_const == null)
5670 int buffer_size = buffer_size_const.Value;
5672 if (buffer_size <= 0) {
5673 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5677 int type_size = Expression.GetTypeSize (MemberType);
5679 if (buffer_size > int.MaxValue / type_size) {
5680 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5681 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5685 buffer_size *= type_size;
5686 EmitFieldSize (buffer_size);
5690 // Emit compiler generated fixed buffer type attribute
5692 CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5694 Type attr_type = TypeManager.CoreLookupType (
5695 "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5697 if (attr_type != null) {
5698 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5700 cab = new CustomAttributeBuilder (ci, new object [0]);
5701 TypeManager.unsafe_value_type_attr = cab;
5707 fixed_buffer_type.SetCustomAttribute (cab);
5712 void EmitFieldSize (int buffer_size)
5714 if (TypeManager.struct_layout_attribute_type == null) {
5715 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5716 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5718 if (TypeManager.struct_layout_attribute_type == null)
5723 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5725 object [] fi_val = new object [] { buffer_size };
5727 if (TypeManager.struct_layout_attribute_ctor == null) {
5728 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5729 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5730 if (TypeManager.struct_layout_attribute_ctor == null)
5734 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5735 ctor_args, fi, fi_val);
5736 fixed_buffer_type.SetCustomAttribute (cab);
5739 // Don't emit FixedBufferAttribute attribute for private types
5741 if ((ModFlags & Modifiers.PRIVATE) != 0)
5744 if (TypeManager.fixed_buffer_attr_ctor == null) {
5745 if (TypeManager.fixed_buffer_attr_type == null) {
5746 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5747 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5749 if (TypeManager.fixed_buffer_attr_type == null)
5753 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5754 Location, TypeManager.type_type, TypeManager.int32_type);
5756 if (TypeManager.fixed_buffer_attr_ctor == null)
5760 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5761 FieldBuilder.SetCustomAttribute (cab);
5764 protected override bool IsFieldClsCompliant {
5770 public void SetCharSet (TypeAttributes ta)
5772 TypeAttributes cta = fixed_buffer_type.Attributes;
5773 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5774 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5775 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5776 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5777 else if (cta == 0 && ta != 0)
5778 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5781 void SetTypeBuilderCharSet (TypeAttributes ta)
5783 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5785 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5787 mi.Invoke (fixed_buffer_type, new object [] { ta });
5791 #region IFixedField Members
5793 public FieldInfo Element {
5799 public Type ElementType {
5809 // The Field class is used to represents class/struct fields during parsing.
5811 public class Field : FieldBase {
5813 // Modifiers allowed in a class declaration
5815 const int AllowedModifiers =
5818 Modifiers.PROTECTED |
5819 Modifiers.INTERNAL |
5822 Modifiers.VOLATILE |
5826 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5827 Attributes attrs, Location loc)
5828 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5833 bool CanBeVolatile ()
5835 if (TypeManager.IsReferenceType (MemberType))
5838 if (MemberType.IsEnum)
5841 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5842 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5843 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5844 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5845 MemberType == TypeManager.float_type)
5851 bool CheckStructLayout (Type type, bool isStatic)
5853 if (TypeManager.IsBuiltinType (type))
5857 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5861 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5862 if (!TypeManager.IsGenericType (type))
5865 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5866 if (!CheckStructLayout (t, false))
5872 Report.Error (523, Location,
5873 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5874 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5878 public override bool Define ()
5880 if (!base.Define ())
5883 if ((ModFlags & Modifiers.VOLATILE) != 0){
5884 if (!CanBeVolatile ()) {
5885 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5886 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5889 if ((ModFlags & Modifiers.READONLY) != 0){
5890 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5891 GetSignatureForError ());
5897 Type[] required_modifier = null;
5898 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5899 if (TypeManager.isvolatile_type == null)
5900 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5901 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5903 if (TypeManager.isvolatile_type != null)
5904 required_modifier = new Type [] { TypeManager.isvolatile_type };
5907 FieldBuilder = Parent.TypeBuilder.DefineField (
5908 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5910 FieldBuilder = Parent.TypeBuilder.DefineField (
5911 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5913 Parent.MemberCache.AddMember (FieldBuilder, this);
5914 TypeManager.RegisterFieldBase (FieldBuilder, this);
5916 catch (ArgumentException) {
5917 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5921 if (initializer != null) {
5922 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5923 new FieldInitializer (FieldBuilder, initializer));
5925 if (Parent.PartialContainer.Kind == Kind.Struct)
5926 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5932 public override string GetSignatureForError ()
5934 string s = base.GetSignatureForError ();
5935 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5938 // Undecorate name mangling
5939 int l = s.LastIndexOf ('>');
5940 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5943 protected override bool VerifyClsCompliance ()
5945 if (!base.VerifyClsCompliance ())
5948 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5949 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5957 // `set' and `get' accessors are represented with an Accessor.
5959 public class Accessor {
5961 // Null if the accessor is empty, or a Block if not
5963 public const int AllowedModifiers =
5965 Modifiers.PROTECTED |
5966 Modifiers.INTERNAL |
5969 public ToplevelBlock Block;
5970 public Attributes Attributes;
5971 public Location Location;
5972 public int ModFlags;
5973 public Parameters Parameters;
5975 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5981 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5985 // Ooouh Martin, templates are missing here.
5986 // When it will be possible move here a lot of child code and template method type.
5987 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5988 protected MethodData method_data;
5989 protected ToplevelBlock block;
5990 protected ListDictionary declarative_security;
5992 // The accessor are created event if they are not wanted.
5993 // But we need them because their names are reserved.
5994 // Field says whether accessor will be emited or not
5995 public readonly bool IsDummy;
5997 protected readonly string prefix;
5999 ReturnParameter return_attributes;
6001 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6002 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6004 this.prefix = prefix;
6008 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6010 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6011 accessor.Attributes)
6013 this.prefix = prefix;
6014 this.block = accessor.Block;
6017 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6019 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6022 public void UpdateName (InterfaceMemberBase member)
6024 SetMemberName (SetupName (prefix, member, Location));
6027 #region IMethodData Members
6029 public ToplevelBlock Block {
6039 public CallingConventions CallingConventions {
6041 return CallingConventions.Standard;
6045 public bool IsExcluded ()
6050 GenericMethod IMethodData.GenericMethod {
6056 public MemberName MethodName {
6062 public Type[] ParameterTypes {
6064 return ParameterInfo.Types;
6068 public abstract Parameters ParameterInfo { get ; }
6069 public abstract Type ReturnType { get; }
6070 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6074 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6076 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6077 a.Type == TypeManager.conditional_attribute_type) {
6078 Report.Error (1667, a.Location,
6079 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6080 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6084 if (a.IsValidSecurityAttribute ()) {
6085 if (declarative_security == null)
6086 declarative_security = new ListDictionary ();
6087 a.ExtractSecurityPermissionSet (declarative_security);
6091 if (a.Target == AttributeTargets.Method) {
6092 method_data.MethodBuilder.SetCustomAttribute (cb);
6096 if (a.Target == AttributeTargets.ReturnValue) {
6097 if (return_attributes == null)
6098 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6100 return_attributes.ApplyAttributeBuilder (a, cb);
6104 ApplyToExtraTarget (a, cb);
6107 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6109 throw new NotSupportedException ("You forgot to define special attribute target handling");
6112 // It is not supported for the accessors
6113 public sealed override bool Define()
6115 throw new NotSupportedException ();
6118 public void Emit (DeclSpace parent)
6120 EmitMethod (parent);
6123 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6124 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6125 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6126 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6128 if (OptAttributes != null)
6129 OptAttributes.Emit ();
6131 if (declarative_security != null) {
6132 foreach (DictionaryEntry de in declarative_security) {
6133 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6140 protected virtual void EmitMethod (DeclSpace parent)
6142 method_data.Emit (parent);
6145 public override bool EnableOverloadChecks (MemberCore overload)
6147 // This can only happen with indexers and it will
6148 // be catched as indexer difference
6149 if (overload is AbstractPropertyEventMethod)
6152 if (overload is MethodCore) {
6153 caching_flags |= Flags.MethodOverloadsExist;
6159 public override bool IsClsComplianceRequired()
6164 public bool IsDuplicateImplementation (MethodCore method)
6166 if (!MemberName.Equals (method.MemberName))
6169 Type[] param_types = method.ParameterTypes;
6171 if (param_types == null || param_types.Length != ParameterTypes.Length)
6174 for (int i = 0; i < param_types.Length; i++)
6175 if (param_types [i] != ParameterTypes [i])
6178 Report.SymbolRelatedToPreviousError (method);
6179 Report.Error (82, Location, "A member `{0}' is already reserved",
6180 method.GetSignatureForError ());
6184 public override bool IsUsed
6195 // Represents header string for documentation comment.
6197 public override string DocCommentHeader {
6198 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6201 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6206 // Properties and Indexers both generate PropertyBuilders, we use this to share
6207 // their common bits.
6209 abstract public class PropertyBase : PropertyBasedMember {
6211 public class GetMethod : PropertyMethod
6213 static string[] attribute_targets = new string [] { "method", "return" };
6215 public GetMethod (PropertyBase method):
6216 base (method, "get_")
6220 public GetMethod (PropertyBase method, Accessor accessor):
6221 base (method, accessor, "get_")
6225 public override MethodBuilder Define (DeclSpace parent)
6227 base.Define (parent);
6232 method_data = new MethodData (method, ModFlags, flags, this);
6234 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6237 return method_data.MethodBuilder;
6240 public override Type ReturnType {
6242 return method.MemberType;
6246 public override Parameters ParameterInfo {
6248 return Parameters.EmptyReadOnlyParameters;
6252 public override string[] ValidAttributeTargets {
6254 return attribute_targets;
6259 public class SetMethod : PropertyMethod {
6261 static string[] attribute_targets = new string [] { "method", "param", "return" };
6262 ImplicitParameter param_attr;
6263 protected Parameters parameters;
6265 public SetMethod (PropertyBase method) :
6266 base (method, "set_")
6268 parameters = new Parameters (
6269 new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6272 public SetMethod (PropertyBase method, Accessor accessor):
6273 base (method, accessor, "set_")
6275 this.parameters = accessor.Parameters;
6278 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6280 if (a.Target == AttributeTargets.Parameter) {
6281 if (param_attr == null)
6282 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6284 param_attr.ApplyAttributeBuilder (a, cb);
6288 base.ApplyAttributeBuilder (a, cb);
6291 public override Parameters ParameterInfo {
6297 public override MethodBuilder Define (DeclSpace parent)
6299 parameters.Resolve (ResolveContext);
6300 base.Define (parent);
6305 method_data = new MethodData (method, ModFlags, flags, this);
6307 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6310 return method_data.MethodBuilder;
6313 public override Type ReturnType {
6315 return TypeManager.void_type;
6319 public override string[] ValidAttributeTargets {
6321 return attribute_targets;
6326 static string[] attribute_targets = new string [] { "property" };
6328 public abstract class PropertyMethod : AbstractPropertyEventMethod
6330 protected readonly PropertyBase method;
6331 protected MethodAttributes flags;
6333 public PropertyMethod (PropertyBase method, string prefix)
6334 : base (method, prefix)
6336 this.method = method;
6337 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);
6340 public PropertyMethod (PropertyBase method, Accessor accessor,
6342 : base (method, accessor, prefix)
6344 this.method = method;
6345 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6347 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6348 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6352 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6354 if (a.IsInternalMethodImplAttribute) {
6355 method.is_external_implementation = true;
6358 base.ApplyAttributeBuilder (a, cb);
6361 public override AttributeTargets AttributeTargets {
6363 return AttributeTargets.Method;
6367 public override bool IsClsComplianceRequired ()
6369 return method.IsClsComplianceRequired ();
6372 public virtual MethodBuilder Define (DeclSpace parent)
6374 CheckForDuplications ();
6377 if (method.InterfaceType != null && method.IsExplicitImpl) {
6378 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6379 MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6381 Report.SymbolRelatedToPreviousError (mi);
6382 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6383 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6389 TypeContainer container = parent.PartialContainer;
6392 // Check for custom access modifier
6394 if ((ModFlags & Modifiers.Accessibility) == 0) {
6395 ModFlags |= method.ModFlags;
6396 flags = method.flags;
6398 if (container.Kind == Kind.Interface)
6399 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6400 GetSignatureForError ());
6402 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6403 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6406 CheckModifiers (ModFlags);
6407 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6408 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6409 flags = Modifiers.MethodAttr (ModFlags);
6410 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6413 CheckAbstractAndExtern (block != null);
6415 if (block != null && block.IsIterator)
6416 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6421 public bool HasCustomAccessModifier
6424 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6428 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6430 return new EmitContext (this,
6431 ds, method.ds, method.Location, ig, ReturnType,
6432 method.ModFlags, false);
6435 public override ObsoleteAttribute GetObsoleteAttribute ()
6437 return method.GetObsoleteAttribute ();
6440 public override string GetSignatureForError()
6442 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6445 void CheckModifiers (int modflags)
6447 modflags &= Modifiers.Accessibility;
6449 int mflags = method.ModFlags & Modifiers.Accessibility;
6451 if ((mflags & Modifiers.PUBLIC) != 0) {
6452 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6454 else if ((mflags & Modifiers.PROTECTED) != 0) {
6455 if ((mflags & Modifiers.INTERNAL) != 0)
6456 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6458 flags |= Modifiers.PRIVATE;
6460 else if ((mflags & Modifiers.INTERNAL) != 0)
6461 flags |= Modifiers.PRIVATE;
6463 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6464 Report.Error (273, Location,
6465 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6466 GetSignatureForError (), method.GetSignatureForError ());
6470 protected bool CheckForDuplications ()
6472 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6475 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6479 public PropertyMethod Get, Set;
6480 public PropertyBuilder PropertyBuilder;
6481 public MethodBuilder GetBuilder, SetBuilder;
6483 protected bool define_set_first = false;
6485 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6486 int allowed_mod, MemberName name,
6487 Attributes attrs, bool define_set_first)
6488 : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6490 this.define_set_first = define_set_first;
6493 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6495 if (a.HasSecurityAttribute) {
6496 a.Error_InvalidSecurityParent ();
6500 PropertyBuilder.SetCustomAttribute (cb);
6503 public override AttributeTargets AttributeTargets {
6505 return AttributeTargets.Property;
6509 public override bool Define ()
6514 if (!IsTypePermitted ())
6520 protected override bool DoDefine ()
6522 if (!base.DoDefine ())
6526 // Accessors modifiers check
6528 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6529 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6530 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6531 GetSignatureForError ());
6535 if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
6536 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6537 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6538 Report.Error (276, Location,
6539 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6540 GetSignatureForError ());
6545 if (MemberType.IsGenericParameter)
6549 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6550 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6559 GetBuilder = Get.Define (Parent);
6560 return (Get.IsDummy) ? true : GetBuilder != null;
6563 bool DefineSet (bool define)
6568 SetBuilder = Set.Define (Parent);
6569 return (Set.IsDummy) ? true : SetBuilder != null;
6572 protected bool DefineAccessors ()
6574 return DefineSet (define_set_first) &&
6576 DefineSet (!define_set_first);
6579 protected abstract PropertyInfo ResolveBaseProperty ();
6581 // TODO: rename to Resolve......
6582 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6584 PropertyInfo base_property = ResolveBaseProperty ();
6585 if (base_property == null)
6588 base_ret_type = base_property.PropertyType;
6589 MethodInfo get_accessor = base_property.GetGetMethod (true);
6590 MethodInfo set_accessor = base_property.GetSetMethod (true);
6591 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6594 // Check base property accessors conflict
6596 if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6597 if (get_accessor == null) {
6598 if (Get != null && !Get.IsDummy) {
6599 Report.SymbolRelatedToPreviousError (base_property);
6600 Report.Error (545, Location,
6601 "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6602 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6605 get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6607 if (!Get.IsDummy && !CheckAccessModifiers (
6608 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6609 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6612 if (set_accessor == null) {
6613 if (Set != null && !Set.IsDummy) {
6614 Report.SymbolRelatedToPreviousError (base_property);
6615 Report.Error (546, Location,
6616 "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6617 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6620 set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6622 if (!Set.IsDummy && !CheckAccessModifiers (
6623 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6624 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6628 // When one accessor does not exist and property hides base one
6629 // we need to propagate this upwards
6630 if (set_accessor == null)
6631 set_accessor = get_accessor;
6634 // Get the less restrictive access
6636 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6639 public override void Emit ()
6642 // The PropertyBuilder can be null for explicit implementations, in that
6643 // case, we do not actually emit the ".property", so there is nowhere to
6644 // put the attribute
6646 if (PropertyBuilder != null && OptAttributes != null)
6647 OptAttributes.Emit ();
6659 /// Tests whether accessors are not in collision with some method (CS0111)
6661 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6663 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6666 public override bool IsUsed
6672 return Get.IsUsed | Set.IsUsed;
6676 protected override void SetMemberName (MemberName new_name)
6678 base.SetMemberName (new_name);
6680 Get.UpdateName (this);
6681 Set.UpdateName (this);
6684 public override string[] ValidAttributeTargets {
6686 return attribute_targets;
6691 // Represents header string for documentation comment.
6693 public override string DocCommentHeader {
6694 get { return "P:"; }
6698 public class Property : PropertyBase {
6699 const int AllowedModifiers =
6702 Modifiers.PROTECTED |
6703 Modifiers.INTERNAL |
6707 Modifiers.OVERRIDE |
6708 Modifiers.ABSTRACT |
6713 const int AllowedInterfaceModifiers =
6716 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6719 Field field = new Field (
6721 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6722 "<" + Name + ">k__BackingField", null, Location);
6723 ((TypeContainer)Parent).PartialContainer.AddField (field);
6726 get_block.Block = new ToplevelBlock (block, null, Location);
6727 Return r = new Return (new SimpleName(field.Name, Location), Location);
6728 get_block.Block.AddStatement (r);
6729 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6732 set_block.Block = new ToplevelBlock (block, set_block.Parameters, Location);
6733 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6734 set_block.Block.AddStatement (new StatementExpression(a));
6735 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6738 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6739 MemberName name, Attributes attrs, Accessor get_block,
6740 Accessor set_block, bool define_set_first)
6741 : this (parent, type, mod, name, attrs, get_block, set_block,
6742 define_set_first, null)
6746 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6747 MemberName name, Attributes attrs, Accessor get_block,
6748 Accessor set_block, bool define_set_first, Block current_block)
6749 : base (parent, type, mod,
6750 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6751 name, attrs, define_set_first)
6753 if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6754 get_block != null && get_block.Block == null &&
6755 set_block != null && set_block.Block == null) {
6756 if (RootContext.Version <= LanguageVersion.ISO_2)
6757 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6759 CreateAutomaticProperty (current_block, get_block, set_block);
6762 if (get_block == null)
6763 Get = new GetMethod (this);
6765 Get = new GetMethod (this, get_block);
6767 if (set_block == null)
6768 Set = new SetMethod (this);
6770 Set = new SetMethod (this, set_block);
6773 public override bool Define ()
6775 if (!DoDefineBase ())
6778 if (!base.Define ())
6781 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6783 if (!DefineAccessors ())
6789 // FIXME - PropertyAttributes.HasDefault ?
6791 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6792 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6795 PropertyBuilder.SetGetMethod (GetBuilder);
6796 Parent.MemberCache.AddMember (GetBuilder, Get);
6800 PropertyBuilder.SetSetMethod (SetBuilder);
6801 Parent.MemberCache.AddMember (SetBuilder, Set);
6804 TypeManager.RegisterProperty (PropertyBuilder, this);
6805 Parent.MemberCache.AddMember (PropertyBuilder, this);
6809 public override void Emit ()
6811 if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6812 Report.Error (842, Location,
6813 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6814 GetSignatureForError ());
6820 protected override PropertyInfo ResolveBaseProperty ()
6822 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6823 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6828 /// Gigantic workaround for lameness in SRE follows :
6829 /// This class derives from EventInfo and attempts to basically
6830 /// wrap around the EventBuilder so that FindMembers can quickly
6831 /// return this in it search for members
6833 public class MyEventBuilder : EventInfo {
6836 // We use this to "point" to our Builder which is
6837 // not really a MemberInfo
6839 EventBuilder MyBuilder;
6842 // We "catch" and wrap these methods
6844 MethodInfo raise, remove, add;
6846 EventAttributes attributes;
6847 Type declaring_type, reflected_type, event_type;
6852 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6854 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6856 // And now store the values in our own fields.
6858 declaring_type = type_builder;
6860 reflected_type = type_builder;
6862 attributes = event_attr;
6865 this.event_type = event_type;
6869 // Methods that you have to override. Note that you only need
6870 // to "implement" the variants that take the argument (those are
6871 // the "abstract" methods, the others (GetAddMethod()) are
6874 public override MethodInfo GetAddMethod (bool nonPublic)
6879 public override MethodInfo GetRemoveMethod (bool nonPublic)
6884 public override MethodInfo GetRaiseMethod (bool nonPublic)
6890 // These methods make "MyEventInfo" look like a Builder
6892 public void SetRaiseMethod (MethodBuilder raiseMethod)
6894 raise = raiseMethod;
6895 MyBuilder.SetRaiseMethod (raiseMethod);
6898 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6900 remove = removeMethod;
6901 MyBuilder.SetRemoveOnMethod (removeMethod);
6904 public void SetAddOnMethod (MethodBuilder addMethod)
6907 MyBuilder.SetAddOnMethod (addMethod);
6910 public void SetCustomAttribute (CustomAttributeBuilder cb)
6912 MyBuilder.SetCustomAttribute (cb);
6915 public override object [] GetCustomAttributes (bool inherit)
6917 // FIXME : There's nothing which can be seemingly done here because
6918 // we have no way of getting at the custom attribute objects of the
6923 public override object [] GetCustomAttributes (Type t, bool inherit)
6925 // FIXME : Same here !
6929 public override bool IsDefined (Type t, bool b)
6934 public override EventAttributes Attributes {
6940 public override string Name {
6946 public override Type DeclaringType {
6948 return declaring_type;
6952 public override Type ReflectedType {
6954 return reflected_type;
6958 public Type EventType {
6964 public void SetUsed ()
6966 if (my_event != null) {
6967 // my_event.SetAssigned ();
6968 my_event.SetMemberIsUsed ();
6974 /// For case when event is declared like property (with add and remove accessors).
6976 public class EventProperty: Event {
6977 abstract class AEventPropertyAccessor : AEventAccessor
6979 protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6980 base (method, accessor, prefix)
6984 public override MethodBuilder Define (DeclSpace ds)
6986 CheckAbstractAndExtern (block != null);
6987 return base.Define (ds);
6990 public override string GetSignatureForError ()
6992 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6996 sealed class AddDelegateMethod: AEventPropertyAccessor
6998 public AddDelegateMethod (Event method, Accessor accessor):
6999 base (method, accessor, "add_")
7003 protected override MethodInfo DelegateMethodInfo {
7005 return TypeManager.delegate_combine_delegate_delegate;
7010 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7012 public RemoveDelegateMethod (Event method, Accessor accessor):
7013 base (method, accessor, "remove_")
7017 protected override MethodInfo DelegateMethodInfo {
7019 return TypeManager.delegate_remove_delegate_delegate;
7025 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7027 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7029 Attributes attrs, Accessor add, Accessor remove)
7030 : base (parent, type, mod_flags, name, attrs)
7032 Add = new AddDelegateMethod (this, add);
7033 Remove = new RemoveDelegateMethod (this, remove);
7036 public override bool Define()
7038 if (!base.Define ())
7045 public override string[] ValidAttributeTargets {
7047 return attribute_targets;
7053 /// Event is declared like field.
7055 public class EventField : Event {
7056 abstract class EventFieldAccessor : AEventAccessor
7058 protected EventFieldAccessor (Event method, string prefix)
7059 : base (method, prefix)
7063 protected override void EmitMethod(DeclSpace parent)
7065 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7068 MethodBuilder mb = method_data.MethodBuilder;
7069 ILGenerator ig = mb.GetILGenerator ();
7071 // TODO: because we cannot use generics yet
7072 FieldInfo field_info = ((EventField)method).FieldBuilder;
7074 if (parent is Class) {
7075 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7078 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7079 ig.Emit (OpCodes.Ldsfld, field_info);
7080 ig.Emit (OpCodes.Ldarg_0);
7081 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7082 ig.Emit (OpCodes.Castclass, method.MemberType);
7083 ig.Emit (OpCodes.Stsfld, field_info);
7085 ig.Emit (OpCodes.Ldarg_0);
7086 ig.Emit (OpCodes.Ldarg_0);
7087 ig.Emit (OpCodes.Ldfld, field_info);
7088 ig.Emit (OpCodes.Ldarg_1);
7089 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7090 ig.Emit (OpCodes.Castclass, method.MemberType);
7091 ig.Emit (OpCodes.Stfld, field_info);
7093 ig.Emit (OpCodes.Ret);
7097 sealed class AddDelegateMethod: EventFieldAccessor
7099 public AddDelegateMethod (Event method):
7100 base (method, "add_")
7104 protected override MethodInfo DelegateMethodInfo {
7106 return TypeManager.delegate_combine_delegate_delegate;
7111 sealed class RemoveDelegateMethod: EventFieldAccessor
7113 public RemoveDelegateMethod (Event method):
7114 base (method, "remove_")
7118 protected override MethodInfo DelegateMethodInfo {
7120 return TypeManager.delegate_remove_delegate_delegate;
7126 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7127 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7129 public FieldBuilder FieldBuilder;
7130 public Expression Initializer;
7132 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7133 : base (parent, type, mod_flags, name, attrs)
7135 Add = new AddDelegateMethod (this);
7136 Remove = new RemoveDelegateMethod (this);
7139 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7141 if (a.Target == AttributeTargets.Field) {
7142 FieldBuilder.SetCustomAttribute (cb);
7146 if (a.Target == AttributeTargets.Method) {
7147 int errors = Report.Errors;
7148 Add.ApplyAttributeBuilder (a, cb);
7149 if (errors == Report.Errors)
7150 Remove.ApplyAttributeBuilder (a, cb);
7154 base.ApplyAttributeBuilder (a, cb);
7157 public override bool Define()
7159 if (!base.Define ())
7165 // FIXME: We are unable to detect whether generic event is used because
7166 // we are using FieldExpr instead of EventExpr for event access in that
7167 // case. When this issue will be fixed this hack can be removed.
7168 if (TypeManager.IsGenericType (MemberType))
7171 if (Add.IsInterfaceImplementation)
7174 FieldBuilder = Parent.TypeBuilder.DefineField (
7176 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7177 TypeManager.RegisterEventField (EventBuilder, this);
7179 if (Initializer != null) {
7180 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7181 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7182 GetSignatureForError ());
7186 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7187 new FieldInitializer (FieldBuilder, Initializer));
7193 public override string[] ValidAttributeTargets
7196 return IsInterface ? attribute_targets_interface : attribute_targets;
7201 public abstract class Event : PropertyBasedMember {
7202 public abstract class AEventAccessor : AbstractPropertyEventMethod
7204 protected readonly Event method;
7205 ImplicitParameter param_attr;
7207 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7209 protected AEventAccessor (Event method, string prefix)
7210 : base (method, prefix)
7212 this.method = method;
7213 this.ModFlags = method.ModFlags;
7216 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7217 : base (method, accessor, prefix)
7219 this.method = method;
7220 this.ModFlags = method.ModFlags;
7223 public bool IsInterfaceImplementation {
7224 get { return method_data.implementing != null; }
7227 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7229 if (a.IsInternalMethodImplAttribute) {
7230 method.is_external_implementation = true;
7233 base.ApplyAttributeBuilder (a, cb);
7236 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7238 if (a.Target == AttributeTargets.Parameter) {
7239 if (param_attr == null)
7240 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7242 param_attr.ApplyAttributeBuilder (a, cb);
7246 base.ApplyAttributeBuilder (a, cb);
7249 public override AttributeTargets AttributeTargets {
7251 return AttributeTargets.Method;
7255 public override bool IsClsComplianceRequired ()
7257 return method.IsClsComplianceRequired ();
7260 public virtual MethodBuilder Define (DeclSpace parent)
7262 method_data = new MethodData (method, method.ModFlags,
7263 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7265 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7268 MethodBuilder mb = method_data.MethodBuilder;
7269 ParameterInfo.ApplyAttributes (mb);
7273 protected abstract MethodInfo DelegateMethodInfo { get; }
7275 public override Type ReturnType {
7277 return TypeManager.void_type;
7281 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7283 return new EmitContext (
7284 this, method.Parent, Location, ig, ReturnType,
7285 method.ModFlags, false);
7288 public override ObsoleteAttribute GetObsoleteAttribute ()
7290 return method.GetObsoleteAttribute ();
7293 public override string[] ValidAttributeTargets {
7295 return attribute_targets;
7299 public override Parameters ParameterInfo {
7301 return method.parameters;
7307 const int AllowedModifiers =
7310 Modifiers.PROTECTED |
7311 Modifiers.INTERNAL |
7316 Modifiers.OVERRIDE |
7318 Modifiers.ABSTRACT |
7321 const int AllowedInterfaceModifiers =
7324 public AEventAccessor Add, Remove;
7325 public MyEventBuilder EventBuilder;
7326 public MethodBuilder AddBuilder, RemoveBuilder;
7328 Parameters parameters;
7330 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7331 : base (parent, null, type, mod_flags,
7332 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7337 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7339 if ((a.HasSecurityAttribute)) {
7340 a.Error_InvalidSecurityParent ();
7344 EventBuilder.SetCustomAttribute (cb);
7347 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7349 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7352 public override AttributeTargets AttributeTargets {
7354 return AttributeTargets.Event;
7358 public override bool Define ()
7360 if (!DoDefineBase ())
7366 if (!TypeManager.IsDelegateType (MemberType)) {
7367 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7371 parameters = Parameters.CreateFullyResolved (
7372 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7377 if (TypeManager.delegate_combine_delegate_delegate == null) {
7378 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7379 TypeManager.delegate_type, "Combine", Location,
7380 TypeManager.delegate_type, TypeManager.delegate_type);
7382 if (TypeManager.delegate_remove_delegate_delegate == null) {
7383 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7384 TypeManager.delegate_type, "Remove", Location,
7385 TypeManager.delegate_type, TypeManager.delegate_type);
7389 // Now define the accessors
7392 AddBuilder = Add.Define (Parent);
7393 if (AddBuilder == null)
7396 RemoveBuilder = Remove.Define (Parent);
7397 if (RemoveBuilder == null)
7400 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7401 EventBuilder.SetAddOnMethod (AddBuilder);
7402 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7404 Parent.MemberCache.AddMember (EventBuilder, this);
7405 Parent.MemberCache.AddMember (AddBuilder, Add);
7406 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7411 public override void Emit ()
7413 if (OptAttributes != null) {
7414 OptAttributes.Emit ();
7418 Remove.Emit (Parent);
7423 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7425 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7426 Parent.TypeBuilder, Name);
7431 AParametersCollection pd = TypeManager.GetParameterData (mi);
7432 base_ret_type = pd.Types [0];
7437 // Represents header string for documentation comment.
7439 public override string DocCommentHeader {
7440 get { return "E:"; }
7445 public class Indexer : PropertyBase
7447 public class GetIndexerMethod : GetMethod
7449 Parameters parameters;
7451 public GetIndexerMethod (Indexer method):
7454 this.parameters = method.parameters;
7457 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7458 base (method, accessor)
7460 parameters = accessor.Parameters;
7463 public override MethodBuilder Define (DeclSpace parent)
7465 parameters.Resolve (ResolveContext);
7466 return base.Define (parent);
7469 public override bool EnableOverloadChecks (MemberCore overload)
7471 if (base.EnableOverloadChecks (overload)) {
7472 overload.caching_flags |= Flags.MethodOverloadsExist;
7479 public override Parameters ParameterInfo {
7486 public class SetIndexerMethod: SetMethod
7488 public SetIndexerMethod (Indexer method):
7491 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7494 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7495 base (method, accessor)
7497 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();
7500 public override bool EnableOverloadChecks (MemberCore overload)
7502 if (base.EnableOverloadChecks (overload)) {
7503 overload.caching_flags |= Flags.MethodOverloadsExist;
7511 const int AllowedModifiers =
7514 Modifiers.PROTECTED |
7515 Modifiers.INTERNAL |
7519 Modifiers.OVERRIDE |
7524 const int AllowedInterfaceModifiers =
7527 public readonly Parameters parameters;
7529 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7530 Parameters parameters, Attributes attrs,
7531 Accessor get_block, Accessor set_block, bool define_set_first)
7532 : base (parent, type, mod,
7533 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7534 name, attrs, define_set_first)
7536 this.parameters = parameters;
7538 if (get_block == null)
7539 Get = new GetIndexerMethod (this);
7541 Get = new GetIndexerMethod (this, get_block);
7543 if (set_block == null)
7544 Set = new SetIndexerMethod (this);
7546 Set = new SetIndexerMethod (this, set_block);
7549 public override bool Define ()
7551 if (!DoDefineBase ())
7554 if (!base.Define ())
7557 if (!DefineParameters (parameters))
7560 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7561 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7562 if (indexer_attr != null) {
7563 // Remove the attribute from the list because it is not emitted
7564 OptAttributes.Attrs.Remove (indexer_attr);
7566 string name = indexer_attr.GetIndexerAttributeValue ();
7572 if (IsExplicitImpl) {
7573 Report.Error (415, indexer_attr.Location,
7574 "The `IndexerName' attribute is valid only on an " +
7575 "indexer that is not an explicit interface member declaration");
7579 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7580 Report.Error (609, indexer_attr.Location,
7581 "Cannot set the `IndexerName' attribute on an indexer marked override");
7587 if (InterfaceType != null) {
7588 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7589 if (base_IndexerName != Name)
7590 ShortName = base_IndexerName;
7593 if (!Parent.PartialContainer.AddMember (this) ||
7594 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7597 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7598 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7602 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7604 if (!DefineAccessors ())
7611 // Now name the parameters
7613 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7614 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7617 PropertyBuilder.SetGetMethod (GetBuilder);
7618 Parent.MemberCache.AddMember (GetBuilder, Get);
7622 PropertyBuilder.SetSetMethod (SetBuilder);
7623 Parent.MemberCache.AddMember (SetBuilder, Set);
7626 TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7627 Parent.MemberCache.AddMember (PropertyBuilder, this);
7631 public override bool EnableOverloadChecks (MemberCore overload)
7633 if (overload is Indexer) {
7634 caching_flags |= Flags.MethodOverloadsExist;
7641 public override string GetDocCommentName (DeclSpace ds)
7643 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7646 public override string GetSignatureForError ()
7648 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7649 if (MemberName.Left != null) {
7651 sb.Append (MemberName.Left.GetSignatureForError ());
7654 sb.Append (".this");
7655 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7656 return sb.ToString ();
7659 protected override PropertyInfo ResolveBaseProperty ()
7661 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7662 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7665 protected override bool VerifyClsCompliance ()
7667 if (!base.VerifyClsCompliance ())
7670 parameters.VerifyClsCompliance ();
7675 public class Operator : MethodOrOperator {
7677 const int AllowedModifiers =
7683 public enum OpType : byte {
7693 // Unary and Binary operators
7716 // Implicit and Explicit
7720 // Just because of enum
7724 public readonly OpType OperatorType;
7726 static readonly string [] [] names;
7730 names = new string[(int)OpType.TOP][];
7731 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7732 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7733 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7734 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7735 names [(int) OpType.True] = new string [] { "true", "op_True" };
7736 names [(int) OpType.False] = new string [] { "false", "op_False" };
7737 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7738 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7739 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7740 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7741 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7742 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7743 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7744 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7745 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7746 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7747 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7748 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7749 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7750 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7751 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7752 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7753 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7754 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7755 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7756 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7759 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7760 int mod_flags, Parameters parameters,
7761 ToplevelBlock block, Attributes attrs, Location loc)
7762 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7763 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7765 OperatorType = type;
7769 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7771 if (a.Type == TypeManager.conditional_attribute_type) {
7772 Error_ConditionalAttributeIsNotValid ();
7776 base.ApplyAttributeBuilder (a, cb);
7779 public override bool Define ()
7781 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7782 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7783 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7787 if (!base.Define ())
7790 // imlicit and explicit operator of same types are not allowed
7791 if (OperatorType == OpType.Explicit)
7792 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7793 else if (OperatorType == OpType.Implicit)
7794 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7796 if (MemberType == TypeManager.void_type) {
7797 Report.Error (590, Location, "User-defined operators cannot return void");
7801 Type declaring_type = MethodData.DeclaringType;
7802 Type return_type = MemberType;
7803 Type first_arg_type = ParameterTypes [0];
7805 Type first_arg_type_unwrap = first_arg_type;
7806 if (TypeManager.IsNullableType (first_arg_type))
7807 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7809 Type return_type_unwrap = return_type;
7810 if (TypeManager.IsNullableType (return_type))
7811 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7814 // Rules for conversion operators
7816 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7817 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7818 Report.Error (555, Location,
7819 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7824 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7825 conv_type = first_arg_type;
7826 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7827 conv_type = return_type;
7829 Report.Error (556, Location,
7830 "User-defined conversion must convert to or from the enclosing type");
7835 // Because IsInterface and IsClass are not supported
7837 if (!TypeManager.IsGenericParameter (conv_type)) {
7838 if (conv_type.IsInterface) {
7839 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7840 GetSignatureForError ());
7844 if (conv_type.IsClass) {
7845 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7846 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7847 GetSignatureForError ());
7851 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7852 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7853 GetSignatureForError ());
7858 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7859 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7860 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");
7863 } else if (Parameters.Count == 1) {
7864 // Checks for Unary operators
7866 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7867 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7868 Report.Error (448, Location,
7869 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7872 if (first_arg_type != declaring_type) {
7874 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7879 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7880 Report.Error (562, Location,
7881 "The parameter type of a unary operator must be the containing type");
7885 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7886 if (return_type != TypeManager.bool_type){
7889 "The return type of operator True or False " +
7896 // Checks for Binary operators
7898 if (first_arg_type != declaring_type &&
7899 Parameters.Types [1] != declaring_type){
7902 "One of the parameters of a binary operator must " +
7903 "be the containing type");
7911 protected override bool DoDefine ()
7913 if (!base.DoDefine ())
7916 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7920 public override void Emit ()
7924 Parameters.ApplyAttributes (MethodBuilder);
7927 // abstract or extern methods have no bodies
7929 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7933 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7934 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7936 ec = CreateEmitContext (Parent, null);
7938 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7939 ec.EmitTopBlock (this, Block);
7942 source.CloseMethod ();
7947 // Operator cannot be override
7948 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7953 public static string GetName (OpType ot)
7955 return names [(int) ot] [0];
7958 public static string GetName (string metadata_name)
7960 for (int i = 0; i < names.Length; ++i) {
7961 if (names [i] [1] == metadata_name)
7962 return names [i] [0];
7967 public static string GetMetadataName (OpType ot)
7969 return names [(int) ot] [1];
7972 public static string GetMetadataName (string name)
7974 for (int i = 0; i < names.Length; ++i) {
7975 if (names [i] [0] == name)
7976 return names [i] [1];
7981 public OpType GetMatchingOperator ()
7983 switch (OperatorType) {
7984 case OpType.Equality:
7985 return OpType.Inequality;
7986 case OpType.Inequality:
7987 return OpType.Equality;
7989 return OpType.False;
7992 case OpType.GreaterThan:
7993 return OpType.LessThan;
7994 case OpType.LessThan:
7995 return OpType.GreaterThan;
7996 case OpType.GreaterThanOrEqual:
7997 return OpType.LessThanOrEqual;
7998 case OpType.LessThanOrEqual:
7999 return OpType.GreaterThanOrEqual;
8005 public override string GetSignatureForError ()
8007 StringBuilder sb = new StringBuilder ();
8008 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8009 sb.AppendFormat ("{0}.{1} operator {2}",
8010 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
8013 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8016 sb.Append (Parameters.GetSignatureForError ());
8017 return sb.ToString ();
8022 // This is used to compare method signatures
8024 struct MethodSignature {
8026 public Type RetType;
8027 public Type [] Parameters;
8030 /// This delegate is used to extract methods which have the
8031 /// same signature as the argument
8033 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8035 public MethodSignature (string name, Type ret_type, Type [] parameters)
8040 if (parameters == null)
8041 Parameters = Type.EmptyTypes;
8043 Parameters = parameters;
8046 public override string ToString ()
8049 if (Parameters.Length != 0){
8050 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8051 for (int i = 0; i < Parameters.Length; i++){
8052 sb.Append (Parameters [i]);
8053 if (i+1 < Parameters.Length)
8056 pars = sb.ToString ();
8059 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8062 public override int GetHashCode ()
8064 return Name.GetHashCode ();
8067 public override bool Equals (Object o)
8069 MethodSignature other = (MethodSignature) o;
8071 if (other.Name != Name)
8074 if (other.RetType != RetType)
8077 if (Parameters == null){
8078 if (other.Parameters == null)
8083 if (other.Parameters == null)
8086 int c = Parameters.Length;
8087 if (other.Parameters.Length != c)
8090 for (int i = 0; i < c; i++)
8091 if (other.Parameters [i] != Parameters [i])
8097 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8099 MethodSignature sig = (MethodSignature) filter_criteria;
8101 if (m.Name != sig.Name)
8105 MethodInfo mi = m as MethodInfo;
8106 PropertyInfo pi = m as PropertyInfo;
8109 ReturnType = mi.ReturnType;
8110 else if (pi != null)
8111 ReturnType = pi.PropertyType;
8116 // we use sig.RetType == null to mean `do not check the
8117 // method return value.
8119 if (sig.RetType != null) {
8120 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8126 args = TypeManager.GetParameterData (mi).Types;
8128 args = TypeManager.GetParameterData (pi).Types;
8129 Type [] sigp = sig.Parameters;
8131 if (args.Length != sigp.Length)
8134 for (int i = args.Length - 1; i >= 0; i--)
8135 if (!TypeManager.IsEqual (args [i], sigp [i]))