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 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 public void AddConstant (Const constant)
304 if (!AddMember (constant))
307 if (constants == null)
308 constants = new MemberCoreArrayList ();
310 constants.Add (constant);
313 public TypeContainer AddTypeContainer (TypeContainer tc)
315 if (!AddMemberType (tc))
319 types = new MemberCoreArrayList ();
325 public virtual TypeContainer AddPartial (TypeContainer next_part)
327 return AddPartial (next_part, next_part.Basename);
330 protected TypeContainer AddPartial (TypeContainer next_part, string name)
332 next_part.ModFlags |= Modifiers.PARTIAL;
333 TypeContainer tc = defined_names [name] as TypeContainer;
336 return AddTypeContainer (next_part);
338 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
339 Report.SymbolRelatedToPreviousError (tc);
340 Error_MissingPartialModifier (next_part);
343 if (tc.Kind != next_part.Kind) {
344 Report.SymbolRelatedToPreviousError (tc);
345 Report.Error (261, next_part.Location,
346 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
347 next_part.GetSignatureForError ());
350 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
351 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
352 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
353 Report.SymbolRelatedToPreviousError (tc);
354 Report.Error (262, next_part.Location,
355 "Partial declarations of `{0}' have conflicting accessibility modifiers",
356 next_part.GetSignatureForError ());
359 if (tc.partial_parts == null)
360 tc.partial_parts = new ArrayList (1);
362 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
363 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
364 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
365 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
366 tc.ModFlags |= next_part.ModFlags;
368 tc.ModFlags |= next_part.ModFlags;
371 if (next_part.attributes != null) {
372 if (tc.attributes == null)
373 tc.attributes = next_part.attributes;
375 tc.attributes.AddAttributes (next_part.attributes.Attrs);
378 next_part.PartialContainer = tc;
379 tc.partial_parts.Add (next_part);
383 public void AddDelegate (Delegate d)
385 if (!AddMemberType (d))
388 if (delegates == null)
389 delegates = new MemberCoreArrayList ();
394 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
396 if (ordered_explicit_member_list == null) {
397 ordered_explicit_member_list = new MemberCoreArrayList ();
398 ordered_member_list = new MemberCoreArrayList ();
402 ordered_explicit_member_list.Add (mc);
403 alist.Insert (0, mc);
406 ordered_member_list.Add (mc);
412 public void AddMethod (Method method)
414 MemberName mn = method.MemberName;
415 if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
419 methods = new MemberCoreArrayList ();
421 if (method.MemberName.Left != null)
422 AddMemberToList (method, methods, true);
424 AddMemberToList (method, methods, false);
428 // Do not use this method: use AddMethod.
430 // This is only used by iterators.
432 public void AppendMethod (Method method)
434 if (!AddMember (method))
438 methods = new MemberCoreArrayList ();
440 AddMemberToList (method, methods, false);
443 public void AddConstructor (Constructor c)
445 if (c.Name != MemberName.Name) {
446 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
449 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
450 if (!AddToContainer (c, is_static ?
451 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
454 if (is_static && c.Parameters.Empty){
455 if (default_static_constructor != null) {
456 Report.SymbolRelatedToPreviousError (default_static_constructor);
457 Report.Error (111, c.Location,
458 "A member `{0}' is already defined. Rename this member or use different parameter types",
459 c.GetSignatureForError ());
463 default_static_constructor = c;
465 if (c.Parameters.Empty)
466 default_constructor = c;
468 if (instance_constructors == null)
469 instance_constructors = new MemberCoreArrayList ();
471 instance_constructors.Add (c);
475 public bool AddField (FieldBase field)
477 if (!AddMember (field))
481 fields = new MemberCoreArrayList ();
485 if ((field.ModFlags & Modifiers.STATIC) != 0)
488 if (first_nonstatic_field == null) {
489 first_nonstatic_field = field;
493 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
494 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
495 Report.Warning (282, 3, field.Location,
496 "struct instance field `{0}' found in different declaration from instance field `{1}'",
497 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
502 public void AddProperty (Property prop)
504 if (!AddMember (prop) ||
505 !AddMember (prop.Get) || !AddMember (prop.Set))
508 if (properties == null)
509 properties = new MemberCoreArrayList ();
511 if (prop.MemberName.Left != null)
512 AddMemberToList (prop, properties, true);
514 AddMemberToList (prop, properties, false);
517 public void AddEvent (Event e)
522 if (e is EventProperty) {
523 if (!AddMember (e.Add))
526 if (!AddMember (e.Remove))
531 events = new MemberCoreArrayList ();
537 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
539 public void AddIndexer (Indexer i)
541 if (indexers == null)
542 indexers = new ArrayList ();
544 if (i.IsExplicitImpl)
545 AddMemberToList (i, indexers, true);
547 AddMemberToList (i, indexers, false);
550 public void AddOperator (Operator op)
555 if (operators == null)
556 operators = new OperatorArrayList (this);
561 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
563 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
565 if (compiler_generated == null)
566 compiler_generated = new ArrayList ();
568 compiler_generated.Add (c);
571 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
573 if (a.Type == TypeManager.default_member_type) {
574 if (Indexers != null) {
575 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
580 base.ApplyAttributeBuilder (a, cb);
583 public override AttributeTargets AttributeTargets {
585 throw new NotSupportedException ();
589 public ArrayList Types {
595 public MemberCoreArrayList Methods {
601 public ArrayList Constants {
607 public ArrayList CompilerGenerated {
609 return compiler_generated;
613 protected Type BaseType {
615 return TypeBuilder.BaseType;
619 public ArrayList Fields {
625 public ArrayList InstanceConstructors {
627 return instance_constructors;
631 public ArrayList Properties {
637 public ArrayList Events {
643 public ArrayList Indexers {
649 public ArrayList Operators {
655 public ArrayList Delegates {
661 protected override TypeAttributes TypeAttr {
663 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
667 public string IndexerName {
669 return indexers == null ? DefaultIndexerName : indexer_name;
673 public bool IsComImport {
675 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
678 return OptAttributes.Contains (TypeManager.comimport_attr_type);
682 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
684 if ((field.ModFlags & Modifiers.STATIC) != 0){
685 if (initialized_static_fields == null) {
686 PartialContainer.HasStaticFieldInitializer = true;
687 initialized_static_fields = new ArrayList (4);
690 initialized_static_fields.Add (expression);
692 if (initialized_fields == null)
693 initialized_fields = new ArrayList (4);
695 initialized_fields.Add (expression);
699 public void ResolveFieldInitializers (EmitContext ec)
701 // Field initializers are tricky for partial classes. They have to
702 // share same costructor (block) but they have they own resolve scope.
703 DeclSpace orig = ec.DeclContainer;
705 if (partial_parts != null) {
706 foreach (TypeContainer part in partial_parts) {
707 ec.DeclContainer = part;
708 part.DoResolveFieldInitializers (ec);
711 ec.DeclContainer = PartialContainer;
712 DoResolveFieldInitializers (ec);
713 ec.DeclContainer = orig;
716 void DoResolveFieldInitializers (EmitContext ec)
719 if (initialized_static_fields == null)
722 bool has_complex_initializer = false;
723 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
724 foreach (FieldInitializer fi in initialized_static_fields) {
725 fi.ResolveStatement (ec);
726 if (!fi.IsComplexInitializer)
729 has_complex_initializer = true;
732 // Need special check to not optimize code like this
733 // static int a = b = 5;
735 if (!has_complex_initializer && RootContext.Optimize) {
736 for (int i = 0; i < initialized_static_fields.Count; ++i) {
737 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
738 if (fi.IsDefaultInitializer) {
739 initialized_static_fields.RemoveAt (i);
749 if (initialized_fields == null)
752 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
753 for (int i = 0; i < initialized_fields.Count; ++i) {
754 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
755 fi.ResolveStatement (ec);
756 if (fi.IsDefaultInitializer && RootContext.Optimize) {
757 // Field is re-initialized to its default value => removed
758 initialized_fields.RemoveAt (i);
766 // Emits the instance field initializers
768 public bool EmitFieldInitializers (EmitContext ec)
770 if (partial_parts != null) {
771 foreach (TypeContainer part in partial_parts)
772 part.EmitFieldInitializers (ec);
778 fields = initialized_static_fields;
780 fields = initialized_fields;
786 foreach (FieldInitializer f in fields) {
787 f.EmitStatement (ec);
792 public override string DocComment {
804 public PendingImplementation PendingImplementations {
805 get { return pending; }
808 public override bool GetClsCompliantAttributeValue ()
810 if (PartialContainer != this)
811 return PartialContainer.GetClsCompliantAttributeValue ();
813 return base.GetClsCompliantAttributeValue ();
816 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
818 // FIXME: get rid of partial_parts and store lists of bases of each part here
819 // assumed, not verified: 'part' is in 'partial_parts'
820 ((TypeContainer) part).type_bases = bases;
823 TypeExpr[] GetNormalBases (out TypeExpr base_class)
826 if (type_bases == null)
829 int count = type_bases.Count;
832 if (Kind == Kind.Class){
833 TypeExpr name = ((Expression) type_bases [0]).ResolveAsBaseTerminal (this, false);
839 if (!name.IsInterface) {
840 // base_class could be a class, struct, enum, delegate.
841 // This is validated in GetClassBases.
847 TypeExpr [] ifaces = new TypeExpr [count-start];
849 for (i = start, j = 0; i < count; i++, j++){
850 TypeExpr resolved = ((Expression) type_bases [i]).ResolveAsBaseTerminal (this, false);
851 if (resolved == null) {
855 ifaces [j] = resolved;
858 return ifaces.Length == 0 ? null : ifaces;
862 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
864 ArrayList ifaces = new ArrayList (0);
865 if (iface_exprs != null)
866 ifaces.AddRange (iface_exprs);
868 foreach (TypeContainer part in partial_parts) {
869 TypeExpr new_base_class;
870 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
871 if (new_base_class != TypeManager.system_object_expr) {
872 if (base_class == TypeManager.system_object_expr)
873 base_class = new_base_class;
875 if (new_base_class != null && !new_base_class.Equals (base_class)) {
876 Report.SymbolRelatedToPreviousError (base_class.Location, "");
877 Report.Error (263, part.Location,
878 "Partial declarations of `{0}' must not specify different base classes",
879 part.GetSignatureForError ());
886 if (new_ifaces == null)
889 foreach (TypeExpr iface in new_ifaces) {
890 if (ifaces.Contains (iface))
897 if (ifaces.Count == 0)
900 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
904 /// This function computes the Base class and also the
905 /// list of interfaces that the class or struct @c implements.
907 /// The return value is an array (might be null) of
908 /// interfaces implemented (as Types).
910 /// The @base_class argument is set to the base object or null
911 /// if this is `System.Object'.
913 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
915 TypeExpr[] ifaces = GetNormalBases (out base_class);
920 int count = ifaces.Length;
922 for (int i = 0; i < count; i++) {
923 TypeExpr iface = (TypeExpr) ifaces [i];
925 if (!iface.IsInterface) {
926 if (Kind != Kind.Class) {
927 // TODO: location of symbol related ....
928 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
930 else if (base_class != null)
931 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
932 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
934 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
935 GetSignatureForError (), iface.GetSignatureForError ());
940 for (int x = 0; x < i; x++) {
941 if (iface.Equals (ifaces [x])) {
942 Report.Error (528, Location,
943 "`{0}' is already listed in " +
944 "interface list", iface.GetSignatureForError ());
949 if ((Kind == Kind.Interface) &&
950 !iface.AsAccessible (this)) {
951 Report.Error (61, Location,
952 "Inconsistent accessibility: base " +
953 "interface `{0}' is less accessible " +
954 "than interface `{1}'", iface.GetSignatureForError (),
962 bool CheckGenericInterfaces (Type[] ifaces)
965 ArrayList already_checked = new ArrayList ();
967 for (int i = 0; i < ifaces.Length; i++) {
968 Type iface = ifaces [i];
969 foreach (Type t in already_checked) {
973 Type[] inferred = new Type [CountTypeParameters];
974 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
977 Report.Error (695, Location,
978 "`{0}' cannot implement both `{1}' and `{2}' " +
979 "because they may unify for some type parameter substitutions",
980 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
981 TypeManager.CSharpName (t));
985 already_checked.Add (iface);
994 protected void Error_TypeInListIsNotInterface (Location loc, string type)
996 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
999 bool CreateTypeBuilder ()
1002 Type default_parent = null;
1003 if (Kind == Kind.Struct)
1004 default_parent = TypeManager.value_type;
1005 else if (Kind == Kind.Enum)
1006 default_parent = TypeManager.enum_type;
1009 if (TypeManager.NamespaceClash (Name, Location)) {
1013 ModuleBuilder builder = CodeGen.Module.Builder;
1014 TypeBuilder = builder.DefineType (
1015 Name, TypeAttr, default_parent, null);
1017 TypeBuilder builder = Parent.TypeBuilder;
1019 TypeBuilder = builder.DefineNestedType (
1020 Basename, TypeAttr, default_parent, null);
1022 } catch (ArgumentException) {
1023 Report.RuntimeMissingSupport (Location, "static classes");
1027 TypeManager.AddUserType (this);
1031 string[] param_names = new string [TypeParameters.Length];
1032 for (int i = 0; i < TypeParameters.Length; i++)
1033 param_names [i] = TypeParameters [i].Name;
1035 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
1037 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1038 for (int i = offset; i < gen_params.Length; i++)
1039 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1046 bool DefineBaseTypes ()
1048 iface_exprs = GetClassBases (out base_type);
1049 if (partial_parts != null) {
1050 iface_exprs = GetNormalPartialBases (ref base_type);
1054 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1055 // which in turn should have called DefineType()s on base types if necessary.
1057 // None of the code below should trigger DefineType()s on classes that we depend on.
1058 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1060 // Let's do it as soon as possible, since code below can call DefineType() on classes
1061 // that depend on us to be populated before they are.
1063 if (!(this is CompilerGeneratedClass))
1064 RootContext.RegisterOrder (this);
1066 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1067 Report.Error (698, base_type.Location,
1068 "A generic type cannot derive from `{0}' because it is an attribute class",
1069 base_type.GetSignatureForError ());
1073 if (!CheckRecursiveDefinition (this))
1076 if (base_type != null && base_type.Type != null) {
1077 TypeBuilder.SetParent (base_type.Type);
1079 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1080 if (obsolete_attr != null && !IsInObsoleteScope)
1081 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1084 // add interfaces that were not added at type creation
1085 if (iface_exprs != null) {
1086 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1090 foreach (Type itype in ifaces)
1091 TypeBuilder.AddInterfaceImplementation (itype);
1093 foreach (TypeExpr ie in iface_exprs) {
1094 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1095 if ((oa != null) && !IsInObsoleteScope)
1096 AttributeTester.Report_ObsoleteMessage (
1097 oa, ie.GetSignatureForError (), Location);
1100 if (!CheckGenericInterfaces (ifaces))
1103 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1110 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1112 public TypeBuilder CreateType ()
1114 if (TypeBuilder != null)
1120 if (!CreateTypeBuilder ()) {
1125 if (partial_parts != null) {
1126 foreach (TypeContainer part in partial_parts)
1127 part.TypeBuilder = TypeBuilder;
1130 if (Types != null) {
1131 foreach (TypeContainer tc in Types) {
1132 if (tc.CreateType () == null) {
1144 public override TypeBuilder DefineType ()
1151 type_defined = true;
1153 if (CreateType () == null) {
1158 if (!DefineBaseTypes ()) {
1163 if (!(this is CompilerGeneratedClass)) {
1164 if (!ResolveMembers ()) {
1170 if (!DefineNestedTypes ()) {
1178 public bool ResolveMembers ()
1180 if (members_resolved)
1181 return members_resolved_ok;
1183 members_resolved_ok = DoResolveMembers ();
1184 members_resolved = true;
1186 return members_resolved_ok;
1189 protected virtual bool DoResolveMembers ()
1191 if (methods != null) {
1192 foreach (Method method in methods) {
1193 if (!method.ResolveMembers ())
1198 if (instance_constructors != null) {
1199 foreach (Constructor c in instance_constructors) {
1200 if (!c.ResolveMembers ())
1205 if (default_static_constructor != null) {
1206 if (!default_static_constructor.ResolveMembers ())
1210 if (operators != null) {
1211 foreach (Operator o in operators) {
1212 if (!o.ResolveMembers ())
1217 if (properties != null) {
1218 foreach (PropertyBase p in properties) {
1219 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1221 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1226 if (indexers != null) {
1227 foreach (PropertyBase p in indexers) {
1228 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1230 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1235 if (events != null) {
1236 foreach (Event e in events) {
1237 if (!e.Add.ResolveMembers ())
1239 if (!e.Remove.ResolveMembers ())
1244 if (compiler_generated != null) {
1245 foreach (CompilerGeneratedClass c in compiler_generated) {
1246 if (c.DefineType () == null)
1254 public override void SetParameterInfo (ArrayList constraints_list)
1256 base.SetParameterInfo (constraints_list);
1258 if (!is_generic || PartialContainer == this)
1261 TypeParameter[] tc_names = PartialContainer.TypeParameters;
1262 for (int i = 0; i < tc_names.Length; ++i) {
1263 if (tc_names [i].Name != type_params [i].Name) {
1264 Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1265 Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1266 GetSignatureForError ());
1272 void UpdateTypeParameterConstraints (TypeContainer part)
1274 TypeParameter[] current_params = CurrentTypeParameters;
1275 for (int i = 0; i < current_params.Length; i++) {
1276 Constraints c = part.CurrentTypeParameters [i].Constraints;
1280 if (current_params [i].UpdateConstraints (part, c))
1283 Report.SymbolRelatedToPreviousError (Location, "");
1284 Report.Error (265, part.Location,
1285 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1286 GetSignatureForError (), current_params [i].GetSignatureForError ());
1290 public bool ResolveType ()
1292 if (!DoResolveType ())
1295 if (compiler_generated != null) {
1296 foreach (CompilerGeneratedClass c in compiler_generated)
1297 if (!c.ResolveType ())
1304 protected virtual bool DoResolveType ()
1306 if ((base_type != null) &&
1307 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1315 if (PartialContainer != this)
1316 throw new InternalErrorException ();
1318 TypeExpr current_type = null;
1320 foreach (TypeParameter type_param in CurrentTypeParameters) {
1321 if (!type_param.Resolve (this)) {
1327 if (partial_parts != null && is_generic) {
1328 foreach (TypeContainer part in partial_parts)
1329 UpdateTypeParameterConstraints (part);
1332 foreach (TypeParameter type_param in TypeParameters) {
1333 if (!type_param.DefineType (this)) {
1339 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1341 foreach (TypeParameter type_param in TypeParameters)
1342 if (!type_param.CheckDependencies ()) {
1347 if (current_type != null) {
1348 current_type = current_type.ResolveAsTypeTerminal (this, false);
1349 if (current_type == null) {
1354 CurrentType = current_type.Type;
1360 protected virtual bool DefineNestedTypes ()
1362 if (Types != null) {
1363 foreach (TypeContainer tc in Types)
1364 if (tc.DefineType () == null)
1368 if (Delegates != null) {
1369 foreach (Delegate d in Delegates)
1370 if (d.DefineType () == null)
1377 TypeContainer InTransit;
1379 protected bool CheckRecursiveDefinition (TypeContainer tc)
1381 if (InTransit != null) {
1382 Report.SymbolRelatedToPreviousError (this);
1383 if (this is Interface)
1385 529, tc.Location, "Inherited interface `{0}' causes a " +
1386 "cycle in the interface hierarchy of `{1}'",
1387 GetSignatureForError (), tc.GetSignatureForError ());
1390 146, tc.Location, "Circular base class dependency " +
1391 "involving `{0}' and `{1}'",
1392 tc.GetSignatureForError (), GetSignatureForError ());
1398 if (base_type != null && base_type.Type != null) {
1399 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1400 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1401 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1405 if (iface_exprs != null) {
1406 foreach (TypeExpr iface in iface_exprs) {
1407 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1408 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1409 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1414 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1421 public static void Error_KeywordNotAllowed (Location loc)
1423 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1427 /// Populates our TypeBuilder with fields and methods
1429 public override bool DefineMembers ()
1431 if (members_defined)
1432 return members_defined_ok;
1434 if (!base.DefineMembers ())
1437 members_defined_ok = DoDefineMembers ();
1438 members_defined = true;
1440 return members_defined_ok;
1443 protected virtual bool DoDefineMembers ()
1445 if (iface_exprs != null) {
1446 foreach (TypeExpr iface in iface_exprs) {
1447 ConstructedType ct = iface as ConstructedType;
1448 if ((ct != null) && !ct.CheckConstraints (this))
1453 if (base_type != null) {
1454 ConstructedType ct = base_type as ConstructedType;
1455 if ((ct != null) && !ct.CheckConstraints (this))
1458 member_cache = new MemberCache (base_type.Type, this);
1459 } else if (Kind == Kind.Interface) {
1460 member_cache = new MemberCache (null, this);
1461 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1462 for (int i = 0; i < ifaces.Length; ++i)
1463 member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1465 member_cache = new MemberCache (null, this);
1469 foreach (TypeContainer tc in types)
1470 member_cache.AddNestedType (tc);
1472 if (delegates != null)
1473 foreach (Delegate d in delegates)
1474 member_cache.AddNestedType (d);
1476 if (partial_parts != null) {
1477 foreach (TypeContainer part in partial_parts)
1478 part.member_cache = member_cache;
1482 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1483 if (conflict_symbol == null) {
1484 if ((ModFlags & Modifiers.NEW) != 0)
1485 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1487 if ((ModFlags & Modifiers.NEW) == 0) {
1488 Report.SymbolRelatedToPreviousError (conflict_symbol);
1489 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1490 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1495 DefineContainerMembers (constants);
1496 DefineContainerMembers (fields);
1498 if (Kind == Kind.Struct || Kind == Kind.Class) {
1499 pending = PendingImplementation.GetPendingImplementations (this);
1503 // Constructors are not in the defined_names array
1505 DefineContainerMembers (instance_constructors);
1507 DefineContainerMembers (events);
1508 DefineContainerMembers (ordered_explicit_member_list);
1509 DefineContainerMembers (ordered_member_list);
1511 DefineContainerMembers (operators);
1512 DefineContainerMembers (delegates);
1514 ComputeIndexerName();
1515 CheckEqualsAndGetHashCode();
1517 if (CurrentType != null) {
1518 GenericType = CurrentType;
1523 // FIXME: This hack is needed because member cache does not work
1524 // with generic types, we rely on runtime to inflate dynamic types.
1525 // TODO: This hack requires member cache refactoring to be removed
1527 if (TypeBuilder.IsGenericType)
1528 member_cache = new MemberCache (this);
1534 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1537 mcal.DefineContainerMembers ();
1540 protected virtual void ComputeIndexerName ()
1542 if (indexers == null)
1545 string class_indexer_name = null;
1548 // If there's both an explicit and an implicit interface implementation, the
1549 // explicit one actually implements the interface while the other one is just
1550 // a normal indexer. See bug #37714.
1553 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1554 foreach (Indexer i in indexers) {
1555 if (i.InterfaceType != null) {
1556 if (seen_normal_indexers)
1557 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1561 seen_normal_indexers = true;
1563 if (class_indexer_name == null) {
1564 class_indexer_name = i.ShortName;
1568 if (i.ShortName != class_indexer_name)
1569 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");
1572 if (class_indexer_name != null)
1573 indexer_name = class_indexer_name;
1576 protected virtual void EmitIndexerName ()
1578 if (!seen_normal_indexers)
1581 if (TypeManager.default_member_ctor == null) {
1582 if (TypeManager.default_member_type == null) {
1583 TypeManager.default_member_type = TypeManager.CoreLookupType (
1584 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1586 if (TypeManager.default_member_type == null)
1590 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1591 TypeManager.default_member_type, Location, TypeManager.string_type);
1593 if (TypeManager.default_member_ctor == null)
1597 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1598 TypeBuilder.SetCustomAttribute (cb);
1601 protected virtual void CheckEqualsAndGetHashCode ()
1603 if (methods == null)
1606 if (HasEquals && !HasGetHashCode) {
1607 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1611 public override bool Define ()
1613 CheckProtectedModifier ();
1615 if (compiler_generated != null) {
1616 foreach (CompilerGeneratedClass c in compiler_generated) {
1625 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1627 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1631 /// This function is based by a delegate to the FindMembers routine
1633 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1639 /// This filter is used by FindMembers, and we just keep
1640 /// a global for the filter to `AlwaysAccept'
1642 static MemberFilter accepting_filter;
1645 static TypeContainer ()
1647 accepting_filter = new MemberFilter (AlwaysAccept);
1650 public MethodInfo[] GetMethods ()
1652 ArrayList members = new ArrayList ();
1656 if (methods != null) {
1657 int len = methods.Count;
1658 for (int i = 0; i < len; i++) {
1659 Method m = (Method) methods [i];
1661 members.Add (m.MethodBuilder);
1665 if (operators != null) {
1666 int len = operators.Count;
1667 for (int i = 0; i < len; i++) {
1668 Operator o = (Operator) operators [i];
1670 members.Add (o.MethodBuilder);
1674 if (properties != null) {
1675 int len = properties.Count;
1676 for (int i = 0; i < len; i++) {
1677 Property p = (Property) properties [i];
1679 if (p.GetBuilder != null)
1680 members.Add (p.GetBuilder);
1681 if (p.SetBuilder != null)
1682 members.Add (p.SetBuilder);
1686 if (indexers != null) {
1687 int len = indexers.Count;
1688 for (int i = 0; i < len; i++) {
1689 Indexer ix = (Indexer) indexers [i];
1691 if (ix.GetBuilder != null)
1692 members.Add (ix.GetBuilder);
1693 if (ix.SetBuilder != null)
1694 members.Add (ix.SetBuilder);
1698 if (events != null) {
1699 int len = events.Count;
1700 for (int i = 0; i < len; i++) {
1701 Event e = (Event) events [i];
1703 if (e.AddBuilder != null)
1704 members.Add (e.AddBuilder);
1705 if (e.RemoveBuilder != null)
1706 members.Add (e.RemoveBuilder);
1710 MethodInfo[] retMethods = new MethodInfo [members.Count];
1711 members.CopyTo (retMethods, 0);
1715 // Indicated whether container has StructLayout attribute set Explicit
1716 public bool HasExplicitLayout {
1717 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1718 set { caching_flags |= Flags.HasExplicitLayout; }
1722 // Return the nested type with name @name. Ensures that the nested type
1723 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1725 public Type FindNestedType (string name)
1727 if (PartialContainer != this)
1728 throw new InternalErrorException ("should not happen");
1730 ArrayList [] lists = { types, delegates };
1732 for (int j = 0; j < lists.Length; ++j) {
1733 ArrayList list = lists [j];
1737 int len = list.Count;
1738 for (int i = 0; i < len; ++i) {
1739 DeclSpace ds = (DeclSpace) list [i];
1740 if (ds.Basename == name) {
1741 return ds.DefineType ();
1749 private void FindMembers_NestedTypes (int modflags,
1750 BindingFlags bf, MemberFilter filter, object criteria,
1751 ref ArrayList members)
1753 ArrayList [] lists = { types, delegates };
1755 for (int j = 0; j < lists.Length; ++j) {
1756 ArrayList list = lists [j];
1760 int len = list.Count;
1761 for (int i = 0; i < len; i++) {
1762 DeclSpace ds = (DeclSpace) list [i];
1764 if ((ds.ModFlags & modflags) == 0)
1767 TypeBuilder tb = ds.TypeBuilder;
1769 if (!(criteria is string) || ds.Basename.Equals (criteria))
1770 tb = ds.DefineType ();
1773 if (tb != null && (filter (tb, criteria) == true)) {
1774 if (members == null)
1775 members = new ArrayList ();
1784 /// This method returns the members of this type just like Type.FindMembers would
1785 /// Only, we need to use this for types which are _being_ defined because MS'
1786 /// implementation can't take care of that.
1789 // FIXME: return an empty static array instead of null, that cleans up
1790 // some code and is consistent with some coding conventions I just found
1794 // Notice that in various cases we check if our field is non-null,
1795 // something that would normally mean that there was a bug elsewhere.
1797 // The problem happens while we are defining p-invoke methods, as those
1798 // will trigger a FindMembers, but this happens before things are defined
1800 // Since the whole process is a no-op, it is fine to check for null here.
1802 // TODO: This approach will be one day completely removed, it's already
1803 // used at few places only
1806 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1807 MemberFilter filter, object criteria)
1809 ArrayList members = null;
1812 if ((bf & BindingFlags.Public) != 0)
1813 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1815 if ((bf & BindingFlags.NonPublic) != 0)
1816 modflags |= Modifiers.PRIVATE;
1818 int static_mask = 0, static_flags = 0;
1819 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1820 case BindingFlags.Static:
1821 static_mask = static_flags = Modifiers.STATIC;
1824 case BindingFlags.Instance:
1825 static_mask = Modifiers.STATIC;
1830 static_mask = static_flags = 0;
1834 Timer.StartTimer (TimerType.TcFindMembers);
1837 filter = accepting_filter;
1839 if ((mt & MemberTypes.Field) != 0) {
1840 if (fields != null) {
1841 int len = fields.Count;
1842 for (int i = 0; i < len; i++) {
1843 FieldBase f = (FieldBase) fields [i];
1845 if ((f.ModFlags & modflags) == 0)
1847 if ((f.ModFlags & static_mask) != static_flags)
1850 FieldBuilder fb = f.FieldBuilder;
1851 if (fb != null && filter (fb, criteria) == true) {
1852 if (members == null)
1853 members = new ArrayList ();
1860 if (constants != null) {
1861 int len = constants.Count;
1862 for (int i = 0; i < len; i++) {
1863 Const con = (Const) constants [i];
1865 if ((con.ModFlags & modflags) == 0)
1867 if ((con.ModFlags & static_mask) != static_flags)
1870 FieldBuilder fb = con.FieldBuilder;
1873 fb = con.FieldBuilder;
1875 if (fb != null && filter (fb, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1885 if ((mt & MemberTypes.Method) != 0) {
1886 if (methods != null) {
1887 int len = methods.Count;
1888 for (int i = 0; i < len; i++) {
1889 Method m = (Method) methods [i];
1891 if ((m.ModFlags & modflags) == 0)
1893 if ((m.ModFlags & static_mask) != static_flags)
1896 MethodBuilder mb = m.MethodBuilder;
1898 if (mb != null && filter (mb, criteria) == true) {
1899 if (members == null)
1900 members = new ArrayList ();
1907 if (operators != null) {
1908 int len = operators.Count;
1909 for (int i = 0; i < len; i++) {
1910 Operator o = (Operator) operators [i];
1912 if ((o.ModFlags & modflags) == 0)
1914 if ((o.ModFlags & static_mask) != static_flags)
1917 MethodBuilder ob = o.MethodBuilder;
1918 if (ob != null && filter (ob, criteria) == true) {
1919 if (members == null)
1920 members = new ArrayList ();
1927 if (events != null) {
1928 foreach (Event e in events) {
1929 if ((e.ModFlags & modflags) == 0)
1931 if ((e.ModFlags & static_mask) != static_flags)
1934 MethodBuilder b = e.AddBuilder;
1935 if (b != null && filter (b, criteria)) {
1936 if (members == null)
1937 members = new ArrayList (4);
1942 b = e.RemoveBuilder;
1943 if (b != null && filter (b, criteria)) {
1944 if (members == null)
1945 members = new ArrayList (4);
1952 if (properties != null) {
1953 int len = properties.Count;
1954 for (int i = 0; i < len; i++) {
1955 Property p = (Property) properties [i];
1957 if ((p.ModFlags & modflags) == 0)
1959 if ((p.ModFlags & static_mask) != static_flags)
1965 if (b != null && filter (b, criteria) == true) {
1966 if (members == null)
1967 members = new ArrayList ();
1973 if (b != null && filter (b, criteria) == true) {
1974 if (members == null)
1975 members = new ArrayList ();
1982 if (indexers != null) {
1983 int len = indexers.Count;
1984 for (int i = 0; i < len; i++) {
1985 Indexer ix = (Indexer) indexers [i];
1987 if ((ix.ModFlags & modflags) == 0)
1989 if ((ix.ModFlags & static_mask) != static_flags)
1995 if (b != null && filter (b, criteria) == true) {
1996 if (members == null)
1997 members = new ArrayList ();
2003 if (b != null && filter (b, criteria) == true) {
2004 if (members == null)
2005 members = new ArrayList ();
2013 if ((mt & MemberTypes.Event) != 0) {
2014 if (events != null) {
2015 int len = events.Count;
2016 for (int i = 0; i < len; i++) {
2017 Event e = (Event) events [i];
2019 if ((e.ModFlags & modflags) == 0)
2021 if ((e.ModFlags & static_mask) != static_flags)
2024 MemberInfo eb = e.EventBuilder;
2025 if (eb != null && filter (eb, criteria) == true) {
2026 if (members == null)
2027 members = new ArrayList ();
2029 members.Add (e.EventBuilder);
2035 if ((mt & MemberTypes.Property) != 0){
2036 if (properties != null) {
2037 int len = properties.Count;
2038 for (int i = 0; i < len; i++) {
2039 Property p = (Property) properties [i];
2041 if ((p.ModFlags & modflags) == 0)
2043 if ((p.ModFlags & static_mask) != static_flags)
2046 MemberInfo pb = p.PropertyBuilder;
2047 if (pb != null && filter (pb, criteria) == true) {
2048 if (members == null)
2049 members = new ArrayList ();
2051 members.Add (p.PropertyBuilder);
2056 if (indexers != null) {
2057 int len = indexers.Count;
2058 for (int i = 0; i < len; i++) {
2059 Indexer ix = (Indexer) indexers [i];
2061 if ((ix.ModFlags & modflags) == 0)
2063 if ((ix.ModFlags & static_mask) != static_flags)
2066 MemberInfo ib = ix.PropertyBuilder;
2067 if (ib != null && filter (ib, criteria) == true) {
2068 if (members == null)
2069 members = new ArrayList ();
2071 members.Add (ix.PropertyBuilder);
2077 if ((mt & MemberTypes.NestedType) != 0)
2078 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2080 if ((mt & MemberTypes.Constructor) != 0){
2081 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2082 int len = instance_constructors.Count;
2083 for (int i = 0; i < len; i++) {
2084 Constructor c = (Constructor) instance_constructors [i];
2086 ConstructorBuilder cb = c.ConstructorBuilder;
2087 if (cb != null && filter (cb, criteria) == true) {
2088 if (members == null)
2089 members = new ArrayList ();
2096 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2097 ConstructorBuilder cb =
2098 default_static_constructor.ConstructorBuilder;
2100 if (cb != null && filter (cb, criteria) == true) {
2101 if (members == null)
2102 members = new ArrayList ();
2110 // Lookup members in base if requested.
2112 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2113 if (TypeBuilder.BaseType != null) {
2114 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2115 if (list.Count > 0) {
2116 if (members == null)
2117 members = new ArrayList ();
2119 members.AddRange (list);
2124 Timer.StopTimer (TimerType.TcFindMembers);
2126 if (members == null)
2127 return MemberList.Empty;
2129 return new MemberList (members);
2132 public override MemberCache MemberCache {
2134 return member_cache;
2138 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2139 MemberFilter filter, object criteria)
2141 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2144 return ds.FindMembers (mt, bf, filter, criteria);
2146 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2150 /// Emits the values for the constants
2152 public void EmitConstants ()
2154 if (constants != null)
2155 foreach (Const con in constants)
2160 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2165 foreach (MemberCore mc in al) {
2166 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2169 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2170 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2175 public virtual void VerifyMembers ()
2178 // Check for internal or private fields that were never assigned
2180 if (Report.WarningLevel >= 3) {
2181 CheckMemberUsage (properties, "property");
2182 CheckMemberUsage (methods, "method");
2183 CheckMemberUsage (constants, "constant");
2185 if (fields != null){
2186 bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2187 foreach (FieldBase f in fields) {
2188 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2189 if (is_type_exposed)
2192 f.SetMemberIsUsed ();
2196 if ((f.caching_flags & Flags.IsAssigned) == 0)
2197 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2200 const int error_code = 414;
2202 const int error_code = 169;
2204 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2205 f.GetSignatureForError ());
2211 // Only report 649 on level 4
2213 if (Report.WarningLevel < 4)
2216 if ((f.caching_flags & Flags.IsAssigned) != 0)
2219 Constant c = New.Constantify (f.MemberType);
2220 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2221 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2227 // TODO: move to ClassOrStruct
2228 void EmitConstructors ()
2230 if (instance_constructors == null)
2233 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2234 bool has_compliant_args = false;
2236 foreach (Constructor c in instance_constructors) {
2240 catch (Exception e) {
2241 throw new InternalErrorException (c, e);
2244 if (has_compliant_args)
2247 has_compliant_args = c.HasCompliantArgs;
2249 if (!has_compliant_args)
2250 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2252 foreach (Constructor c in instance_constructors) {
2256 catch (Exception e) {
2257 throw new InternalErrorException (c, e);
2264 /// Emits the code, this step is performed after all
2265 /// the types, enumerations, constructors
2267 public virtual void EmitType ()
2269 if (OptAttributes != null)
2270 OptAttributes.Emit ();
2273 // Structs with no fields need to have at least one byte.
2274 // The right thing would be to set the PackingSize in a DefineType
2275 // but there are no functions that allow interfaces *and* the size to
2279 if (Kind == Kind.Struct && first_nonstatic_field == null){
2280 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2281 FieldAttributes.Private);
2283 if (HasExplicitLayout){
2284 object [] ctor_args = new object [] { 0 };
2286 if (TypeManager.field_offset_attribute_ctor == null) {
2288 if (TypeManager.field_offset_attribute_type == null) {
2289 TypeManager.field_offset_attribute_type = TypeManager.CoreLookupType (
2290 "System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, true);
2293 TypeManager.field_offset_attribute_ctor = TypeManager.GetPredefinedConstructor (
2294 TypeManager.field_offset_attribute_type, Location, TypeManager.int32_type);
2297 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2298 TypeManager.field_offset_attribute_ctor, ctor_args);
2299 fb.SetCustomAttribute (cba);
2305 EmitConstructors ();
2307 // Can not continue if constants are broken
2309 if (Report.Errors > 0)
2312 if (default_static_constructor != null)
2313 default_static_constructor.Emit ();
2315 if (methods != null){
2316 for (int i = 0; i < methods.Count; ++i)
2317 ((Method)methods[i]).Emit ();
2320 if (operators != null)
2321 foreach (Operator o in operators)
2324 if (properties != null)
2325 foreach (Property p in properties)
2328 if (indexers != null) {
2329 foreach (Indexer indx in indexers)
2335 foreach (FieldBase f in fields)
2338 if (events != null){
2339 foreach (Event e in Events)
2343 if (delegates != null) {
2344 foreach (Delegate d in Delegates) {
2349 if (pending != null)
2350 if (pending.VerifyPendingMethods ())
2353 if (Report.Errors > 0)
2356 if (compiler_generated != null) {
2357 foreach (CompilerGeneratedClass c in compiler_generated) {
2358 if (!c.DefineMembers ())
2359 throw new InternalErrorException ();
2361 foreach (CompilerGeneratedClass c in compiler_generated)
2366 public override void CloseType ()
2368 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2372 caching_flags |= Flags.CloseTypeCreated;
2373 TypeBuilder.CreateType ();
2374 } catch (TypeLoadException){
2376 // This is fine, the code still created the type
2378 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2379 // Console.WriteLine (e.Message);
2380 } catch (Exception e) {
2381 throw new InternalErrorException (this, e);
2385 foreach (TypeContainer tc in Types)
2386 if (tc.Kind == Kind.Struct)
2389 foreach (TypeContainer tc in Types)
2390 if (tc.Kind != Kind.Struct)
2394 if (Delegates != null)
2395 foreach (Delegate d in Delegates)
2398 if (CompilerGenerated != null)
2399 foreach (CompilerGeneratedClass c in CompilerGenerated)
2406 initialized_fields = null;
2407 initialized_static_fields = null;
2409 ordered_explicit_member_list = null;
2410 ordered_member_list = null;
2415 compiler_generated = null;
2416 default_constructor = null;
2417 default_static_constructor = null;
2419 OptAttributes = null;
2422 member_cache = null;
2426 // Performs the validation on a Method's modifiers (properties have
2427 // the same properties).
2429 public bool MethodModifiersValid (MemberCore mc)
2431 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2432 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2433 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2435 int flags = mc.ModFlags;
2438 // At most one of static, virtual or override
2440 if ((flags & Modifiers.STATIC) != 0){
2441 if ((flags & vao) != 0){
2442 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2443 mc.GetSignatureForError ());
2448 if (Kind == Kind.Struct){
2449 if ((flags & va) != 0){
2450 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2455 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2456 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2457 mc.GetSignatureForError ());
2462 // If the declaration includes the abstract modifier, then the
2463 // declaration does not include static, virtual or extern
2465 if ((flags & Modifiers.ABSTRACT) != 0){
2466 if ((flags & Modifiers.EXTERN) != 0){
2468 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2472 if ((flags & Modifiers.SEALED) != 0) {
2473 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2477 if ((flags & Modifiers.VIRTUAL) != 0){
2478 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2482 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2483 Report.SymbolRelatedToPreviousError (this);
2484 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2485 mc.GetSignatureForError (), GetSignatureForError ());
2490 if ((flags & Modifiers.PRIVATE) != 0){
2491 if ((flags & vao) != 0){
2492 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2497 if ((flags & Modifiers.SEALED) != 0){
2498 if ((flags & Modifiers.OVERRIDE) == 0){
2499 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2507 public Constructor DefaultStaticConstructor {
2508 get { return default_static_constructor; }
2511 protected override bool VerifyClsCompliance ()
2513 if (!base.VerifyClsCompliance ())
2518 Type base_type = TypeBuilder.BaseType;
2519 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2520 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2527 /// Checks whether container name is CLS Compliant
2529 void VerifyClsName ()
2531 Hashtable base_members = base_cache == null ?
2533 base_cache.GetPublicMembers ();
2534 Hashtable this_members = new Hashtable ();
2536 foreach (DictionaryEntry entry in defined_names) {
2537 MemberCore mc = (MemberCore)entry.Value;
2538 if (!mc.IsClsComplianceRequired ())
2541 string name = (string) entry.Key;
2542 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2544 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2545 object found = base_members [lcase];
2546 if (found == null) {
2547 found = this_members [lcase];
2548 if (found == null) {
2549 this_members.Add (lcase, mc);
2554 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2557 if (found is MemberInfo) {
2558 if (basename == ((MemberInfo) found).Name)
2560 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2562 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2565 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2567 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2574 /// Performs checks for an explicit interface implementation. First it
2575 /// checks whether the `interface_type' is a base inteface implementation.
2576 /// Then it checks whether `name' exists in the interface type.
2578 public bool VerifyImplements (InterfaceMemberBase mb)
2580 if (ifaces != null) {
2581 foreach (Type t in ifaces){
2582 if (TypeManager.IsEqual (t, mb.InterfaceType))
2587 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2588 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2589 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2593 public override Type LookupAnyGeneric (string typeName)
2595 if (types != null) {
2596 foreach (TypeContainer tc in types) {
2600 int pos = tc.Basename.LastIndexOf ('`');
2601 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2602 return tc.TypeBuilder;
2606 return base.LookupAnyGeneric (typeName);
2609 public void Mark_HasEquals ()
2611 cached_method |= CachedMethods.Equals;
2614 public void Mark_HasGetHashCode ()
2616 cached_method |= CachedMethods.GetHashCode;
2620 /// Method container contains Equals method
2622 public bool HasEquals {
2624 return (cached_method & CachedMethods.Equals) != 0;
2629 /// Method container contains GetHashCode method
2631 public bool HasGetHashCode {
2633 return (cached_method & CachedMethods.GetHashCode) != 0;
2637 public bool HasStaticFieldInitializer {
2639 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2643 cached_method |= CachedMethods.HasStaticFieldInitializer;
2645 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2653 string IMemberContainer.Name {
2659 Type IMemberContainer.Type {
2665 bool IMemberContainer.IsInterface {
2667 return Kind == Kind.Interface;
2671 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2673 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2675 if (GenericType != null)
2676 return TypeManager.FindMembers (GenericType, mt, new_bf,
2679 return FindMembers (mt, new_bf, null, null);
2683 // Generates xml doc comments (if any), and if required,
2684 // handle warning report.
2686 internal override void GenerateDocComment (DeclSpace ds)
2688 DocUtil.GenerateTypeDocComment (this, ds);
2691 public override string DocCommentHeader {
2692 get { return "T:"; }
2695 public MemberCache BaseCache {
2697 if (base_cache != null)
2699 if (TypeBuilder.BaseType != null)
2700 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2701 if (TypeBuilder.IsInterface)
2702 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2708 public abstract class ClassOrStruct : TypeContainer {
2709 ListDictionary declarative_security;
2711 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2712 MemberName name, Attributes attrs, Kind kind)
2713 : base (ns, parent, name, attrs, kind)
2717 protected override bool AddToContainer (MemberCore symbol, string name)
2719 if (name == MemberName.Name) {
2720 if (symbol is TypeParameter) {
2721 Report.Error (694, symbol.Location,
2722 "Type parameter `{0}' has same name as " +
2723 "containing type, or method", name);
2727 Report.SymbolRelatedToPreviousError (this);
2728 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2729 symbol.GetSignatureForError ());
2733 return base.AddToContainer (symbol, name);
2736 public override void VerifyMembers ()
2738 base.VerifyMembers ();
2740 if ((events != null) && Report.WarningLevel >= 3) {
2741 foreach (Event e in events){
2742 // Note: The event can be assigned from same class only, so we can report
2743 // this warning for all accessibility modes
2744 if ((e.caching_flags & Flags.IsUsed) == 0)
2745 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2750 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2752 if (a.IsValidSecurityAttribute ()) {
2753 if (declarative_security == null)
2754 declarative_security = new ListDictionary ();
2756 a.ExtractSecurityPermissionSet (declarative_security);
2760 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2761 HasExplicitLayout = true;
2764 base.ApplyAttributeBuilder (a, cb);
2768 /// Defines the default constructors
2770 protected void DefineDefaultConstructor (bool is_static)
2772 // The default instance constructor is public
2773 // If the class is abstract, the default constructor is protected
2774 // The default static constructor is private
2778 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2780 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2783 Constructor c = new Constructor (this, MemberName.Name, mods,
2784 Parameters.EmptyReadOnlyParameters,
2785 new GeneratedBaseInitializer (Location),
2789 c.Block = new ToplevelBlock (null, Location);
2792 public override bool Define ()
2794 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2795 DefineDefaultConstructor (true);
2797 if (default_static_constructor != null)
2798 default_static_constructor.Define ();
2800 return base.Define ();
2803 public override void Emit ()
2807 if (declarative_security != null) {
2808 foreach (DictionaryEntry de in declarative_security) {
2809 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2814 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2816 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2819 protected override TypeAttributes TypeAttr {
2821 if (default_static_constructor == null)
2822 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2824 return base.TypeAttr;
2830 // TODO: should be sealed
2831 public class Class : ClassOrStruct {
2832 const int AllowedModifiers =
2835 Modifiers.PROTECTED |
2836 Modifiers.INTERNAL |
2838 Modifiers.ABSTRACT |
2843 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2845 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2847 : base (ns, parent, name, attrs, Kind.Class)
2849 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2850 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2852 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2853 Report.FeatureIsNotAvailable (Location, "static classes");
2857 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2859 if (part.Name == "System.Object")
2860 Report.Error (537, part.Location,
2861 "The class System.Object cannot have a base class or implement an interface.");
2862 base.AddBasesForPart (part, bases);
2865 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2867 if (a.Type == TypeManager.attribute_usage_type) {
2868 if (!TypeManager.IsAttributeType (BaseType) &&
2869 TypeBuilder.FullName != "System.Attribute") {
2870 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2874 if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2875 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2879 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2880 !attributes.Contains (TypeManager.guid_attr_type)) {
2881 a.Error_MissingGuidAttribute ();
2885 if (a.Type == TypeManager.extension_attribute_type) {
2886 a.Error_MisusedExtensionAttribute ();
2890 if (AttributeTester.IsAttributeExcluded (a.Type))
2893 base.ApplyAttributeBuilder (a, cb);
2896 public override AttributeTargets AttributeTargets {
2898 return AttributeTargets.Class;
2902 protected override void DefineContainerMembers (MemberCoreArrayList list)
2908 base.DefineContainerMembers (list);
2912 foreach (MemberCore m in list) {
2913 if (m is Operator) {
2914 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2918 if (m is Destructor) {
2919 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2923 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2924 m.CheckProtectedModifier ();
2929 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2933 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2936 if (m is Constructor) {
2937 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2941 Method method = m as Method;
2942 if (method != null && method.Parameters.HasExtensionMethodType) {
2943 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2947 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2950 base.DefineContainerMembers (list);
2953 public override TypeBuilder DefineType ()
2955 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2956 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2960 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2961 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2965 return base.DefineType ();
2968 protected override bool DoDefineMembers ()
2970 if (InstanceConstructors == null && !IsStatic)
2971 DefineDefaultConstructor (false);
2973 return base.DoDefineMembers ();
2976 public override void Emit ()
2981 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2982 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2986 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2988 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2990 if (base_class == null) {
2991 if (RootContext.StdLib)
2992 base_class = TypeManager.system_object_expr;
2993 else if (Name != "System.Object")
2994 base_class = TypeManager.system_object_expr;
2996 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2998 689, base_class.Location,
2999 "Cannot derive from `{0}' because it is a type parameter",
3000 base_class.GetSignatureForError ());
3004 if (base_class.IsSealed){
3005 Report.SymbolRelatedToPreviousError (base_class.Type);
3006 if (base_class.Type.IsAbstract) {
3007 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3008 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3010 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3011 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3016 if (!base_class.CanInheritFrom ()){
3017 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3018 GetSignatureForError (), base_class.GetSignatureForError ());
3022 if (!base_class.AsAccessible (this)) {
3023 Report.SymbolRelatedToPreviousError (base_class.Type);
3024 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3025 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3029 if (PartialContainer.IsStaticClass) {
3030 if (base_class.Type != TypeManager.object_type) {
3031 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3032 GetSignatureForError (), base_class.GetSignatureForError ());
3036 if (ifaces != null) {
3037 foreach (TypeExpr t in ifaces)
3038 Report.SymbolRelatedToPreviousError (t.Type);
3039 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
3046 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3047 /// Valid only for attribute classes.
3048 public bool IsExcluded ()
3050 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3051 return (caching_flags & Flags.Excluded) != 0;
3053 caching_flags &= ~Flags.Excluded_Undetected;
3055 if (OptAttributes == null)
3058 if (TypeManager.conditional_attribute_type == null)
3061 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3066 foreach (Attribute a in attrs) {
3067 string condition = a.GetConditionalAttributeValue ();
3068 if (RootContext.AllDefines.Contains (condition))
3072 caching_flags |= Flags.Excluded;
3078 return (ModFlags & Modifiers.STATIC) != 0;
3083 // FIXME: How do we deal with the user specifying a different
3086 protected override TypeAttributes TypeAttr {
3088 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3090 ta |= StaticClassAttribute;
3096 public sealed class Struct : ClassOrStruct {
3098 // Modifiers allowed in a struct declaration
3100 const int AllowedModifiers =
3103 Modifiers.PROTECTED |
3104 Modifiers.INTERNAL |
3108 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3109 int mod, Attributes attrs)
3110 : base (ns, parent, name, attrs, Kind.Struct)
3114 if (parent.Parent == null)
3115 accmods = Modifiers.INTERNAL;
3117 accmods = Modifiers.PRIVATE;
3119 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3121 this.ModFlags |= Modifiers.SEALED;
3124 public override AttributeTargets AttributeTargets {
3126 return AttributeTargets.Struct;
3130 const TypeAttributes DefaultTypeAttributes =
3131 TypeAttributes.SequentialLayout |
3132 TypeAttributes.Sealed |
3133 TypeAttributes.BeforeFieldInit;
3136 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3138 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3140 // If we are compiling our runtime,
3141 // and we are defining ValueType, then our
3142 // base is `System.Object'.
3144 if (base_class == null) {
3145 if (!RootContext.StdLib && Name == "System.ValueType")
3146 base_class = TypeManager.system_object_expr;
3148 base_class = TypeManager.system_valuetype_expr;
3155 // FIXME: Allow the user to specify a different set of attributes
3156 // in some cases (Sealed for example is mandatory for a class,
3157 // but what SequentialLayout can be changed
3159 protected override TypeAttributes TypeAttr {
3161 return base.TypeAttr | DefaultTypeAttributes;
3165 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3167 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3168 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3169 field.GetSignatureForError ());
3172 base.RegisterFieldForInitialization (field, expression);
3180 public sealed class Interface : TypeContainer, IMemberContainer {
3183 /// Modifiers allowed in a class declaration
3185 public const int AllowedModifiers =
3188 Modifiers.PROTECTED |
3189 Modifiers.INTERNAL |
3193 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3195 : base (ns, parent, name, attrs, Kind.Interface)
3199 if (parent.Parent == null)
3200 accmods = Modifiers.INTERNAL;
3202 accmods = Modifiers.PRIVATE;
3204 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3207 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3209 if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3210 !attributes.Contains (TypeManager.guid_attr_type)) {
3211 a.Error_MissingGuidAttribute ();
3214 base.ApplyAttributeBuilder (a, cb);
3218 public override AttributeTargets AttributeTargets {
3220 return AttributeTargets.Interface;
3224 const TypeAttributes DefaultTypeAttributes =
3225 TypeAttributes.AutoLayout |
3226 TypeAttributes.Abstract |
3227 TypeAttributes.Interface;
3229 protected override TypeAttributes TypeAttr {
3231 return base.TypeAttr | DefaultTypeAttributes;
3235 protected override bool VerifyClsCompliance ()
3237 if (!base.VerifyClsCompliance ())
3240 if (ifaces != null) {
3241 foreach (Type t in ifaces) {
3242 if (AttributeTester.IsClsCompliant (t))
3245 Report.SymbolRelatedToPreviousError (t);
3246 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3247 GetSignatureForError (), TypeManager.CSharpName (t));
3255 // It is used as a base class for all property based members
3256 // This includes properties, indexers, and events
3257 public abstract class PropertyBasedMember : InterfaceMemberBase
3259 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3260 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3261 MemberName name, Attributes attrs)
3262 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3266 protected override bool VerifyClsCompliance ()
3268 if (!base.VerifyClsCompliance ())
3271 if (!AttributeTester.IsClsCompliant (MemberType)) {
3272 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3273 GetSignatureForError ());
3281 public abstract class MethodCore : InterfaceMemberBase
3283 public readonly Parameters Parameters;
3284 protected ToplevelBlock block;
3286 public MethodCore (DeclSpace parent, GenericMethod generic,
3287 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3288 MemberName name, Attributes attrs, Parameters parameters)
3289 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3291 Parameters = parameters;
3295 // Returns the System.Type array for the parameters of this method
3297 public Type [] ParameterTypes {
3299 return Parameters.Types;
3303 public Parameters ParameterInfo
3310 public ToplevelBlock Block {
3320 protected override bool CheckBase ()
3322 // Check whether arguments were correct.
3323 if (!DefineParameters (Parameters))
3326 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
3327 if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
3328 MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
3331 // TODO: Find a better way how to check reserved accessors collision
3332 Method m = this as Method;
3334 if (!m.CheckForDuplications ())
3339 if (!base.CheckBase ())
3346 // Returns a string that represents the signature for this
3347 // member which should be used in XML documentation.
3349 public override string GetDocCommentName (DeclSpace ds)
3351 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3355 // Raised (and passed an XmlElement that contains the comment)
3356 // when GenerateDocComment is writing documentation expectedly.
3358 // FIXME: with a few effort, it could be done with XmlReader,
3359 // that means removal of DOM use.
3361 internal override void OnGenerateDocComment (XmlElement el)
3363 DocUtil.OnMethodGenerateDocComment (this, el);
3367 // Represents header string for documentation comment.
3369 public override string DocCommentHeader
3371 get { return "M:"; }
3374 public override bool EnableOverloadChecks (MemberCore overload)
3376 if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3377 caching_flags |= Flags.MethodOverloadsExist;
3384 public virtual void SetYields ()
3386 ModFlags |= Modifiers.METHOD_YIELDS;
3389 protected override bool VerifyClsCompliance ()
3391 if (!base.VerifyClsCompliance ())
3394 if (Parameters.HasArglist) {
3395 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3398 if (!AttributeTester.IsClsCompliant (MemberType)) {
3399 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3400 GetSignatureForError ());
3403 Parameters.VerifyClsCompliance ();
3409 public abstract class InterfaceMemberBase : MemberBase {
3411 // Whether this is an interface member.
3413 public bool IsInterface;
3416 // If true, this is an explicit interface implementation
3418 public bool IsExplicitImpl;
3420 protected bool is_external_implementation;
3423 // The interface type we are explicitly implementing
3425 public Type InterfaceType;
3428 // The method we're overriding if this is an override method.
3430 protected MethodInfo base_method;
3432 readonly int explicit_mod_flags;
3433 public MethodAttributes flags;
3435 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3436 FullNamedExpression type, int mod, int allowed_mod, bool is_iface,
3437 MemberName name, Attributes attrs)
3438 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3441 IsInterface = is_iface;
3442 IsExplicitImpl = (MemberName.Left != null);
3443 explicit_mod_flags = mod;
3446 protected override bool CheckBase ()
3448 if (!base.CheckBase ())
3454 // Is null for System.Object while compiling corlib and base interfaces
3455 if (Parent.PartialContainer.BaseCache == null) {
3456 if ((ModFlags & Modifiers.NEW) != 0) {
3457 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3462 Type base_ret_type = null;
3463 base_method = FindOutBaseMethod (ref base_ret_type);
3465 // method is override
3466 if (base_method != null) {
3467 if (!CheckMethodAgainstBase (base_ret_type))
3470 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3471 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3473 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3474 Report.SymbolRelatedToPreviousError (base_method);
3475 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3476 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3479 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3480 Report.SymbolRelatedToPreviousError (base_method);
3481 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3482 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3489 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3490 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3491 if (conflict_symbol != null) {
3492 Report.SymbolRelatedToPreviousError (conflict_symbol);
3494 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3495 else if (this is PropertyBase)
3496 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3498 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3500 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3501 GetSignatureForError (), SimpleName.GetMemberType (this));
3506 if (conflict_symbol == null) {
3507 if ((ModFlags & Modifiers.NEW) != 0) {
3508 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3513 if ((ModFlags & Modifiers.NEW) == 0) {
3514 if (this is Method && conflict_symbol is MethodBase)
3517 Report.SymbolRelatedToPreviousError (conflict_symbol);
3518 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3519 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3526 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3527 // that have been defined.
3529 // `name' is the user visible name for reporting errors (this is used to
3530 // provide the right name regarding method names and properties)
3532 bool CheckMethodAgainstBase (Type base_method_type)
3536 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3537 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3538 Report.Error (506, Location,
3539 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3540 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3544 // Now we check that the overriden method is not final
3546 if (base_method.IsFinal) {
3547 Report.SymbolRelatedToPreviousError (base_method);
3548 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3549 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3553 // Check that the permissions are not being changed
3555 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3556 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3558 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3559 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3563 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3564 Report.SymbolRelatedToPreviousError (base_method);
3565 if (this is PropertyBasedMember) {
3566 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3567 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3570 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3571 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3577 if ((ModFlags & Modifiers.NEW) == 0) {
3578 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3579 ModFlags |= Modifiers.NEW;
3580 Report.SymbolRelatedToPreviousError (base_method);
3581 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3582 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",
3583 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3585 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3586 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3590 if (base_method.IsAbstract && !IsInterface) {
3591 Report.SymbolRelatedToPreviousError (base_method);
3592 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3593 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3601 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3603 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3605 // when overriding protected internal, the method can be declared
3606 // protected internal only within the same assembly or assembly
3607 // which has InternalsVisibleTo
3609 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3610 return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3611 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3613 // if it's not "protected internal", it must be "protected"
3617 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3619 // protected within the same assembly - an error
3622 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3623 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3625 // protected ok, but other attributes differ - report an error
3631 return (thisp == base_classp);
3635 protected bool DefineParameters (Parameters parameters)
3637 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3639 if (!parameters.Resolve (rc))
3643 foreach (Parameter p in parameters.FixedParameters) {
3644 if (p.CheckAccessibility (this))
3647 Report.SymbolRelatedToPreviousError (p.ParameterType);
3648 if (this is Indexer)
3649 Report.Error (55, Location,
3650 "Inconsistent accessibility: parameter type `" +
3651 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3652 "accessible than indexer `" + GetSignatureForError () + "'");
3653 else if (this is Operator)
3654 Report.Error (57, Location,
3655 "Inconsistent accessibility: parameter type `" +
3656 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3657 "accessible than operator `" + GetSignatureForError () + "'");
3659 Report.Error (51, Location,
3660 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3661 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3667 protected override bool DoDefine()
3669 if (!base.DoDefine ())
3672 if (IsExplicitImpl) {
3673 TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3677 InterfaceType = texpr.Type;
3679 if (!InterfaceType.IsInterface) {
3680 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3684 if (!Parent.PartialContainer.VerifyImplements (this))
3691 protected virtual bool DoDefineBase ()
3694 throw new InternalErrorException ();
3697 ModFlags = Modifiers.PUBLIC |
3698 Modifiers.ABSTRACT |
3699 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3701 flags = MethodAttributes.Public |
3702 MethodAttributes.Abstract |
3703 MethodAttributes.HideBySig |
3704 MethodAttributes.NewSlot |
3705 MethodAttributes.Virtual;
3707 if (!Parent.PartialContainer.MethodModifiersValid (this))
3710 flags = Modifiers.MethodAttr (ModFlags);
3713 if (IsExplicitImpl) {
3714 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3715 if (iface_texpr == null)
3718 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3719 Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3720 GetSignatureForError ());
3724 InterfaceType = iface_texpr.Type;
3726 if (!InterfaceType.IsInterface) {
3727 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3731 if (!Parent.PartialContainer.VerifyImplements (this))
3734 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3740 public override void Emit()
3742 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3743 // We are more strict than Microsoft and report CS0626 as error
3744 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3745 Report.Error (626, Location,
3746 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3747 GetSignatureForError ());
3753 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3755 Report.SymbolRelatedToPreviousError (base_method);
3756 string base_name = TypeManager.GetFullNameSignature (base_method);
3757 string this_name = GetSignatureForError ();
3758 if (suffix != null) {
3759 base_name += suffix;
3760 this_name += suffix;
3763 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3764 this_name, Modifiers.GetDescription (ma), base_name);
3767 protected static string Error722 {
3769 return "`{0}': static types cannot be used as return types";
3774 /// Gets base method and its return type
3776 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3779 // The "short" name of this property / indexer / event. This is the
3780 // name without the explicit interface.
3782 public string ShortName
3784 get { return MemberName.Name; }
3785 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3788 public string GetFullName (MemberName name)
3790 if (!IsExplicitImpl)
3793 return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
3796 protected override bool VerifyClsCompliance ()
3798 if (!base.VerifyClsCompliance ()) {
3799 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3800 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3803 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3804 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3809 if (GenericMethod != null)
3810 GenericMethod.VerifyClsCompliance ();
3815 public override bool IsUsed
3817 get { return IsExplicitImpl || base.IsUsed; }
3822 public abstract class MethodOrOperator : MethodCore, IMethodData
3824 public MethodBuilder MethodBuilder;
3825 ReturnParameter return_attributes;
3826 ListDictionary declarative_security;
3827 protected MethodData MethodData;
3830 ArrayList anonymous_methods;
3832 static string[] attribute_targets = new string [] { "method", "return" };
3834 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3835 int allowed_mod, bool is_interface, MemberName name,
3836 Attributes attrs, Parameters parameters)
3837 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3842 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3844 if (a.Target == AttributeTargets.ReturnValue) {
3845 if (return_attributes == null)
3846 return_attributes = new ReturnParameter (MethodBuilder, Location);
3848 return_attributes.ApplyAttributeBuilder (a, cb);
3852 if (a.IsInternalMethodImplAttribute) {
3853 is_external_implementation = true;
3856 if (a.Type == TypeManager.dllimport_type) {
3857 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3858 if ((ModFlags & extern_static) != extern_static) {
3859 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3861 is_external_implementation = true;
3864 if (a.IsValidSecurityAttribute ()) {
3865 if (declarative_security == null)
3866 declarative_security = new ListDictionary ();
3867 a.ExtractSecurityPermissionSet (declarative_security);
3871 if (MethodBuilder != null)
3872 MethodBuilder.SetCustomAttribute (cb);
3875 public override AttributeTargets AttributeTargets {
3877 return AttributeTargets.Method;
3881 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3883 return new EmitContext (
3884 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3887 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
3889 if (anonymous_methods == null)
3890 anonymous_methods = new ArrayList ();
3891 anonymous_methods.Add (anonymous);
3894 protected bool DefineGenericMethod ()
3896 if (!DoDefineBase ())
3900 if (GenericMethod != null) {
3903 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags); //, ReturnType, null);
3905 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3908 if (!GenericMethod.Define (MethodBuilder, block))
3916 public bool ResolveMembers ()
3918 if (!DefineGenericMethod ())
3921 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
3922 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
3923 if (iterator == null)
3927 if (anonymous_methods != null) {
3928 foreach (AnonymousMethodExpression ame in anonymous_methods) {
3929 if (!ame.CreateAnonymousHelpers ())
3937 public override bool Define ()
3942 if (!CheckAbstractAndExtern (block != null))
3945 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3946 for (int i = 0; i < Parameters.Count; ++i ) {
3947 if (Parameters.ParameterModifier (i) == Parameter.Modifier.OUT) {
3948 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3949 GetSignatureForError ());
3958 if (IsPartialDefinition) {
3959 caching_flags &= ~Flags.Excluded_Undetected;
3960 caching_flags |= Flags.Excluded;
3961 // Add to member cache only when a partial method implementation is not there
3962 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3963 MethodBase mb = new PartialMethodDefinitionInfo (this);
3964 Parent.MemberCache.AddMember (mb, this);
3965 TypeManager.AddMethod (mb, this);
3971 MethodData = new MethodData (
3972 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3974 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3977 MethodBuilder = MethodData.MethodBuilder;
3980 if (MethodBuilder.IsGenericMethod)
3981 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3984 Parent.MemberCache.AddMember (MethodBuilder, this);
3986 if (!TypeManager.IsGenericParameter (MemberType)) {
3987 if (MemberType.IsAbstract && MemberType.IsSealed) {
3988 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3996 public override void Emit ()
3999 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
4000 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
4002 if (OptAttributes != null)
4003 OptAttributes.Emit ();
4005 if (declarative_security != null) {
4006 foreach (DictionaryEntry de in declarative_security) {
4007 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4014 protected void Error_ConditionalAttributeIsNotValid ()
4016 Report.Error (577, Location,
4017 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4018 GetSignatureForError ());
4021 public bool IsPartialDefinition {
4023 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
4027 public bool IsPartialImplementation {
4029 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
4033 public override string[] ValidAttributeTargets {
4035 return attribute_targets;
4039 #region IMethodData Members
4041 public CallingConventions CallingConventions {
4043 CallingConventions cc = Parameters.CallingConvention;
4044 if (Parameters.HasArglist && block != null)
4045 block.HasVarargs = true;
4048 if ((ModFlags & Modifiers.STATIC) == 0)
4049 cc |= CallingConventions.HasThis;
4051 // FIXME: How is `ExplicitThis' used in C#?
4057 public Type ReturnType {
4063 public MemberName MethodName {
4069 public Iterator Iterator {
4070 get { return iterator; }
4073 public new Location Location {
4075 return base.Location;
4079 protected override bool CheckBase ()
4081 if (!base.CheckBase ())
4084 // TODO: Destructor should derive from MethodCore
4085 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4086 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4087 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4095 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4097 public bool IsExcluded () {
4098 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4099 return (caching_flags & Flags.Excluded) != 0;
4101 caching_flags &= ~Flags.Excluded_Undetected;
4103 if (base_method == null) {
4104 if (OptAttributes == null)
4107 if (TypeManager.conditional_attribute_type == null)
4110 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4115 foreach (Attribute a in attrs) {
4116 string condition = a.GetConditionalAttributeValue ();
4117 if (condition == null)
4120 if (RootContext.AllDefines.Contains (condition))
4124 caching_flags |= Flags.Excluded;
4128 IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
4130 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4131 caching_flags |= Flags.Excluded;
4137 if (md.IsExcluded ()) {
4138 caching_flags |= Flags.Excluded;
4144 GenericMethod IMethodData.GenericMethod {
4146 return GenericMethod;
4150 public virtual void EmitExtraSymbolInfo ()
4157 public class SourceMethod : ISourceMethod
4162 protected SourceMethod (DeclSpace parent, MethodBase builder,
4163 ISourceFile file, Location start, Location end)
4165 this.parent = parent;
4166 this.builder = builder;
4168 SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
4171 public string Name {
4172 get { return builder.Name; }
4175 public int NamespaceID {
4176 get { return parent.NamespaceEntry.SymbolFileID; }
4181 if (builder is MethodBuilder)
4182 return ((MethodBuilder) builder).GetToken ().Token;
4183 else if (builder is ConstructorBuilder)
4184 return ((ConstructorBuilder) builder).GetToken ().Token;
4186 throw new NotSupportedException ();
4190 public void CloseMethod ()
4192 SymbolWriter.CloseMethod ();
4195 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
4197 if (!SymbolWriter.HasSymbolWriter)
4202 Location start_loc = block.StartLocation;
4203 if (start_loc.IsNull)
4206 Location end_loc = block.EndLocation;
4210 ISourceFile file = start_loc.SourceFile;
4214 return new SourceMethod (
4215 parent, builder, file, start_loc, end_loc);
4219 public class Method : MethodOrOperator, IAnonymousHost {
4222 /// Modifiers allowed in a class declaration
4224 const int AllowedModifiers =
4227 Modifiers.PROTECTED |
4228 Modifiers.INTERNAL |
4233 Modifiers.OVERRIDE |
4234 Modifiers.ABSTRACT |
4236 Modifiers.METHOD_YIELDS |
4239 const int AllowedInterfaceModifiers =
4240 Modifiers.NEW | Modifiers.UNSAFE;
4243 // return_type can be "null" for VOID values.
4245 public Method (DeclSpace parent, GenericMethod generic,
4246 FullNamedExpression return_type, int mod, bool is_iface,
4247 MemberName name, Parameters parameters, Attributes attrs)
4248 : base (parent, generic, return_type, mod,
4249 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4250 is_iface, name, attrs, parameters)
4254 public override string GetSignatureForError()
4256 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4259 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4261 Report.Error (17, location,
4262 "Program `{0}' has more than one entry point defined: `{1}'",
4263 CodeGen.FileName, TypeManager.CSharpSignature(b));
4266 bool IsEntryPoint ()
4268 if (ReturnType != TypeManager.void_type &&
4269 ReturnType != TypeManager.int32_type)
4272 if (Parameters.Count == 0)
4275 if (Parameters.Count > 1)
4278 Type t = Parameters.ParameterType (0);
4279 return t.IsArray && t.GetArrayRank () == 1 &&
4280 TypeManager.GetElementType (t) == TypeManager.string_type &&
4281 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4284 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4286 if (a.Type == TypeManager.conditional_attribute_type) {
4287 if (IsExplicitImpl) {
4288 Error_ConditionalAttributeIsNotValid ();
4292 if (ReturnType != TypeManager.void_type) {
4293 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4297 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4298 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4303 Report.Error (582, Location, "Conditional not valid on interface members");
4307 if (MethodData.implementing != null) {
4308 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4309 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4310 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4314 for (int i = 0; i < Parameters.Count; ++i) {
4315 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4316 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4322 if (a.Type == TypeManager.extension_attribute_type) {
4323 a.Error_MisusedExtensionAttribute ();
4327 base.ApplyAttributeBuilder (a, cb);
4330 public bool CheckForDuplications ()
4332 ArrayList ar = Parent.PartialContainer.Properties;
4334 for (int i = 0; i < ar.Count; ++i) {
4335 PropertyBase pb = (PropertyBase) ar [i];
4336 if (pb.AreAccessorsDuplicateImplementation (this))
4341 ar = Parent.PartialContainer.Indexers;
4343 for (int i = 0; i < ar.Count; ++i) {
4344 PropertyBase pb = (PropertyBase) ar [i];
4345 if (pb.AreAccessorsDuplicateImplementation (this))
4356 public override bool Define ()
4358 if (!base.Define ())
4361 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4362 Error1599 (Location, ReturnType);
4366 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4367 Name == "Finalize" && !(this is Destructor)) {
4368 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4371 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4372 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4373 Parent.PartialContainer.Mark_HasEquals ();
4374 else if (Parameters.Empty && Name == "GetHashCode")
4375 Parent.PartialContainer.Mark_HasGetHashCode ();
4378 if ((ModFlags & Modifiers.STATIC) == 0)
4381 if (Parameters.HasExtensionMethodType) {
4382 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4383 if (!Parent.IsTopLevel)
4384 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4385 GetSignatureForError ());
4387 if (TypeManager.extension_attribute_type == null) {
4388 Report.Error (1110, Location,
4389 "`{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",
4390 GetSignatureForError ());
4391 } else if (TypeManager.extension_attribute_attr == null) {
4392 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4393 TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4396 TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4399 ModFlags |= Modifiers.METHOD_EXTENSION;
4400 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4401 CodeGen.Assembly.HasExtensionMethods = true;
4403 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4404 GetSignatureForError ());
4409 // This is used to track the Entry Point,
4411 if (RootContext.NeedsEntryPoint &&
4413 (RootContext.MainClass == null ||
4414 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4415 if (IsEntryPoint ()) {
4417 if (RootContext.EntryPoint == null) {
4418 if (Parent.IsGeneric || MemberName.IsGeneric) {
4419 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4420 GetSignatureForError ());
4422 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4423 md.SetMemberIsUsed ();
4425 RootContext.EntryPoint = MethodBuilder;
4426 RootContext.EntryPointLocation = Location;
4429 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4430 Error_DuplicateEntryPoint (MethodBuilder, Location);
4433 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4434 GetSignatureForError ());
4444 public override void Emit ()
4447 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4448 if (IsPartialDefinition) {
4450 // Do attribute checks only when partial implementation does not exist
4452 if (MethodBuilder == null)
4458 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4459 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4460 GetSignatureForError ());
4462 MethodData.Emit (Parent);
4466 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4467 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4473 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4474 Location, MethodBuilder);
4479 public override bool EnableOverloadChecks (MemberCore overload)
4481 // TODO: It can be deleted when members will be defined in correct order
4482 if (overload is Operator)
4483 return overload.EnableOverloadChecks (this);
4485 if (overload is Indexer)
4488 return base.EnableOverloadChecks (overload);
4491 public static void Error1599 (Location loc, Type t)
4493 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4496 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4498 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4499 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4504 if (mi.IsSpecialName)
4507 base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4511 public void SetPartialDefinition (Method methodDefinition)
4513 caching_flags |= Flags.PartialDefinitionExists;
4514 methodDefinition.MethodBuilder = MethodBuilder;
4515 if (methodDefinition.attributes == null)
4518 if (attributes == null) {
4519 attributes = methodDefinition.attributes;
4521 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4525 protected override bool VerifyClsCompliance ()
4527 if (!base.VerifyClsCompliance ())
4530 if (ParameterInfo.Count > 0) {
4531 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4533 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4540 public abstract class ConstructorInitializer : Expression
4542 ArrayList argument_list;
4543 MethodGroupExpr base_constructor_group;
4545 public ConstructorInitializer (ArrayList argument_list, Location loc)
4547 this.argument_list = argument_list;
4551 public ArrayList Arguments {
4553 return argument_list;
4557 public override Expression CreateExpressionTree (EmitContext ec)
4559 throw new NotSupportedException ("ET");
4562 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4564 if (argument_list != null){
4565 foreach (Argument a in argument_list){
4566 if (!a.Resolve (ec, loc))
4571 if (this is ConstructorBaseInitializer) {
4572 if (ec.ContainerType.BaseType == null)
4575 type = ec.ContainerType.BaseType;
4576 if (ec.ContainerType.IsValueType) {
4577 Report.Error (522, loc,
4578 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4583 // It is legal to have "this" initializers that take no arguments
4584 // in structs, they are just no-ops.
4586 // struct D { public D (int a) : this () {}
4588 if (ec.ContainerType.IsValueType && argument_list == null)
4591 type = ec.ContainerType;
4594 base_constructor_group = MemberLookupFinal (
4595 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4596 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4597 loc) as MethodGroupExpr;
4599 if (base_constructor_group == null)
4602 base_constructor_group = base_constructor_group.OverloadResolve (
4603 ec, ref argument_list, false, loc);
4605 if (base_constructor_group == null)
4608 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4610 if (base_ctor == caller_builder){
4611 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4617 public override Expression DoResolve (EmitContext ec)
4619 throw new NotSupportedException ();
4622 public override void Emit (EmitContext ec)
4624 // It can be null for static initializers
4625 if (base_constructor_group == null)
4628 ec.Mark (loc, false);
4630 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4632 base_constructor_group.EmitCall (ec, argument_list);
4636 public class ConstructorBaseInitializer : ConstructorInitializer {
4637 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4638 base (argument_list, l)
4643 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4644 public GeneratedBaseInitializer (Location loc):
4650 public class ConstructorThisInitializer : ConstructorInitializer {
4651 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4652 base (argument_list, l)
4657 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4658 public ConstructorBuilder ConstructorBuilder;
4659 public ConstructorInitializer Initializer;
4660 ListDictionary declarative_security;
4661 ArrayList anonymous_methods;
4662 bool has_compliant_args;
4665 // Modifiers allowed for a constructor.
4667 public const int AllowedModifiers =
4669 Modifiers.PROTECTED |
4670 Modifiers.INTERNAL |
4676 static readonly string[] attribute_targets = new string [] { "method" };
4679 // The spec claims that static is not permitted, but
4680 // my very own code has static constructors.
4682 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4683 ConstructorInitializer init, Location loc)
4684 : base (parent, null, null, mod, AllowedModifiers, false,
4685 new MemberName (name, loc), null, args)
4690 public bool HasCompliantArgs {
4691 get { return has_compliant_args; }
4694 public override AttributeTargets AttributeTargets {
4695 get { return AttributeTargets.Constructor; }
4698 public Iterator Iterator {
4699 get { return null; }
4703 // Returns true if this is a default constructor
4705 public bool IsDefault ()
4707 if ((ModFlags & Modifiers.STATIC) != 0)
4708 return Parameters.Empty;
4710 return Parameters.Empty &&
4711 (Initializer is ConstructorBaseInitializer) &&
4712 (Initializer.Arguments == null);
4715 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4717 if (a.IsValidSecurityAttribute ()) {
4718 if (declarative_security == null) {
4719 declarative_security = new ListDictionary ();
4721 a.ExtractSecurityPermissionSet (declarative_security);
4725 if (a.IsInternalMethodImplAttribute) {
4726 is_external_implementation = true;
4729 ConstructorBuilder.SetCustomAttribute (cb);
4732 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4734 if (anonymous_methods == null)
4735 anonymous_methods = new ArrayList ();
4736 anonymous_methods.Add (anonymous);
4739 public bool ResolveMembers ()
4741 if (anonymous_methods != null) {
4742 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4743 if (!ame.CreateAnonymousHelpers ())
4751 protected override bool CheckBase ()
4753 if ((ModFlags & Modifiers.STATIC) != 0) {
4754 if (!Parameters.Empty) {
4755 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4756 GetSignatureForError ());
4760 // the rest can be ignored
4764 // Check whether arguments were correct.
4765 if (!DefineParameters (Parameters))
4768 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4769 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
4772 if (Parent.PartialContainer.Kind == Kind.Struct) {
4773 if (ParameterTypes.Length == 0) {
4774 Report.Error (568, Location,
4775 "Structs cannot contain explicit parameterless constructors");
4780 CheckProtectedModifier ();
4786 // Creates the ConstructorBuilder
4788 public override bool Define ()
4790 if (ConstructorBuilder != null)
4793 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4794 MethodAttributes.SpecialName);
4796 if ((ModFlags & Modifiers.STATIC) != 0) {
4797 ca |= MethodAttributes.Static | MethodAttributes.Private;
4799 ca |= MethodAttributes.HideBySig;
4801 if ((ModFlags & Modifiers.PUBLIC) != 0)
4802 ca |= MethodAttributes.Public;
4803 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4804 if ((ModFlags & Modifiers.INTERNAL) != 0)
4805 ca |= MethodAttributes.FamORAssem;
4807 ca |= MethodAttributes.Family;
4808 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4809 ca |= MethodAttributes.Assembly;
4811 ca |= MethodAttributes.Private;
4814 if (!CheckAbstractAndExtern (block != null))
4817 // Check if arguments were correct.
4821 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4822 ca, CallingConventions,
4825 if ((ModFlags & Modifiers.UNSAFE) != 0)
4826 ConstructorBuilder.InitLocals = false;
4828 if (Parent.PartialContainer.IsComImport) {
4829 if (!IsDefault ()) {
4830 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4831 Parent.GetSignatureForError ());
4834 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4837 Parent.MemberCache.AddMember (ConstructorBuilder, this);
4838 TypeManager.AddMethod (ConstructorBuilder, this);
4840 // It's here only to report an error
4841 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4842 member_type = TypeManager.void_type;
4843 Iterator.CreateIterator (this, Parent, null, ModFlags);
4852 public override void Emit ()
4854 if (OptAttributes != null)
4855 OptAttributes.Emit ();
4859 EmitContext ec = CreateEmitContext (null, null);
4862 // If we use a "this (...)" constructor initializer, then
4863 // do not emit field initializers, they are initialized in the other constructor
4865 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4866 !(Initializer is ConstructorThisInitializer);
4868 if (emit_field_initializers)
4869 Parent.PartialContainer.ResolveFieldInitializers (ec);
4871 if (block != null) {
4872 // If this is a non-static `struct' constructor and doesn't have any
4873 // initializer, it must initialize all of the struct's fields.
4874 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4875 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4876 block.AddThisVariable (Parent, Location);
4878 if (!block.ResolveMeta (ec, ParameterInfo))
4882 if ((ModFlags & Modifiers.STATIC) == 0){
4883 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4884 Initializer = new GeneratedBaseInitializer (Location);
4887 // Spec mandates that Initializers will not have
4891 if ((Initializer != null) &&
4892 !Initializer.Resolve (ConstructorBuilder, ec))
4894 ec.IsStatic = false;
4897 Parameters.ApplyAttributes (ConstructorBuilder);
4899 SourceMethod source = null;
4901 ec.OmitDebuggingInfo = true;
4903 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4905 bool unreachable = false;
4906 if (block != null) {
4907 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4910 ec.EmitMeta (block);
4912 if (Report.Errors > 0)
4915 if (emit_field_initializers)
4916 Parent.PartialContainer.EmitFieldInitializers (ec);
4918 if (block.ScopeInfo != null) {
4919 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4920 init.EmitStatement (ec);
4923 if (Initializer != null)
4924 Initializer.Emit (ec);
4926 ec.EmitResolvedTopBlock (block, unreachable);
4930 source.CloseMethod ();
4932 if (declarative_security != null) {
4933 foreach (DictionaryEntry de in declarative_security) {
4934 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4941 // Is never override
4942 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4947 public override string GetSignatureForError()
4949 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4952 public override string[] ValidAttributeTargets {
4954 return attribute_targets;
4958 protected override bool VerifyClsCompliance ()
4960 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4964 if (ParameterInfo.Count > 0) {
4965 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4967 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4969 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4970 foreach (Type param in ParameterTypes) {
4971 if (param.IsArray) {
4977 has_compliant_args = true;
4981 #region IMethodData Members
4983 public System.Reflection.CallingConventions CallingConventions {
4985 CallingConventions cc = Parameters.CallingConvention;
4987 if (Parent.PartialContainer.Kind == Kind.Class)
4988 if ((ModFlags & Modifiers.STATIC) == 0)
4989 cc |= CallingConventions.HasThis;
4991 // FIXME: How is `ExplicitThis' used in C#?
4997 public new Location Location {
4999 return base.Location;
5003 public MemberName MethodName {
5009 public Type ReturnType {
5015 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5017 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5018 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5019 ec.CurrentBlock = block;
5023 public bool IsExcluded()
5028 GenericMethod IMethodData.GenericMethod {
5034 void IMethodData.EmitExtraSymbolInfo ()
5041 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5043 public interface IMethodData
5045 CallingConventions CallingConventions { get; }
5046 Location Location { get; }
5047 MemberName MethodName { get; }
5048 Type ReturnType { get; }
5049 GenericMethod GenericMethod { get; }
5050 Parameters ParameterInfo { get; }
5052 Iterator Iterator { get; }
5054 Attributes OptAttributes { get; }
5055 ToplevelBlock Block { get; set; }
5057 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5058 ObsoleteAttribute GetObsoleteAttribute ();
5059 string GetSignatureForError ();
5061 bool IsClsComplianceRequired ();
5062 void SetMemberIsUsed ();
5063 void EmitExtraSymbolInfo ();
5067 // Encapsulates most of the Method's state
5069 public class MethodData {
5071 readonly IMethodData method;
5073 public readonly GenericMethod GenericMethod;
5076 // Are we implementing an interface ?
5078 public MethodInfo implementing;
5083 protected InterfaceMemberBase member;
5084 protected int modifiers;
5085 protected MethodAttributes flags;
5086 protected Type declaring_type;
5087 protected MethodInfo parent_method;
5089 MethodBuilder builder = null;
5090 public MethodBuilder MethodBuilder {
5096 public Type DeclaringType {
5098 return declaring_type;
5102 public MethodData (InterfaceMemberBase member,
5103 int modifiers, MethodAttributes flags, IMethodData method)
5105 this.member = member;
5106 this.modifiers = modifiers;
5109 this.method = method;
5112 public MethodData (InterfaceMemberBase member,
5113 int modifiers, MethodAttributes flags,
5114 IMethodData method, MethodBuilder builder,
5115 GenericMethod generic, MethodInfo parent_method)
5116 : this (member, modifiers, flags, method)
5118 this.builder = builder;
5119 this.GenericMethod = generic;
5120 this.parent_method = parent_method;
5123 public bool Define (DeclSpace parent, string method_full_name)
5125 string name = method.MethodName.Basename;
5127 TypeContainer container = parent.PartialContainer;
5129 PendingImplementation pending = container.PendingImplementations;
5130 if (pending != null){
5131 if (member is Indexer) // TODO: test it, but it should work without this IF
5132 implementing = pending.IsInterfaceIndexer (
5133 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5135 implementing = pending.IsInterfaceMethod (
5136 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5138 if (member.InterfaceType != null){
5139 if (implementing == null){
5140 if (member is PropertyBase) {
5141 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5142 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5143 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5146 Report.Error (539, method.Location,
5147 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5148 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5152 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5153 Report.SymbolRelatedToPreviousError (implementing);
5154 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5155 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5159 if (implementing != null) {
5160 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5161 if (prop_method == null) {
5162 if (TypeManager.IsSpecialMethod (implementing)) {
5163 Report.SymbolRelatedToPreviousError (implementing);
5164 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5165 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5166 implementing.Name.StartsWith ("get_") ? "get" : "set");
5168 } else if (implementing.DeclaringType.IsInterface) {
5169 if (!implementing.IsSpecialName) {
5170 Report.SymbolRelatedToPreviousError (implementing);
5171 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5172 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5175 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5176 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5177 Report.SymbolRelatedToPreviousError (implementing);
5178 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5179 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5188 // For implicit implementations, make sure we are public, for
5189 // explicit implementations, make sure we are private.
5191 if (implementing != null){
5193 // Setting null inside this block will trigger a more
5194 // verbose error reporting for missing interface implementations
5196 // The "candidate" function has been flagged already
5197 // but it wont get cleared
5199 if (member.IsExplicitImpl){
5200 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5201 Report.SymbolRelatedToPreviousError (implementing);
5202 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5203 method.GetSignatureForError ());
5207 if (implementing.DeclaringType.IsInterface) {
5209 // If this is an interface method implementation,
5210 // check for public accessibility
5212 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5214 implementing = null;
5216 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5217 // We may never be private.
5218 implementing = null;
5220 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5222 // We may be protected if we're overriding something.
5224 implementing = null;
5229 // Static is not allowed
5231 if ((modifiers & Modifiers.STATIC) != 0){
5232 implementing = null;
5237 // If implementing is still valid, set flags
5239 if (implementing != null){
5241 // When implementing interface methods, set NewSlot
5242 // unless, we are overwriting a method.
5244 if (implementing.DeclaringType.IsInterface){
5245 if ((modifiers & Modifiers.OVERRIDE) == 0)
5246 flags |= MethodAttributes.NewSlot;
5249 MethodAttributes.Virtual |
5250 MethodAttributes.HideBySig;
5252 // Set Final unless we're virtual, abstract or already overriding a method.
5253 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5254 flags |= MethodAttributes.Final;
5257 DefineMethodBuilder (container, method_full_name, method.ParameterInfo.Types);
5259 if (builder == null)
5262 if (container.CurrentType != null)
5263 declaring_type = container.CurrentType;
5265 declaring_type = container.TypeBuilder;
5267 if ((modifiers & Modifiers.UNSAFE) != 0)
5268 builder.InitLocals = false;
5271 if (implementing != null){
5273 // clear the pending implemntation flag
5275 if (member is Indexer) {
5276 pending.ImplementIndexer (
5277 member.InterfaceType, builder, method.ReturnType,
5278 method.ParameterInfo, member.IsExplicitImpl);
5280 pending.ImplementMethod (
5281 member.InterfaceType, name, method.ReturnType,
5282 method.ParameterInfo, member.IsExplicitImpl);
5284 if (member.IsExplicitImpl)
5285 container.TypeBuilder.DefineMethodOverride (
5286 builder, implementing);
5289 TypeManager.AddMethod (builder, method);
5291 if (GenericMethod != null) {
5292 bool is_override = member.IsExplicitImpl |
5293 ((modifiers & Modifiers.OVERRIDE) != 0);
5295 if (implementing != null)
5296 parent_method = implementing;
5298 EmitContext ec = method.CreateEmitContext (container, null);
5299 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5308 /// Create the MethodBuilder for the method
5310 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5312 if (builder == null) {
5313 builder = container.TypeBuilder.DefineMethod (
5314 method_name, flags, method.CallingConventions,
5315 method.ReturnType, ParameterTypes);
5319 #if GMCS_SOURCE && !MS_COMPATIBLE
5320 builder.SetGenericMethodSignature (
5321 flags, method.CallingConventions,
5322 method.ReturnType, ParameterTypes);
5329 public void Emit (DeclSpace parent)
5331 ToplevelBlock block = method.Block;
5335 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5337 ec = method.CreateEmitContext (parent, null);
5339 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5341 if (GenericMethod != null)
5342 GenericMethod.EmitAttributes ();
5344 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5347 // Handle destructors specially
5349 // FIXME: This code generates buggy code
5351 if (member is Destructor)
5352 EmitDestructor (ec, block);
5354 ec.EmitTopBlock (method, block);
5356 if (source != null) {
5357 method.EmitExtraSymbolInfo ();
5358 source.CloseMethod ();
5362 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5364 ILGenerator ig = ec.ig;
5366 Label finish = ig.DefineLabel ();
5368 block.SetDestructor ();
5370 ig.BeginExceptionBlock ();
5371 ec.ReturnLabel = finish;
5372 ec.HasReturnLabel = true;
5373 ec.EmitTopBlock (method, block);
5375 // ig.MarkLabel (finish);
5376 ig.BeginFinallyBlock ();
5378 if (ec.ContainerType.BaseType != null) {
5379 Expression member_lookup = Expression.MemberLookup (
5380 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5381 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5383 if (member_lookup != null){
5384 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5386 ig.Emit (OpCodes.Ldarg_0);
5387 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5391 ig.EndExceptionBlock ();
5392 //ig.MarkLabel (ec.ReturnLabel);
5393 ig.Emit (OpCodes.Ret);
5397 // TODO: Should derive from MethodCore
5398 public class Destructor : Method {
5400 static string[] attribute_targets = new string [] { "method" };
5402 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5403 string name, Parameters parameters, Attributes attrs,
5405 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5409 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5411 if (a.Type == TypeManager.conditional_attribute_type) {
5412 Error_ConditionalAttributeIsNotValid ();
5416 base.ApplyAttributeBuilder (a, cb);
5419 public override string GetSignatureForError ()
5421 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5424 public override string[] ValidAttributeTargets {
5426 return attribute_targets;
5431 abstract public class MemberBase : MemberCore {
5432 protected FullNamedExpression type_name;
5433 public readonly DeclSpace ds;
5434 public readonly GenericMethod GenericMethod;
5437 // The type of this property / indexer / event
5439 protected Type member_type;
5440 public Type MemberType {
5442 // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
5443 if (member_type == null && type_name != null) {
5444 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5445 type_name = type_name.ResolveAsTypeTerminal (rc, false);
5446 if (type_name != null) {
5447 member_type = type_name.Type;
5455 // The constructor is only exposed to our children
5457 protected MemberBase (DeclSpace parent, GenericMethod generic,
5458 FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5459 MemberName name, Attributes attrs)
5460 : base (parent, name, attrs)
5462 this.ds = generic != null ? generic : (DeclSpace) parent;
5463 this.type_name = type;
5464 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5465 GenericMethod = generic;
5466 if (GenericMethod != null)
5467 GenericMethod.ModFlags = ModFlags;
5470 protected virtual bool CheckBase ()
5472 CheckProtectedModifier ();
5477 protected virtual bool DoDefine ()
5479 if (MemberType == null)
5482 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5483 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5484 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5485 GetSignatureForError (), Parent.GetSignatureForError ());
5489 // verify accessibility
5490 if (!IsAccessibleAs (MemberType)) {
5491 Report.SymbolRelatedToPreviousError (MemberType);
5492 if (this is Property)
5493 Report.Error (53, Location,
5494 "Inconsistent accessibility: property type `" +
5495 TypeManager.CSharpName (MemberType) + "' is less " +
5496 "accessible than property `" + GetSignatureForError () + "'");
5497 else if (this is Indexer)
5498 Report.Error (54, Location,
5499 "Inconsistent accessibility: indexer return type `" +
5500 TypeManager.CSharpName (MemberType) + "' is less " +
5501 "accessible than indexer `" + GetSignatureForError () + "'");
5502 else if (this is MethodCore) {
5503 if (this is Operator)
5504 Report.Error (56, Location,
5505 "Inconsistent accessibility: return type `" +
5506 TypeManager.CSharpName (MemberType) + "' is less " +
5507 "accessible than operator `" + GetSignatureForError () + "'");
5509 Report.Error (50, Location,
5510 "Inconsistent accessibility: return type `" +
5511 TypeManager.CSharpName (MemberType) + "' is less " +
5512 "accessible than method `" + GetSignatureForError () + "'");
5514 Report.Error (52, Location,
5515 "Inconsistent accessibility: field type `" +
5516 TypeManager.CSharpName (MemberType) + "' is less " +
5517 "accessible than field `" + GetSignatureForError () + "'");
5525 protected bool IsTypePermitted ()
5527 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5528 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5536 // Abstract class for all fields
5538 abstract public class FieldBase : MemberBase {
5539 public FieldBuilder FieldBuilder;
5540 public Status status;
5541 protected Expression initializer;
5544 public enum Status : byte {
5545 HAS_OFFSET = 4 // Used by FieldMember.
5548 static readonly string[] attribute_targets = new string [] { "field" };
5550 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5551 int allowed_mod, MemberName name, Attributes attrs)
5552 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5555 if ((mod & Modifiers.ABSTRACT) != 0)
5556 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5559 public override AttributeTargets AttributeTargets {
5561 return AttributeTargets.Field;
5565 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5567 if (a.Type == TypeManager.field_offset_attribute_type) {
5568 status |= Status.HAS_OFFSET;
5570 if (!Parent.PartialContainer.HasExplicitLayout) {
5571 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5575 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5576 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5582 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5583 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5588 if (a.Type == TypeManager.marshal_as_attr_type) {
5589 UnmanagedMarshal marshal = a.GetMarshal (this);
5590 if (marshal != null) {
5591 FieldBuilder.SetMarshal (marshal);
5596 if ((a.HasSecurityAttribute)) {
5597 a.Error_InvalidSecurityParent ();
5601 FieldBuilder.SetCustomAttribute (cb);
5604 protected override bool CheckBase ()
5606 if (!base.CheckBase ())
5609 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5610 if (conflict_symbol == null) {
5611 if ((ModFlags & Modifiers.NEW) != 0) {
5612 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5617 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5618 Report.SymbolRelatedToPreviousError (conflict_symbol);
5619 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5620 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5626 public override bool Define()
5628 if (MemberType == null || member_type == null)
5631 if (TypeManager.IsGenericParameter (MemberType))
5634 if (MemberType == TypeManager.void_type) {
5635 // TODO: wrong location
5636 Expression.Error_VoidInvalidInTheContext (Location);
5640 if (MemberType.IsSealed && MemberType.IsAbstract) {
5641 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5651 if (!IsTypePermitted ())
5658 // Represents header string for documentation comment.
5660 public override string DocCommentHeader {
5661 get { return "F:"; }
5664 public override void Emit ()
5667 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5668 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5672 if (OptAttributes != null) {
5673 OptAttributes.Emit ();
5676 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5677 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5683 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5685 Report.SymbolRelatedToPreviousError (static_class);
5686 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5690 public Expression Initializer {
5692 if (value != null) {
5693 this.initializer = value;
5698 protected virtual bool IsFieldClsCompliant {
5700 if (FieldBuilder == null)
5703 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5707 public override string[] ValidAttributeTargets
5710 return attribute_targets;
5714 protected override bool VerifyClsCompliance ()
5716 if (!base.VerifyClsCompliance ())
5719 if (!IsFieldClsCompliant) {
5720 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5725 public void SetAssigned ()
5727 caching_flags |= Flags.IsAssigned;
5731 interface IFixedBuffer
5733 FieldInfo Element { get; }
5734 Type ElementType { get; }
5737 public class FixedFieldExternal: IFixedBuffer
5739 FieldInfo element_field;
5741 public FixedFieldExternal (FieldInfo fi)
5743 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5746 #region IFixedField Members
5748 public FieldInfo Element {
5750 return element_field;
5754 public Type ElementType {
5756 return element_field.FieldType;
5764 /// Fixed buffer implementation
5766 public class FixedField : FieldBase, IFixedBuffer
5768 public const string FixedElementName = "FixedElementField";
5769 static int GlobalCounter = 0;
5770 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5771 static FieldInfo[] fi;
5773 TypeBuilder fixed_buffer_type;
5774 FieldBuilder element;
5775 Expression size_expr;
5777 const int AllowedModifiers =
5780 Modifiers.PROTECTED |
5781 Modifiers.INTERNAL |
5784 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5785 Expression size_expr, Attributes attrs, Location loc):
5786 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5788 if (RootContext.Version == LanguageVersion.ISO_1)
5789 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5791 this.size_expr = size_expr;
5794 public override bool Define()
5796 if (!Parent.IsInUnsafeScope)
5797 Expression.UnsafeError (Location);
5799 if (!base.Define ())
5802 if (!TypeManager.IsPrimitiveType (MemberType)) {
5803 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",
5804 GetSignatureForError ());
5807 // Create nested fixed buffer container
5808 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5809 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5810 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5812 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5813 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5815 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5816 Parent.MemberCache.AddMember (FieldBuilder, this);
5817 TypeManager.RegisterFieldBase (FieldBuilder, this);
5822 public override void Emit()
5824 if (Parent.PartialContainer.Kind != Kind.Struct) {
5825 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5826 GetSignatureForError ());
5829 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5830 Constant c = size_expr.ResolveAsConstant (ec, this);
5834 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5835 if (buffer_size_const == null)
5838 int buffer_size = buffer_size_const.Value;
5840 if (buffer_size <= 0) {
5841 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5845 int type_size = Expression.GetTypeSize (MemberType);
5847 if (buffer_size > int.MaxValue / type_size) {
5848 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5849 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5853 buffer_size *= type_size;
5854 EmitFieldSize (buffer_size);
5858 void EmitFieldSize (int buffer_size)
5860 if (TypeManager.struct_layout_attribute_type == null) {
5861 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5862 "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5864 if (TypeManager.struct_layout_attribute_type == null)
5869 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5871 object [] fi_val = new object [] { buffer_size };
5873 if (TypeManager.struct_layout_attribute_ctor == null) {
5874 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5875 TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5876 if (TypeManager.struct_layout_attribute_ctor == null)
5880 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5881 ctor_args, fi, fi_val);
5882 fixed_buffer_type.SetCustomAttribute (cab);
5885 // Don't emit FixedBufferAttribute attribute for private types
5887 if ((ModFlags & Modifiers.PRIVATE) != 0)
5890 if (TypeManager.fixed_buffer_attr_ctor == null) {
5891 if (TypeManager.fixed_buffer_attr_type == null) {
5892 TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5893 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5895 if (TypeManager.fixed_buffer_attr_type == null)
5899 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5900 Location, TypeManager.type_type, TypeManager.int32_type);
5902 if (TypeManager.fixed_buffer_attr_ctor == null)
5906 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5907 FieldBuilder.SetCustomAttribute (cab);
5910 protected override bool IsFieldClsCompliant {
5916 #region IFixedField Members
5918 public FieldInfo Element {
5924 public Type ElementType {
5934 // The Field class is used to represents class/struct fields during parsing.
5936 public class Field : FieldBase {
5938 // Modifiers allowed in a class declaration
5940 const int AllowedModifiers =
5943 Modifiers.PROTECTED |
5944 Modifiers.INTERNAL |
5947 Modifiers.VOLATILE |
5951 public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
5952 Attributes attrs, Location loc)
5953 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5958 bool CanBeVolatile ()
5960 if (TypeManager.IsReferenceType (MemberType))
5963 if (MemberType.IsEnum)
5966 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5967 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5968 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5969 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5970 MemberType == TypeManager.float_type)
5976 public override bool Define ()
5978 if (!base.Define ())
5981 if ((ModFlags & Modifiers.VOLATILE) != 0){
5982 if (!CanBeVolatile ()) {
5983 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5984 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5987 if ((ModFlags & Modifiers.READONLY) != 0){
5988 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5989 GetSignatureForError ());
5993 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5997 Type[] required_modifier = null;
5998 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5999 if (TypeManager.isvolatile_type == null)
6000 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
6001 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
6003 if (TypeManager.isvolatile_type != null)
6004 required_modifier = new Type [] { TypeManager.isvolatile_type };
6007 FieldBuilder = Parent.TypeBuilder.DefineField (
6008 Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
6010 FieldBuilder = Parent.TypeBuilder.DefineField (
6011 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6013 Parent.MemberCache.AddMember (FieldBuilder, this);
6014 TypeManager.RegisterFieldBase (FieldBuilder, this);
6016 catch (ArgumentException) {
6017 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6021 if (initializer != null)
6022 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
6023 new FieldInitializer (FieldBuilder, initializer));
6025 if (Parent.PartialContainer.Kind == Kind.Struct && (fa & FieldAttributes.Static) == 0 &&
6026 MemberType == Parent.TypeBuilder && !TypeManager.IsBuiltinType (MemberType) && initializer == null) {
6027 Report.Error (523, Location, "Struct member `{0}' causes a cycle in the structure layout",
6028 GetSignatureForError ());
6035 public override string GetSignatureForError ()
6037 string s = base.GetSignatureForError ();
6038 if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
6041 // Undecorate name mangling
6042 int l = s.LastIndexOf ('>');
6043 return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
6046 protected override bool VerifyClsCompliance ()
6048 if (!base.VerifyClsCompliance ())
6051 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6052 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6060 // `set' and `get' accessors are represented with an Accessor.
6062 public class Accessor : IAnonymousHost {
6064 // Null if the accessor is empty, or a Block if not
6066 public const int AllowedModifiers =
6068 Modifiers.PROTECTED |
6069 Modifiers.INTERNAL |
6072 public ToplevelBlock Block;
6073 public Attributes Attributes;
6074 public Location Location;
6075 public int ModFlags;
6077 public ArrayList AnonymousMethods;
6079 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6084 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6087 public void SetYields ()
6092 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6094 if (AnonymousMethods == null)
6095 AnonymousMethods = new ArrayList ();
6096 AnonymousMethods.Add (ame);
6100 // Ooouh Martin, templates are missing here.
6101 // When it will be possible move here a lot of child code and template method type.
6102 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6103 protected MethodData method_data;
6104 protected ToplevelBlock block;
6105 protected ListDictionary declarative_security;
6107 // The accessor are created event if they are not wanted.
6108 // But we need them because their names are reserved.
6109 // Field says whether accessor will be emited or not
6110 public readonly bool IsDummy;
6112 protected readonly string prefix;
6114 ReturnParameter return_attributes;
6116 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6117 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6119 this.prefix = prefix;
6123 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6125 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6126 accessor.Attributes)
6128 this.prefix = prefix;
6129 this.block = accessor.Block;
6132 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6134 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6137 public void UpdateName (InterfaceMemberBase member)
6139 SetMemberName (SetupName (prefix, member, Location));
6142 #region IMethodData Members
6144 public abstract Iterator Iterator {
6148 public ToplevelBlock Block {
6158 public CallingConventions CallingConventions {
6160 return CallingConventions.Standard;
6164 public bool IsExcluded ()
6169 GenericMethod IMethodData.GenericMethod {
6175 public MemberName MethodName {
6181 public Type[] ParameterTypes {
6183 return ParameterInfo.Types;
6187 public abstract Parameters ParameterInfo { get ; }
6188 public abstract Type ReturnType { get; }
6189 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6193 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6195 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6196 a.Type == TypeManager.conditional_attribute_type) {
6197 Report.Error (1667, a.Location,
6198 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6199 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6203 if (a.IsValidSecurityAttribute ()) {
6204 if (declarative_security == null)
6205 declarative_security = new ListDictionary ();
6206 a.ExtractSecurityPermissionSet (declarative_security);
6210 if (a.Target == AttributeTargets.Method) {
6211 method_data.MethodBuilder.SetCustomAttribute (cb);
6215 if (a.Target == AttributeTargets.ReturnValue) {
6216 if (return_attributes == null)
6217 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6219 return_attributes.ApplyAttributeBuilder (a, cb);
6223 ApplyToExtraTarget (a, cb);
6226 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6228 throw new NotSupportedException ("You forgot to define special attribute target handling");
6231 // It is not supported for the accessors
6232 public sealed override bool Define()
6234 throw new NotSupportedException ();
6237 public void Emit (DeclSpace parent)
6239 EmitMethod (parent);
6242 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6243 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6245 if (OptAttributes != null)
6246 OptAttributes.Emit ();
6248 if (declarative_security != null) {
6249 foreach (DictionaryEntry de in declarative_security) {
6250 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6257 protected virtual void EmitMethod (DeclSpace parent)
6259 method_data.Emit (parent);
6262 public override bool EnableOverloadChecks (MemberCore overload)
6264 // This can only happen with indexers and it will
6265 // be catched as indexer difference
6266 if (overload is AbstractPropertyEventMethod)
6269 if (overload is MethodCore) {
6270 caching_flags |= Flags.MethodOverloadsExist;
6276 public override bool IsClsComplianceRequired()
6281 public bool IsDuplicateImplementation (MethodCore method)
6283 if (!MemberName.Equals (method.MemberName))
6286 Type[] param_types = method.ParameterTypes;
6288 if (param_types == null || param_types.Length != ParameterTypes.Length)
6291 for (int i = 0; i < param_types.Length; i++)
6292 if (param_types [i] != ParameterTypes [i])
6295 Report.SymbolRelatedToPreviousError (method);
6296 Report.Error (82, Location, "A member `{0}' is already reserved",
6297 method.GetSignatureForError ());
6301 public override bool IsUsed
6311 public new Location Location {
6313 return base.Location;
6317 public virtual bool ResolveMembers ()
6323 // Represents header string for documentation comment.
6325 public override string DocCommentHeader {
6326 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6329 void IMethodData.EmitExtraSymbolInfo ()
6334 // Properties and Indexers both generate PropertyBuilders, we use this to share
6335 // their common bits.
6337 abstract public class PropertyBase : PropertyBasedMember {
6339 public class GetMethod : PropertyMethod
6341 static string[] attribute_targets = new string [] { "method", "return" };
6343 public GetMethod (PropertyBase method):
6344 base (method, "get_")
6348 public GetMethod (PropertyBase method, Accessor accessor):
6349 base (method, accessor, "get_")
6353 public override MethodBuilder Define (DeclSpace parent)
6355 if (!CheckForDuplications ())
6361 base.Define (parent);
6363 method_data = new MethodData (method, ModFlags, flags, this);
6365 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6368 return method_data.MethodBuilder;
6371 public override Type ReturnType {
6373 return method.MemberType;
6377 public override Parameters ParameterInfo {
6379 return Parameters.EmptyReadOnlyParameters;
6383 public override string[] ValidAttributeTargets {
6385 return attribute_targets;
6390 public class SetMethod : PropertyMethod {
6392 static string[] attribute_targets = new string [] { "method", "param", "return" };
6393 ImplicitParameter param_attr;
6394 protected Parameters parameters;
6396 public SetMethod (PropertyBase method):
6397 base (method, "set_")
6401 public SetMethod (PropertyBase method, Accessor accessor):
6402 base (method, accessor, "set_")
6406 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6408 if (a.Target == AttributeTargets.Parameter) {
6409 if (param_attr == null)
6410 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6412 param_attr.ApplyAttributeBuilder (a, cb);
6416 base.ApplyAttributeBuilder (a, cb);
6419 public override Parameters ParameterInfo {
6421 if (parameters == null)
6422 DefineParameters ();
6427 protected virtual void DefineParameters ()
6429 parameters = Parameters.CreateFullyResolved (
6430 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6433 public override MethodBuilder Define (DeclSpace parent)
6435 if (!CheckForDuplications ())
6441 base.Define (parent);
6443 method_data = new MethodData (method, ModFlags, flags, this);
6445 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6448 return method_data.MethodBuilder;
6451 public override Type ReturnType {
6453 return TypeManager.void_type;
6457 public override string[] ValidAttributeTargets {
6459 return attribute_targets;
6464 static string[] attribute_targets = new string [] { "property" };
6466 public abstract class PropertyMethod : AbstractPropertyEventMethod
6468 protected readonly PropertyBase method;
6469 protected MethodAttributes flags;
6471 ArrayList anonymous_methods;
6474 public PropertyMethod (PropertyBase method, string prefix)
6475 : base (method, prefix)
6477 this.method = method;
6480 public PropertyMethod (PropertyBase method, Accessor accessor,
6482 : base (method, accessor, prefix)
6484 this.method = method;
6485 this.ModFlags = accessor.ModFlags;
6486 yields = accessor.Yields;
6487 anonymous_methods = accessor.AnonymousMethods;
6489 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6490 Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6494 public override Iterator Iterator {
6495 get { return iterator; }
6498 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6500 if (a.IsInternalMethodImplAttribute) {
6501 method.is_external_implementation = true;
6504 base.ApplyAttributeBuilder (a, cb);
6507 public override AttributeTargets AttributeTargets {
6509 return AttributeTargets.Method;
6513 public override bool IsClsComplianceRequired ()
6515 return method.IsClsComplianceRequired ();
6518 public override bool ResolveMembers ()
6521 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6522 if (iterator == null)
6526 if (anonymous_methods != null) {
6527 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6528 if (!ame.CreateAnonymousHelpers ())
6536 public virtual MethodBuilder Define (DeclSpace parent)
6538 TypeContainer container = parent.PartialContainer;
6541 // Check for custom access modifier
6543 if ((ModFlags & Modifiers.Accessibility) == 0) {
6544 ModFlags |= method.ModFlags;
6545 flags = method.flags;
6547 if (container.Kind == Kind.Interface)
6548 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6549 GetSignatureForError ());
6551 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6552 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6555 CheckModifiers (ModFlags);
6556 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6557 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6558 flags = Modifiers.MethodAttr (ModFlags);
6559 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6562 CheckAbstractAndExtern (block != null);
6566 public bool HasCustomAccessModifier
6569 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6573 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6575 return new EmitContext (method,
6576 ds, method.ds, method.Location, ig, ReturnType,
6577 method.ModFlags, false);
6580 public override ObsoleteAttribute GetObsoleteAttribute ()
6582 return method.GetObsoleteAttribute ();
6585 public override string GetSignatureForError()
6587 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6590 void CheckModifiers (int modflags)
6592 modflags &= Modifiers.Accessibility;
6594 int mflags = method.ModFlags & Modifiers.Accessibility;
6596 if ((mflags & Modifiers.PUBLIC) != 0) {
6597 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6599 else if ((mflags & Modifiers.PROTECTED) != 0) {
6600 if ((mflags & Modifiers.INTERNAL) != 0)
6601 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6603 flags |= Modifiers.PRIVATE;
6605 else if ((mflags & Modifiers.INTERNAL) != 0)
6606 flags |= Modifiers.PRIVATE;
6608 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6609 Report.Error (273, Location,
6610 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6611 GetSignatureForError (), method.GetSignatureForError ());
6615 protected bool CheckForDuplications ()
6617 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6620 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6624 public PropertyMethod Get, Set;
6625 public PropertyBuilder PropertyBuilder;
6626 public MethodBuilder GetBuilder, SetBuilder;
6628 protected bool define_set_first = false;
6630 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6631 int allowed_mod, bool is_iface, MemberName name,
6632 Attributes attrs, bool define_set_first)
6633 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6635 this.define_set_first = define_set_first;
6638 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6640 if (a.HasSecurityAttribute) {
6641 a.Error_InvalidSecurityParent ();
6645 PropertyBuilder.SetCustomAttribute (cb);
6648 public override AttributeTargets AttributeTargets {
6650 return AttributeTargets.Property;
6654 public override bool Define ()
6659 if (!IsTypePermitted ())
6665 protected override bool DoDefine ()
6667 if (!base.DoDefine ())
6671 // Accessors modifiers check
6673 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6674 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6675 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6676 GetSignatureForError ());
6680 if ((Get.IsDummy || Set.IsDummy)
6681 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6682 Report.Error (276, Location,
6683 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6684 GetSignatureForError ());
6689 if (MemberType.IsGenericParameter)
6693 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6694 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6703 GetBuilder = Get.Define (Parent);
6704 return (Get.IsDummy) ? true : GetBuilder != null;
6707 bool DefineSet (bool define)
6712 SetBuilder = Set.Define (Parent);
6713 return (Set.IsDummy) ? true : SetBuilder != null;
6716 protected bool DefineAccessors ()
6718 return DefineSet (define_set_first) &&
6720 DefineSet (!define_set_first);
6723 protected abstract PropertyInfo ResolveBaseProperty ();
6725 // TODO: rename to Resolve......
6726 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6728 PropertyInfo base_property = ResolveBaseProperty ();
6729 if (base_property == null)
6732 base_ret_type = base_property.PropertyType;
6733 MethodInfo get_accessor = base_property.GetGetMethod (true);
6734 MethodInfo set_accessor = base_property.GetSetMethod (true);
6735 MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6737 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6738 if (Get != null && !Get.IsDummy && get_accessor == null) {
6739 Report.SymbolRelatedToPreviousError (base_property);
6740 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6743 if (Set != null && !Set.IsDummy && set_accessor == null) {
6744 Report.SymbolRelatedToPreviousError (base_property);
6745 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6749 // Check base class accessors access
6752 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6753 get_accessor_access = set_accessor_access = 0;
6754 if ((ModFlags & Modifiers.NEW) == 0) {
6755 if (get_accessor != null) {
6756 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6757 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6759 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6760 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6763 if (set_accessor != null) {
6764 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6765 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6767 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6768 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6773 // When one accessor does not exist and property hides base one
6774 // we need to propagate this upwards
6775 if (set_accessor == null)
6776 set_accessor = get_accessor;
6779 // Get the less restrictive access
6781 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6784 public override void Emit ()
6787 // The PropertyBuilder can be null for explicit implementations, in that
6788 // case, we do not actually emit the ".property", so there is nowhere to
6789 // put the attribute
6791 if (PropertyBuilder != null && OptAttributes != null)
6792 OptAttributes.Emit ();
6804 /// Tests whether accessors are not in collision with some method (CS0111)
6806 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6808 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6811 public override bool IsUsed
6817 return Get.IsUsed | Set.IsUsed;
6821 protected override void SetMemberName (MemberName new_name)
6823 base.SetMemberName (new_name);
6825 Get.UpdateName (this);
6826 Set.UpdateName (this);
6829 public override string[] ValidAttributeTargets {
6831 return attribute_targets;
6836 // Represents header string for documentation comment.
6838 public override string DocCommentHeader {
6839 get { return "P:"; }
6843 public class Property : PropertyBase {
6844 const int AllowedModifiers =
6847 Modifiers.PROTECTED |
6848 Modifiers.INTERNAL |
6852 Modifiers.OVERRIDE |
6853 Modifiers.ABSTRACT |
6856 Modifiers.METHOD_YIELDS |
6859 const int AllowedInterfaceModifiers =
6862 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6865 Field field = new Field (
6867 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6868 "<" + Name + ">k__BackingField", null, Location);
6869 ((TypeContainer)Parent).AddField (field);
6872 get_block.Block = new ToplevelBlock (block, null, Location);
6873 Return r = new Return (new SimpleName(field.Name, Location), Location);
6874 get_block.Block.AddStatement (r);
6875 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6878 Parameters parameters = new Parameters (new Parameter (type_name, "value", Parameter.Modifier.NONE, null, Location));
6879 set_block.Block = new ToplevelBlock (block, parameters, Location);
6880 Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6881 set_block.Block.AddStatement (new StatementExpression(a));
6882 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6885 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6886 MemberName name, Attributes attrs, Accessor get_block,
6887 Accessor set_block, bool define_set_first)
6888 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6889 define_set_first, null)
6893 public Property (DeclSpace parent, FullNamedExpression type, int mod, bool is_iface,
6894 MemberName name, Attributes attrs, Accessor get_block,
6895 Accessor set_block, bool define_set_first, Block current_block)
6896 : base (parent, type, mod,
6897 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6898 is_iface, name, attrs, define_set_first)
6900 if (!is_iface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6901 get_block != null && get_block.Block == null &&
6902 set_block != null && set_block.Block == null) {
6903 if (RootContext.Version <= LanguageVersion.ISO_2)
6904 Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6906 CreateAutomaticProperty (current_block, get_block, set_block);
6909 if (get_block == null)
6910 Get = new GetMethod (this);
6912 Get = new GetMethod (this, get_block);
6914 if (set_block == null)
6915 Set = new SetMethod (this);
6917 Set = new SetMethod (this, set_block);
6920 public override bool Define ()
6922 if (!DoDefineBase ())
6925 if (!base.Define ())
6931 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6933 if (!DefineAccessors ())
6936 // FIXME - PropertyAttributes.HasDefault ?
6938 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6939 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6942 PropertyBuilder.SetGetMethod (GetBuilder);
6943 Parent.MemberCache.AddMember (GetBuilder, Get);
6947 PropertyBuilder.SetSetMethod (SetBuilder);
6948 Parent.MemberCache.AddMember (SetBuilder, Set);
6951 TypeManager.RegisterProperty (PropertyBuilder, this);
6952 Parent.MemberCache.AddMember (PropertyBuilder, this);
6956 protected override PropertyInfo ResolveBaseProperty ()
6958 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6959 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6964 /// Gigantic workaround for lameness in SRE follows :
6965 /// This class derives from EventInfo and attempts to basically
6966 /// wrap around the EventBuilder so that FindMembers can quickly
6967 /// return this in it search for members
6969 public class MyEventBuilder : EventInfo {
6972 // We use this to "point" to our Builder which is
6973 // not really a MemberInfo
6975 EventBuilder MyBuilder;
6978 // We "catch" and wrap these methods
6980 MethodInfo raise, remove, add;
6982 EventAttributes attributes;
6983 Type declaring_type, reflected_type, event_type;
6988 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6990 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6992 // And now store the values in our own fields.
6994 declaring_type = type_builder;
6996 reflected_type = type_builder;
6998 attributes = event_attr;
7001 this.event_type = event_type;
7005 // Methods that you have to override. Note that you only need
7006 // to "implement" the variants that take the argument (those are
7007 // the "abstract" methods, the others (GetAddMethod()) are
7010 public override MethodInfo GetAddMethod (bool nonPublic)
7015 public override MethodInfo GetRemoveMethod (bool nonPublic)
7020 public override MethodInfo GetRaiseMethod (bool nonPublic)
7026 // These methods make "MyEventInfo" look like a Builder
7028 public void SetRaiseMethod (MethodBuilder raiseMethod)
7030 raise = raiseMethod;
7031 MyBuilder.SetRaiseMethod (raiseMethod);
7034 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7036 remove = removeMethod;
7037 MyBuilder.SetRemoveOnMethod (removeMethod);
7040 public void SetAddOnMethod (MethodBuilder addMethod)
7043 MyBuilder.SetAddOnMethod (addMethod);
7046 public void SetCustomAttribute (CustomAttributeBuilder cb)
7048 MyBuilder.SetCustomAttribute (cb);
7051 public override object [] GetCustomAttributes (bool inherit)
7053 // FIXME : There's nothing which can be seemingly done here because
7054 // we have no way of getting at the custom attribute objects of the
7059 public override object [] GetCustomAttributes (Type t, bool inherit)
7061 // FIXME : Same here !
7065 public override bool IsDefined (Type t, bool b)
7070 public override EventAttributes Attributes {
7076 public override string Name {
7082 public override Type DeclaringType {
7084 return declaring_type;
7088 public override Type ReflectedType {
7090 return reflected_type;
7094 public Type EventType {
7100 public void SetUsed ()
7102 if (my_event != null) {
7103 // my_event.SetAssigned ();
7104 my_event.SetMemberIsUsed ();
7110 /// For case when event is declared like property (with add and remove accessors).
7112 public class EventProperty: Event {
7113 abstract class AEventPropertyAccessor : AEventAccessor
7115 readonly ArrayList anonymous_methods;
7117 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7118 base (method, accessor, prefix)
7120 this.anonymous_methods = accessor.AnonymousMethods;
7123 public override MethodBuilder Define (DeclSpace ds)
7125 CheckAbstractAndExtern (block != null);
7126 return base.Define (ds);
7129 public override string GetSignatureForError ()
7131 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7134 public override bool ResolveMembers ()
7136 if (anonymous_methods == null)
7139 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7140 if (!ame.CreateAnonymousHelpers ())
7149 sealed class AddDelegateMethod: AEventPropertyAccessor
7151 public AddDelegateMethod (Event method, Accessor accessor):
7152 base (method, accessor, "add_")
7156 protected override MethodInfo DelegateMethodInfo {
7158 return TypeManager.delegate_combine_delegate_delegate;
7163 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7165 public RemoveDelegateMethod (Event method, Accessor accessor):
7166 base (method, accessor, "remove_")
7170 protected override MethodInfo DelegateMethodInfo {
7172 return TypeManager.delegate_remove_delegate_delegate;
7178 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7180 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
7181 bool is_iface, MemberName name,
7182 Attributes attrs, Accessor add, Accessor remove)
7183 : base (parent, type, mod_flags, is_iface, name, attrs)
7185 Add = new AddDelegateMethod (this, add);
7186 Remove = new RemoveDelegateMethod (this, remove);
7189 public override bool Define()
7191 if (!base.Define ())
7198 public override string[] ValidAttributeTargets {
7200 return attribute_targets;
7206 /// Event is declared like field.
7208 public class EventField : Event {
7209 abstract class EventFieldAccessor : AEventAccessor
7211 protected EventFieldAccessor (Event method, string prefix)
7212 : base (method, prefix)
7216 protected override void EmitMethod(DeclSpace parent)
7218 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7221 MethodBuilder mb = method_data.MethodBuilder;
7222 ILGenerator ig = mb.GetILGenerator ();
7224 // TODO: because we cannot use generics yet
7225 FieldInfo field_info = ((EventField)method).FieldBuilder;
7227 if (parent is Class) {
7228 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7231 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7232 ig.Emit (OpCodes.Ldsfld, field_info);
7233 ig.Emit (OpCodes.Ldarg_0);
7234 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7235 ig.Emit (OpCodes.Castclass, method.MemberType);
7236 ig.Emit (OpCodes.Stsfld, field_info);
7238 ig.Emit (OpCodes.Ldarg_0);
7239 ig.Emit (OpCodes.Ldarg_0);
7240 ig.Emit (OpCodes.Ldfld, field_info);
7241 ig.Emit (OpCodes.Ldarg_1);
7242 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7243 ig.Emit (OpCodes.Castclass, method.MemberType);
7244 ig.Emit (OpCodes.Stfld, field_info);
7246 ig.Emit (OpCodes.Ret);
7250 sealed class AddDelegateMethod: EventFieldAccessor
7252 public AddDelegateMethod (Event method):
7253 base (method, "add_")
7257 protected override MethodInfo DelegateMethodInfo {
7259 return TypeManager.delegate_combine_delegate_delegate;
7264 sealed class RemoveDelegateMethod: EventFieldAccessor
7266 public RemoveDelegateMethod (Event method):
7267 base (method, "remove_")
7271 protected override MethodInfo DelegateMethodInfo {
7273 return TypeManager.delegate_remove_delegate_delegate;
7279 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7280 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7282 public FieldBuilder FieldBuilder;
7283 public Expression Initializer;
7285 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags,
7286 bool is_iface, MemberName name,
7288 : base (parent, type, mod_flags, is_iface, name, attrs)
7290 Add = new AddDelegateMethod (this);
7291 Remove = new RemoveDelegateMethod (this);
7294 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7296 if (a.Target == AttributeTargets.Field) {
7297 FieldBuilder.SetCustomAttribute (cb);
7301 if (a.Target == AttributeTargets.Method) {
7302 int errors = Report.Errors;
7303 Add.ApplyAttributeBuilder (a, cb);
7304 if (errors == Report.Errors)
7305 Remove.ApplyAttributeBuilder (a, cb);
7309 base.ApplyAttributeBuilder (a, cb);
7312 public override bool Define()
7314 if (!base.Define ())
7320 // FIXME: We are unable to detect whether generic event is used because
7321 // we are using FieldExpr instead of EventExpr for event access in that
7322 // case. When this issue will be fixed this hack can be removed.
7323 if (TypeManager.IsGenericType (MemberType))
7326 if (Add.IsInterfaceImplementation)
7329 FieldBuilder = Parent.TypeBuilder.DefineField (
7331 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7332 TypeManager.RegisterEventField (EventBuilder, this);
7334 if (Initializer != null) {
7335 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7336 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7337 GetSignatureForError ());
7341 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7342 new FieldInitializer (FieldBuilder, Initializer));
7348 public override string[] ValidAttributeTargets
7351 return IsInterface ? attribute_targets_interface : attribute_targets;
7356 public abstract class Event : PropertyBasedMember {
7357 public abstract class AEventAccessor : AbstractPropertyEventMethod
7359 protected readonly Event method;
7360 ImplicitParameter param_attr;
7362 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7364 protected AEventAccessor (Event method, string prefix)
7365 : base (method, prefix)
7367 this.method = method;
7368 this.ModFlags = method.ModFlags;
7371 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7372 : base (method, accessor, prefix)
7374 this.method = method;
7375 this.ModFlags = method.ModFlags;
7378 public override Iterator Iterator {
7379 get { return null; }
7382 public bool IsInterfaceImplementation {
7383 get { return method_data.implementing != null; }
7386 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7388 if (a.IsInternalMethodImplAttribute) {
7389 method.is_external_implementation = true;
7392 base.ApplyAttributeBuilder (a, cb);
7395 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7397 if (a.Target == AttributeTargets.Parameter) {
7398 if (param_attr == null)
7399 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7401 param_attr.ApplyAttributeBuilder (a, cb);
7405 base.ApplyAttributeBuilder (a, cb);
7408 public override AttributeTargets AttributeTargets {
7410 return AttributeTargets.Method;
7414 public override bool IsClsComplianceRequired ()
7416 return method.IsClsComplianceRequired ();
7419 public virtual MethodBuilder Define (DeclSpace parent)
7421 method_data = new MethodData (method, method.ModFlags,
7422 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7424 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7427 MethodBuilder mb = method_data.MethodBuilder;
7428 ParameterInfo.ApplyAttributes (mb);
7432 protected abstract MethodInfo DelegateMethodInfo { get; }
7434 public override Type ReturnType {
7436 return TypeManager.void_type;
7440 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7442 return new EmitContext (
7443 ds, method.Parent, Location, ig, ReturnType,
7444 method.ModFlags, false);
7447 public override ObsoleteAttribute GetObsoleteAttribute ()
7449 return method.GetObsoleteAttribute ();
7452 public override string[] ValidAttributeTargets {
7454 return attribute_targets;
7458 public override Parameters ParameterInfo {
7460 return method.parameters;
7466 const int AllowedModifiers =
7469 Modifiers.PROTECTED |
7470 Modifiers.INTERNAL |
7475 Modifiers.OVERRIDE |
7477 Modifiers.ABSTRACT |
7480 const int AllowedInterfaceModifiers =
7483 public AEventAccessor Add, Remove;
7484 public MyEventBuilder EventBuilder;
7485 public MethodBuilder AddBuilder, RemoveBuilder;
7487 Parameters parameters;
7489 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags,
7490 bool is_iface, MemberName name, Attributes attrs)
7491 : base (parent, null, type, mod_flags,
7492 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7497 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7499 if ((a.HasSecurityAttribute)) {
7500 a.Error_InvalidSecurityParent ();
7504 EventBuilder.SetCustomAttribute (cb);
7507 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7509 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7512 public override AttributeTargets AttributeTargets {
7514 return AttributeTargets.Event;
7518 public override bool Define ()
7520 if (!DoDefineBase ())
7526 if (!TypeManager.IsDelegateType (MemberType)) {
7527 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7531 parameters = Parameters.CreateFullyResolved (
7532 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7537 if (TypeManager.delegate_combine_delegate_delegate == null) {
7538 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7539 TypeManager.delegate_type, "Combine", Location,
7540 TypeManager.delegate_type, TypeManager.delegate_type);
7542 if (TypeManager.delegate_remove_delegate_delegate == null) {
7543 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7544 TypeManager.delegate_type, "Remove", Location,
7545 TypeManager.delegate_type, TypeManager.delegate_type);
7549 // Now define the accessors
7552 AddBuilder = Add.Define (Parent);
7553 if (AddBuilder == null)
7556 RemoveBuilder = Remove.Define (Parent);
7557 if (RemoveBuilder == null)
7560 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7561 EventBuilder.SetAddOnMethod (AddBuilder);
7562 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7564 Parent.MemberCache.AddMember (EventBuilder, this);
7565 Parent.MemberCache.AddMember (AddBuilder, Add);
7566 Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7571 public override void Emit ()
7573 if (OptAttributes != null) {
7574 OptAttributes.Emit ();
7578 Remove.Emit (Parent);
7583 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7585 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7586 Parent.TypeBuilder, Name);
7591 ParameterData pd = TypeManager.GetParameterData (mi);
7592 base_ret_type = pd.ParameterType (0);
7597 // Represents header string for documentation comment.
7599 public override string DocCommentHeader {
7600 get { return "E:"; }
7605 public class Indexer : PropertyBase
7607 class GetIndexerMethod : GetMethod
7609 public GetIndexerMethod (PropertyBase method):
7614 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7615 base (method, accessor)
7619 public override bool EnableOverloadChecks (MemberCore overload)
7621 if (base.EnableOverloadChecks (overload)) {
7622 overload.caching_flags |= Flags.MethodOverloadsExist;
7629 public override Parameters ParameterInfo {
7631 return ((Indexer)method).parameters;
7636 class SetIndexerMethod: SetMethod
7638 public SetIndexerMethod (PropertyBase method):
7643 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7644 base (method, accessor)
7648 protected override void DefineParameters ()
7650 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7651 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7654 public override bool EnableOverloadChecks (MemberCore overload)
7656 if (base.EnableOverloadChecks (overload)) {
7657 overload.caching_flags |= Flags.MethodOverloadsExist;
7665 const int AllowedModifiers =
7668 Modifiers.PROTECTED |
7669 Modifiers.INTERNAL |
7673 Modifiers.OVERRIDE |
7678 const int AllowedInterfaceModifiers =
7681 public readonly Parameters parameters;
7683 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7684 bool is_iface, Parameters parameters, Attributes attrs,
7685 Accessor get_block, Accessor set_block, bool define_set_first)
7686 : base (parent, type, mod,
7687 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7688 is_iface, name, attrs, define_set_first)
7690 if (type == TypeManager.system_void_expr)
7691 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7693 this.parameters = parameters;
7695 if (get_block == null)
7696 Get = new GetIndexerMethod (this);
7698 Get = new GetIndexerMethod (this, get_block);
7700 if (set_block == null)
7701 Set = new SetIndexerMethod (this);
7703 Set = new SetIndexerMethod (this, set_block);
7706 public override bool Define ()
7708 if (!DoDefineBase ())
7711 if (!base.Define ())
7714 if (!DefineParameters (parameters))
7717 if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7718 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7719 if (indexer_attr != null) {
7720 // Remove the attribute from the list because it is not emitted
7721 OptAttributes.Attrs.Remove (indexer_attr);
7723 string name = indexer_attr.GetIndexerAttributeValue ();
7729 if (IsExplicitImpl) {
7730 Report.Error (415, indexer_attr.Location,
7731 "The `IndexerName' attribute is valid only on an " +
7732 "indexer that is not an explicit interface member declaration");
7736 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7737 Report.Error (609, indexer_attr.Location,
7738 "Cannot set the `IndexerName' attribute on an indexer marked override");
7744 if (InterfaceType != null) {
7745 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7746 if (base_IndexerName != Name)
7747 ShortName = base_IndexerName;
7750 if (!Parent.PartialContainer.AddMember (this) ||
7751 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7758 if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
7759 if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
7763 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7765 if (!DefineAccessors ())
7769 // Setup iterator if we are one
7770 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7771 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7772 if (iterator == null)
7778 // Now name the parameters
7780 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7781 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.Types);
7784 PropertyBuilder.SetGetMethod (GetBuilder);
7785 Parent.MemberCache.AddMember (GetBuilder, Get);
7789 PropertyBuilder.SetSetMethod (SetBuilder);
7790 Parent.MemberCache.AddMember (SetBuilder, Set);
7793 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7794 Parent.MemberCache.AddMember (PropertyBuilder, this);
7798 public override bool EnableOverloadChecks (MemberCore overload)
7800 if (overload is Indexer) {
7801 caching_flags |= Flags.MethodOverloadsExist;
7808 public override string GetDocCommentName (DeclSpace ds)
7810 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7813 public override string GetSignatureForError ()
7815 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7816 if (MemberName.Left != null) {
7818 sb.Append (MemberName.Left.GetSignatureForError ());
7821 sb.Append (".this");
7822 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7823 return sb.ToString ();
7826 protected override PropertyInfo ResolveBaseProperty ()
7828 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7829 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7832 protected override bool VerifyClsCompliance ()
7834 if (!base.VerifyClsCompliance ())
7837 parameters.VerifyClsCompliance ();
7842 public class Operator : MethodOrOperator, IAnonymousHost {
7844 const int AllowedModifiers =
7850 public enum OpType : byte {
7860 // Unary and Binary operators
7883 // Implicit and Explicit
7887 // Just because of enum
7891 public readonly OpType OperatorType;
7893 static readonly string [] [] names;
7897 names = new string[(int)OpType.TOP][];
7898 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7899 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7900 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7901 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7902 names [(int) OpType.True] = new string [] { "true", "op_True" };
7903 names [(int) OpType.False] = new string [] { "false", "op_False" };
7904 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7905 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7906 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7907 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7908 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7909 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7910 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7911 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7912 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7913 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7914 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7915 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7916 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7917 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7918 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7919 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7920 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7921 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7922 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7923 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7926 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7927 int mod_flags, Parameters parameters,
7928 ToplevelBlock block, Attributes attrs, Location loc)
7929 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7930 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7932 OperatorType = type;
7936 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7938 if (a.Type == TypeManager.conditional_attribute_type) {
7939 Error_ConditionalAttributeIsNotValid ();
7943 base.ApplyAttributeBuilder (a, cb);
7946 public override bool Define ()
7948 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7949 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7950 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7954 if (!base.Define ())
7957 // imlicit and explicit operator of same types are not allowed
7958 if (OperatorType == OpType.Explicit)
7959 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7960 else if (OperatorType == OpType.Implicit)
7961 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7963 if (MemberType == TypeManager.void_type) {
7964 Report.Error (590, Location, "User-defined operators cannot return void");
7968 Type declaring_type = MethodData.DeclaringType;
7969 Type return_type = MemberType;
7970 Type first_arg_type = ParameterTypes [0];
7972 Type first_arg_type_unwrap = first_arg_type;
7973 if (TypeManager.IsNullableType (first_arg_type))
7974 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7976 Type return_type_unwrap = return_type;
7977 if (TypeManager.IsNullableType (return_type))
7978 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
7981 // Rules for conversion operators
7983 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7984 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7985 Report.Error (555, Location,
7986 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7991 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7992 conv_type = first_arg_type;
7993 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7994 conv_type = return_type;
7996 Report.Error (556, Location,
7997 "User-defined conversion must convert to or from the enclosing type");
8002 // Because IsInterface and IsClass are not supported
8004 if (!TypeManager.IsGenericParameter (conv_type)) {
8005 if (conv_type.IsInterface) {
8006 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8007 GetSignatureForError ());
8011 if (conv_type.IsClass) {
8012 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
8013 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
8014 GetSignatureForError ());
8018 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
8019 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
8020 GetSignatureForError ());
8025 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8026 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8027 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");
8030 } else if (Parameters.Count == 1) {
8031 // Checks for Unary operators
8033 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8034 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8035 Report.Error (448, Location,
8036 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8039 if (first_arg_type != declaring_type) {
8041 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8046 if (first_arg_type != declaring_type){
8049 "The parameter of a unary operator must be the " +
8054 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8055 if (return_type != TypeManager.bool_type){
8058 "The return type of operator True or False " +
8065 // Checks for Binary operators
8067 if (first_arg_type != declaring_type &&
8068 ParameterTypes [1] != declaring_type){
8071 "One of the parameters of a binary operator must " +
8072 "be the containing type");
8080 protected override bool DoDefine ()
8082 if (!base.DoDefine ())
8085 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8089 public override void Emit ()
8093 Parameters.ApplyAttributes (MethodBuilder);
8096 // abstract or extern methods have no bodies
8098 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8102 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8103 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8105 ec = CreateEmitContext (Parent, null);
8107 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8108 ec.EmitTopBlock (this, Block);
8111 source.CloseMethod ();
8116 // Operator cannot be override
8117 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8122 public static string GetName (OpType ot)
8124 return names [(int) ot] [0];
8127 public static string GetName (string metadata_name)
8129 for (int i = 0; i < names.Length; ++i) {
8130 if (names [i] [1] == metadata_name)
8131 return names [i] [0];
8136 public static string GetMetadataName (OpType ot)
8138 return names [(int) ot] [1];
8141 public static string GetMetadataName (string name)
8143 for (int i = 0; i < names.Length; ++i) {
8144 if (names [i] [0] == name)
8145 return names [i] [1];
8150 public OpType GetMatchingOperator ()
8152 switch (OperatorType) {
8153 case OpType.Equality:
8154 return OpType.Inequality;
8155 case OpType.Inequality:
8156 return OpType.Equality;
8158 return OpType.False;
8161 case OpType.GreaterThan:
8162 return OpType.LessThan;
8163 case OpType.LessThan:
8164 return OpType.GreaterThan;
8165 case OpType.GreaterThanOrEqual:
8166 return OpType.LessThanOrEqual;
8167 case OpType.LessThanOrEqual:
8168 return OpType.GreaterThanOrEqual;
8174 public override string GetSignatureForError ()
8176 StringBuilder sb = new StringBuilder ();
8177 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8178 sb.AppendFormat ("{0}.{1} operator {2}",
8179 Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
8182 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8185 sb.Append (Parameters.GetSignatureForError ());
8186 return sb.ToString ();
8191 // This is used to compare method signatures
8193 struct MethodSignature {
8195 public Type RetType;
8196 public Type [] Parameters;
8199 /// This delegate is used to extract methods which have the
8200 /// same signature as the argument
8202 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8204 public MethodSignature (string name, Type ret_type, Type [] parameters)
8209 if (parameters == null)
8210 Parameters = Type.EmptyTypes;
8212 Parameters = parameters;
8215 public override string ToString ()
8218 if (Parameters.Length != 0){
8219 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8220 for (int i = 0; i < Parameters.Length; i++){
8221 sb.Append (Parameters [i]);
8222 if (i+1 < Parameters.Length)
8225 pars = sb.ToString ();
8228 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8231 public override int GetHashCode ()
8233 return Name.GetHashCode ();
8236 public override bool Equals (Object o)
8238 MethodSignature other = (MethodSignature) o;
8240 if (other.Name != Name)
8243 if (other.RetType != RetType)
8246 if (Parameters == null){
8247 if (other.Parameters == null)
8252 if (other.Parameters == null)
8255 int c = Parameters.Length;
8256 if (other.Parameters.Length != c)
8259 for (int i = 0; i < c; i++)
8260 if (other.Parameters [i] != Parameters [i])
8266 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8268 MethodSignature sig = (MethodSignature) filter_criteria;
8270 if (m.Name != sig.Name)
8274 MethodInfo mi = m as MethodInfo;
8275 PropertyInfo pi = m as PropertyInfo;
8278 ReturnType = mi.ReturnType;
8279 else if (pi != null)
8280 ReturnType = pi.PropertyType;
8285 // we use sig.RetType == null to mean `do not check the
8286 // method return value.
8288 if (sig.RetType != null) {
8289 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8295 args = TypeManager.GetParameterData (mi).Types;
8297 args = TypeManager.GetArgumentTypes (pi);
8298 Type [] sigp = sig.Parameters;
8300 if (args.Length != sigp.Length)
8303 for (int i = args.Length - 1; i >= 0; i--)
8304 if (!TypeManager.IsEqual (args [i], sigp [i]))