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 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 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.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 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 // Operator pair checking
106 public Type ret_type;
107 public Type type1, type2;
109 public Operator.OpType ot;
111 public OperatorEntry (int f, Operator o)
115 ret_type = o.MemberType;
116 Type [] pt = o.ParameterTypes;
123 public override int GetHashCode ()
125 return ret_type.GetHashCode ();
128 public override bool Equals (object o)
130 OperatorEntry other = (OperatorEntry) o;
132 if (other.ret_type != ret_type)
134 if (other.type1 != type1)
136 if (other.type2 != type2)
143 // Checks that some operators come in pairs:
149 // They are matched based on the return type and the argument types
151 void CheckPairedOperators ()
153 IDictionary pairs = new HybridDictionary ();
154 Operator true_op = null;
155 Operator false_op = null;
156 bool has_equality_or_inequality = false;
158 // Register all the operators we care about.
159 foreach (Operator op in this){
162 // Skip erroneous code.
163 if (op.MethodBuilder == null)
166 switch (op.OperatorType){
167 case Operator.OpType.Equality:
169 has_equality_or_inequality = true;
171 case Operator.OpType.Inequality:
173 has_equality_or_inequality = true;
176 case Operator.OpType.True:
179 case Operator.OpType.False:
183 case Operator.OpType.GreaterThan:
185 case Operator.OpType.LessThan:
188 case Operator.OpType.GreaterThanOrEqual:
190 case Operator.OpType.LessThanOrEqual:
196 OperatorEntry oe = new OperatorEntry (reg, op);
198 object o = pairs [oe];
202 oe = (OperatorEntry) o;
207 if (true_op != null){
208 if (false_op == null)
209 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
210 true_op.GetSignatureForError ());
211 } else if (false_op != null)
212 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
213 false_op.GetSignatureForError ());
216 // Look for the mistakes.
218 foreach (DictionaryEntry de in pairs){
219 OperatorEntry oe = (OperatorEntry) de.Key;
226 case Operator.OpType.Equality:
229 case Operator.OpType.Inequality:
232 case Operator.OpType.GreaterThan:
235 case Operator.OpType.LessThan:
238 case Operator.OpType.GreaterThanOrEqual:
241 case Operator.OpType.LessThanOrEqual:
245 Report.Error (216, oe.op.Location,
246 "The operator `{0}' requires a matching operator `{1}' to also be defined",
247 oe.op.GetSignatureForError (), s);
250 if (has_equality_or_inequality && Report.WarningLevel > 2) {
251 if (container.Methods == null || !container.HasEquals)
252 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
254 if (container.Methods == null || !container.HasGetHashCode)
255 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
259 public override void DefineContainerMembers ()
261 base.DefineContainerMembers ();
262 CheckPairedOperators ();
273 // Whether this is a struct, class or interface
274 public readonly Kind Kind;
276 // Holds a list of classes and structures
277 protected ArrayList types;
279 MemberCoreArrayList ordered_explicit_member_list;
280 MemberCoreArrayList ordered_member_list;
282 // Holds the list of properties
283 MemberCoreArrayList properties;
285 // Holds the list of delegates
286 MemberCoreArrayList delegates;
288 // Holds the list of constructors
289 protected MemberCoreArrayList instance_constructors;
291 // Holds the list of fields
292 MemberCoreArrayList fields;
294 // Holds a list of fields that have initializers
295 protected ArrayList initialized_fields;
297 // Holds a list of static fields that have initializers
298 protected ArrayList initialized_static_fields;
300 // Holds the list of constants
301 MemberCoreArrayList constants;
303 // Holds the methods.
304 MemberCoreArrayList methods;
307 protected MemberCoreArrayList events;
309 // Holds the indexers
312 // Holds the operators
313 MemberCoreArrayList operators;
315 // Holds the compiler generated classes
316 ArrayList compiler_generated;
319 // Pointers to the default constructor and the default static constructor
321 protected Constructor default_constructor;
322 protected Constructor default_static_constructor;
325 // Points to the first non-static field added to the container.
327 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
328 // and the first one's as good as any.
330 FieldBase first_nonstatic_field = null;
333 // This one is computed after we can distinguish interfaces
334 // from classes from the arraylist `type_bases'
337 TypeExpr[] iface_exprs;
340 ArrayList type_bases;
342 bool members_resolved;
343 bool members_resolved_ok;
344 bool members_defined;
345 bool members_defined_ok;
347 // The interfaces we implement.
348 protected Type[] ifaces;
350 // The base member cache and our member cache
351 MemberCache base_cache;
352 MemberCache member_cache;
354 public const string DefaultIndexerName = "Item";
356 private bool seen_normal_indexers = false;
357 private string indexer_name = DefaultIndexerName;
359 private CachedMethods cached_method;
362 GenericTypeParameterBuilder[] gen_params;
365 ArrayList partial_parts;
368 /// The pending methods that need to be implemented
369 // (interfaces or abstract methods)
371 PendingImplementation pending;
373 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
374 Attributes attrs, Kind kind)
375 : base (ns, parent, name, attrs)
377 if (parent != null && parent.NamespaceEntry != ns)
378 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
381 this.PartialContainer = this;
384 public bool AddMember (MemberCore symbol)
386 return AddToContainer (symbol, symbol.MemberName.MethodName);
389 protected virtual bool AddMemberType (DeclSpace ds)
391 return AddToContainer (ds, ds.Basename);
394 public void AddConstant (Const constant)
396 if (!AddMember (constant))
399 if (constants == null)
400 constants = new MemberCoreArrayList ();
402 constants.Add (constant);
405 public TypeContainer AddTypeContainer (TypeContainer tc)
407 if (!AddMemberType (tc))
411 types = new MemberCoreArrayList ();
417 public virtual TypeContainer AddPartial (TypeContainer next_part)
419 return AddPartial (next_part, next_part.Basename);
422 protected TypeContainer AddPartial (TypeContainer next_part, string name)
424 next_part.ModFlags |= Modifiers.PARTIAL;
425 TypeContainer tc = defined_names [name] as TypeContainer;
428 return AddTypeContainer (next_part);
430 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
431 Report.SymbolRelatedToPreviousError (tc);
432 Error_MissingPartialModifier (next_part);
436 if (tc.Kind != next_part.Kind) {
437 Report.SymbolRelatedToPreviousError (tc);
438 Report.Error (261, next_part.Location,
439 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
440 next_part.GetSignatureForError ());
444 if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
445 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
446 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
447 Report.SymbolRelatedToPreviousError (tc);
448 Report.Error (262, next_part.Location,
449 "Partial declarations of `{0}' have conflicting accessibility modifiers",
450 next_part.GetSignatureForError ());
454 if (tc.MemberName.IsGeneric) {
455 TypeParameter[] tc_names = tc.TypeParameters;
456 TypeParameterName[] part_names = next_part.MemberName.TypeArguments.GetDeclarations ();
458 for (int i = 0; i < tc_names.Length; ++i) {
459 if (tc_names[i].Name == part_names[i].Name)
462 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
463 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
464 tc.GetSignatureForError ());
469 if (tc.partial_parts == null)
470 tc.partial_parts = new ArrayList (1);
472 tc.ModFlags |= next_part.ModFlags;
473 if (next_part.attributes != null) {
474 if (tc.attributes == null)
475 tc.attributes = next_part.attributes;
477 tc.attributes.AddAttributes (next_part.attributes.Attrs);
480 next_part.PartialContainer = tc;
481 tc.partial_parts.Add (next_part);
485 public void AddDelegate (Delegate d)
487 if (!AddMemberType (d))
490 if (delegates == null)
491 delegates = new MemberCoreArrayList ();
496 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
498 if (ordered_explicit_member_list == null) {
499 ordered_explicit_member_list = new MemberCoreArrayList ();
500 ordered_member_list = new MemberCoreArrayList ();
504 ordered_explicit_member_list.Add (mc);
505 alist.Insert (0, mc);
508 ordered_member_list.Add (mc);
514 public void AddMethod (Method method)
516 if (!AddMember (method))
520 methods = new MemberCoreArrayList ();
522 if (method.MemberName.Left != null)
523 AddMemberToList (method, methods, true);
525 AddMemberToList (method, methods, false);
529 // Do not use this method: use AddMethod.
531 // This is only used by iterators.
533 public void AppendMethod (Method method)
535 if (!AddMember (method))
539 methods = new MemberCoreArrayList ();
541 AddMemberToList (method, methods, false);
544 public void AddConstructor (Constructor c)
546 if (c.Name != MemberName.Name) {
547 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
550 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
553 if (default_static_constructor != null) {
554 Report.SymbolRelatedToPreviousError (default_static_constructor);
555 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
559 default_static_constructor = c;
561 if (c.Parameters.Empty){
562 if (default_constructor != null) {
563 Report.SymbolRelatedToPreviousError (default_constructor);
564 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
567 default_constructor = c;
570 if (instance_constructors == null)
571 instance_constructors = new MemberCoreArrayList ();
573 instance_constructors.Add (c);
577 internal static string Error111 {
579 return "`{0}' is already defined. Rename this member or use different parameter types";
583 public void AddField (FieldBase field)
585 if (!AddMember (field))
589 fields = new MemberCoreArrayList ();
593 if ((field.ModFlags & Modifiers.STATIC) != 0)
596 if (first_nonstatic_field == null) {
597 first_nonstatic_field = field;
601 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
602 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
603 Report.Warning (282, 3, field.Location,
604 "struct instance field `{0}' found in different declaration from instance field `{1}'",
605 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
609 public void AddProperty (Property prop)
611 if (!AddMember (prop) ||
612 !AddMember (prop.Get) || !AddMember (prop.Set))
615 if (properties == null)
616 properties = new MemberCoreArrayList ();
618 if (prop.MemberName.Left != null)
619 AddMemberToList (prop, properties, true);
621 AddMemberToList (prop, properties, false);
624 public void AddEvent (Event e)
629 if (e is EventProperty) {
630 if (!AddMember (e.Add))
633 if (!AddMember (e.Remove))
638 events = new MemberCoreArrayList ();
644 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
646 public void AddIndexer (Indexer i)
648 if (indexers == null)
649 indexers = new ArrayList ();
651 if (i.IsExplicitImpl)
652 AddMemberToList (i, indexers, true);
654 AddMemberToList (i, indexers, false);
657 public void AddOperator (Operator op)
662 if (operators == null)
663 operators = new OperatorArrayList (this);
668 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
670 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
672 if (compiler_generated == null)
673 compiler_generated = new ArrayList ();
675 compiler_generated.Add (c);
678 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
680 if (a.Type == TypeManager.default_member_type) {
681 if (Indexers != null) {
682 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
687 base.ApplyAttributeBuilder (a, cb);
690 public override AttributeTargets AttributeTargets {
692 throw new NotSupportedException ();
696 public ArrayList Types {
702 public MemberCoreArrayList Methods {
708 public ArrayList Constants {
714 public ArrayList CompilerGenerated {
716 return compiler_generated;
720 protected Type BaseType {
722 return TypeBuilder.BaseType;
726 public ArrayList Bases {
736 public ArrayList Fields {
742 public ArrayList InstanceConstructors {
744 return instance_constructors;
748 public ArrayList Properties {
754 public ArrayList Events {
760 public ArrayList Indexers {
766 public ArrayList Operators {
772 public ArrayList Delegates {
778 protected override TypeAttributes TypeAttr {
780 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
784 public string IndexerName {
786 return indexers == null ? DefaultIndexerName : indexer_name;
790 public bool IsComImport {
792 if (OptAttributes == null)
795 return OptAttributes.Contains (TypeManager.comimport_attr_type);
799 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
801 if ((field.ModFlags & Modifiers.STATIC) != 0){
802 if (initialized_static_fields == null)
803 initialized_static_fields = new ArrayList (4);
805 initialized_static_fields.Add (expression);
807 if (initialized_fields == null)
808 initialized_fields = new ArrayList (4);
810 initialized_fields.Add (expression);
815 // Emits the instance field initializers
817 public bool EmitFieldInitializers (EmitContext ec)
822 fields = initialized_static_fields;
824 fields = initialized_fields;
830 foreach (FieldInitializer f in fields) {
831 f.EmitStatement (ec);
836 public override string DocComment {
848 public PendingImplementation PendingImplementations {
849 get { return pending; }
852 public override bool GetClsCompliantAttributeValue ()
854 if (PartialContainer != this)
855 return PartialContainer.GetClsCompliantAttributeValue ();
857 return base.GetClsCompliantAttributeValue ();
860 public void AddBasesForPart (DeclSpace part, ArrayList bases)
862 // FIXME: get rid of partial_parts and store lists of bases of each part here
863 // assumed, not verified: 'part' is in 'partial_parts'
864 ((TypeContainer) part).Bases = bases;
867 TypeExpr[] GetNormalBases (out TypeExpr base_class)
873 int count = Bases.Count;
876 if (Kind == Kind.Class){
877 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
883 if (!name.IsInterface) {
884 // base_class could be a class, struct, enum, delegate.
885 // This is validated in GetClassBases.
891 TypeExpr [] ifaces = new TypeExpr [count-start];
893 for (i = start, j = 0; i < count; i++, j++){
894 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
895 if (resolved == null) {
899 ifaces [j] = resolved;
902 return ifaces.Length == 0 ? null : ifaces;
906 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
908 ArrayList ifaces = new ArrayList (0);
909 if (iface_exprs != null)
910 ifaces.AddRange (iface_exprs);
912 foreach (TypeContainer part in partial_parts) {
913 TypeExpr new_base_class;
914 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
915 if (new_base_class != TypeManager.system_object_expr) {
916 if (base_class == TypeManager.system_object_expr)
917 base_class = new_base_class;
919 if (new_base_class != null && !new_base_class.Equals (base_class)) {
920 Report.SymbolRelatedToPreviousError (base_class.Location, "");
921 Report.Error (263, part.Location,
922 "Partial declarations of `{0}' must not specify different base classes",
923 part.GetSignatureForError ());
930 if (new_ifaces == null)
933 foreach (TypeExpr iface in new_ifaces) {
934 if (ifaces.Contains (iface))
941 if (ifaces.Count == 0)
944 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
948 /// This function computes the Base class and also the
949 /// list of interfaces that the class or struct @c implements.
951 /// The return value is an array (might be null) of
952 /// interfaces implemented (as Types).
954 /// The @base_class argument is set to the base object or null
955 /// if this is `System.Object'.
957 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
959 TypeExpr[] ifaces = GetNormalBases (out base_class);
964 int count = ifaces.Length;
966 for (int i = 0; i < count; i++) {
967 TypeExpr iface = (TypeExpr) ifaces [i];
969 if (!iface.IsInterface) {
970 if (Kind != Kind.Class) {
971 // TODO: location of symbol related ....
972 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
974 else if (base_class != null)
975 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
976 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
978 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
979 GetSignatureForError (), iface.GetSignatureForError ());
984 for (int x = 0; x < i; x++) {
985 if (iface.Equals (ifaces [x])) {
986 Report.Error (528, Location,
987 "`{0}' is already listed in " +
988 "interface list", iface.GetSignatureForError ());
993 if ((Kind == Kind.Interface) &&
994 !iface.AsAccessible (Parent, ModFlags)) {
995 Report.Error (61, Location,
996 "Inconsistent accessibility: base " +
997 "interface `{0}' is less accessible " +
998 "than interface `{1}'", iface.Name,
1006 bool CheckGenericInterfaces (Type[] ifaces)
1009 ArrayList already_checked = new ArrayList ();
1011 for (int i = 0; i < ifaces.Length; i++) {
1012 Type iface = ifaces [i];
1013 foreach (Type t in already_checked) {
1017 Type[] inferred = new Type [CountTypeParameters];
1018 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
1021 Report.Error (695, Location,
1022 "`{0}' cannot implement both `{1}' and `{2}' " +
1023 "because they may unify for some type parameter substitutions",
1024 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1025 TypeManager.CSharpName (t));
1029 already_checked.Add (iface);
1038 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1040 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1043 bool CreateTypeBuilder ()
1046 Type default_parent = null;
1047 if (Kind == Kind.Struct)
1048 default_parent = TypeManager.value_type;
1049 else if (Kind == Kind.Enum)
1050 default_parent = TypeManager.enum_type;
1053 if (TypeManager.NamespaceClash (Name, Location)) {
1057 ModuleBuilder builder = CodeGen.Module.Builder;
1058 TypeBuilder = builder.DefineType (
1059 Name, TypeAttr, default_parent, null);
1061 TypeBuilder builder = Parent.TypeBuilder;
1063 TypeBuilder = builder.DefineNestedType (
1064 Basename, TypeAttr, default_parent, null);
1066 } catch (ArgumentException) {
1067 Report.RuntimeMissingSupport (Location, "static classes");
1071 TypeManager.AddUserType (this);
1075 string[] param_names = new string [TypeParameters.Length];
1076 for (int i = 0; i < TypeParameters.Length; i++)
1077 param_names [i] = TypeParameters [i].Name;
1079 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1081 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1082 for (int i = offset; i < gen_params.Length; i++)
1083 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1090 bool DefineBaseTypes ()
1092 iface_exprs = GetClassBases (out base_type);
1093 if (partial_parts != null) {
1094 iface_exprs = GetNormalPartialBases (ref base_type);
1098 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1099 // which in turn should have called DefineType()s on base types if necessary.
1101 // None of the code below should trigger DefineType()s on classes that we depend on.
1102 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1104 // Let's do it as soon as possible, since code below can call DefineType() on classes
1105 // that depend on us to be populated before they are.
1107 if (!(this is CompilerGeneratedClass))
1108 RootContext.RegisterOrder (this);
1110 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1111 Report.Error (698, base_type.Location,
1112 "A generic type cannot derive from `{0}' because it is an attribute class",
1117 if (!CheckRecursiveDefinition (this))
1120 if (base_type != null && base_type.Type != null) {
1121 TypeBuilder.SetParent (base_type.Type);
1123 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1124 if (obsolete_attr != null && !IsInObsoleteScope)
1125 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1128 // add interfaces that were not added at type creation
1129 if (iface_exprs != null) {
1130 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1134 foreach (Type itype in ifaces)
1135 TypeBuilder.AddInterfaceImplementation (itype);
1137 foreach (TypeExpr ie in iface_exprs) {
1138 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1139 if ((oa != null) && !IsInObsoleteScope)
1140 AttributeTester.Report_ObsoleteMessage (
1141 oa, ie.GetSignatureForError (), Location);
1144 if (!CheckGenericInterfaces (ifaces))
1147 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1154 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1156 public TypeBuilder CreateType ()
1158 if (TypeBuilder != null)
1164 if (!CreateTypeBuilder ()) {
1169 if (partial_parts != null) {
1170 foreach (TypeContainer part in partial_parts)
1171 part.TypeBuilder = TypeBuilder;
1174 if (Types != null) {
1175 foreach (TypeContainer tc in Types) {
1176 if (tc.CreateType () == null) {
1188 public override TypeBuilder DefineType ()
1195 type_defined = true;
1197 if (CreateType () == null) {
1202 if (!DefineBaseTypes ()) {
1207 if (!(this is CompilerGeneratedClass)) {
1208 if (!ResolveMembers ()) {
1214 if (!DefineNestedTypes ()) {
1222 public bool ResolveMembers ()
1224 if (members_resolved)
1225 return members_resolved_ok;
1227 members_resolved_ok = DoResolveMembers ();
1228 members_resolved = true;
1230 return members_resolved_ok;
1233 protected virtual bool DoResolveMembers ()
1235 if (methods != null) {
1236 foreach (Method method in methods) {
1237 if (!method.ResolveMembers ())
1242 if (instance_constructors != null) {
1243 foreach (Constructor c in instance_constructors) {
1244 if (!c.ResolveMembers ())
1249 if (default_static_constructor != null) {
1250 if (!default_static_constructor.ResolveMembers ())
1254 if (operators != null) {
1255 foreach (Operator o in operators) {
1256 if (!o.ResolveMembers ())
1261 if (properties != null) {
1262 foreach (PropertyBase p in properties) {
1263 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1265 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1270 if (indexers != null) {
1271 foreach (PropertyBase p in indexers) {
1272 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1274 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1279 if (events != null) {
1280 foreach (Event e in events) {
1281 if (!e.Add.ResolveMembers ())
1283 if (!e.Remove.ResolveMembers ())
1288 if (compiler_generated != null) {
1289 foreach (CompilerGeneratedClass c in compiler_generated) {
1290 if (c.DefineType () == null)
1298 Constraints [] constraints;
1299 public override void SetParameterInfo (ArrayList constraints_list)
1301 if (PartialContainer == this) {
1302 base.SetParameterInfo (constraints_list);
1306 if (constraints_list == null)
1309 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1311 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1312 for (int i = 0; i < constraints.Length; i++) {
1313 foreach (Constraints constraint in constraints_list) {
1314 if (constraint.TypeParameter == current_params [i].Name) {
1315 constraints [i] = constraint;
1322 bool UpdateTypeParameterConstraints ()
1324 if (constraints == null)
1327 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1328 for (int i = 0; i < current_params.Length; i++) {
1329 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1330 Report.SymbolRelatedToPreviousError (Location, "");
1331 Report.Error (265, PartialContainer.Location,
1332 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1333 PartialContainer.GetSignatureForError (), current_params [i].Name);
1341 public bool ResolveType ()
1343 if (!DoResolveType ())
1346 if (compiler_generated != null) {
1347 foreach (CompilerGeneratedClass c in compiler_generated)
1348 if (!c.ResolveType ())
1355 protected virtual bool DoResolveType ()
1357 if ((base_type != null) &&
1358 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1366 if (PartialContainer != this)
1367 throw new InternalErrorException ();
1369 TypeExpr current_type = null;
1371 foreach (TypeParameter type_param in CurrentTypeParameters) {
1372 if (!type_param.Resolve (this)) {
1378 if (partial_parts != null) {
1379 foreach (TypeContainer part in partial_parts) {
1380 if (!part.UpdateTypeParameterConstraints ()) {
1387 foreach (TypeParameter type_param in TypeParameters) {
1388 if (!type_param.DefineType (this)) {
1394 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1396 foreach (TypeParameter type_param in TypeParameters)
1397 if (!type_param.CheckDependencies ()) {
1402 if (current_type != null) {
1403 current_type = current_type.ResolveAsTypeTerminal (this, false);
1404 if (current_type == null) {
1409 CurrentType = current_type.Type;
1415 protected virtual bool DefineNestedTypes ()
1417 if (Types != null) {
1418 foreach (TypeContainer tc in Types)
1419 if (tc.DefineType () == null)
1423 if (Delegates != null) {
1424 foreach (Delegate d in Delegates)
1425 if (d.DefineType () == null)
1432 TypeContainer InTransit;
1434 protected bool CheckRecursiveDefinition (TypeContainer tc)
1436 if (InTransit != null) {
1437 Report.SymbolRelatedToPreviousError (this);
1438 if (this is Interface)
1440 529, tc.Location, "Inherited interface `{0}' causes a " +
1441 "cycle in the interface hierarchy of `{1}'",
1442 GetSignatureForError (), tc.GetSignatureForError ());
1445 146, tc.Location, "Circular base class dependency " +
1446 "involving `{0}' and `{1}'",
1447 tc.GetSignatureForError (), GetSignatureForError ());
1453 if (base_type != null && base_type.Type != null) {
1454 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1455 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1456 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1460 if (iface_exprs != null) {
1461 foreach (TypeExpr iface in iface_exprs) {
1462 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1463 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1464 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1469 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1476 public static void Error_KeywordNotAllowed (Location loc)
1478 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1482 /// Populates our TypeBuilder with fields and methods
1484 public override bool DefineMembers ()
1486 if (members_defined)
1487 return members_defined_ok;
1489 if (!base.DefineMembers ())
1492 members_defined_ok = DoDefineMembers ();
1493 members_defined = true;
1495 return members_defined_ok;
1498 protected virtual bool DoDefineMembers ()
1500 if (iface_exprs != null) {
1501 foreach (TypeExpr iface in iface_exprs) {
1502 ConstructedType ct = iface as ConstructedType;
1503 if ((ct != null) && !ct.CheckConstraints (this))
1508 if (base_type != null) {
1509 ConstructedType ct = base_type as ConstructedType;
1510 if ((ct != null) && !ct.CheckConstraints (this))
1515 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1516 if (conflict_symbol == null) {
1517 if ((ModFlags & Modifiers.NEW) != 0)
1518 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1520 if ((ModFlags & Modifiers.NEW) == 0) {
1521 Report.SymbolRelatedToPreviousError (conflict_symbol);
1522 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1523 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1528 DefineContainerMembers (constants);
1529 DefineContainerMembers (fields);
1531 if (Kind == Kind.Struct || Kind == Kind.Class) {
1532 pending = PendingImplementation.GetPendingImplementations (this);
1536 // Constructors are not in the defined_names array
1538 DefineContainerMembers (instance_constructors);
1540 DefineContainerMembers (events);
1541 DefineContainerMembers (ordered_explicit_member_list);
1542 DefineContainerMembers (ordered_member_list);
1544 DefineContainerMembers (operators);
1545 DefineContainerMembers (delegates);
1547 ComputeIndexerName();
1548 CheckEqualsAndGetHashCode();
1550 if (CurrentType != null) {
1551 GenericType = CurrentType;
1555 member_cache = new MemberCache (this);
1556 if (partial_parts != null) {
1557 foreach (TypeContainer part in partial_parts)
1558 part.member_cache = member_cache;
1565 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1568 mcal.DefineContainerMembers ();
1571 protected virtual void ComputeIndexerName ()
1573 if (indexers == null)
1576 string class_indexer_name = null;
1579 // If there's both an explicit and an implicit interface implementation, the
1580 // explicit one actually implements the interface while the other one is just
1581 // a normal indexer. See bug #37714.
1584 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1585 foreach (Indexer i in indexers) {
1586 if (i.InterfaceType != null) {
1587 if (seen_normal_indexers)
1588 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1592 seen_normal_indexers = true;
1594 if (class_indexer_name == null) {
1595 class_indexer_name = i.ShortName;
1599 if (i.ShortName != class_indexer_name)
1600 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");
1603 if (class_indexer_name != null)
1604 indexer_name = class_indexer_name;
1607 protected virtual void EmitIndexerName ()
1609 if (!seen_normal_indexers)
1612 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1613 TypeBuilder.SetCustomAttribute (cb);
1616 protected virtual void CheckEqualsAndGetHashCode ()
1618 if (methods == null)
1621 if (HasEquals && !HasGetHashCode) {
1622 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1626 public override bool Define ()
1628 if (compiler_generated != null) {
1629 foreach (CompilerGeneratedClass c in compiler_generated) {
1638 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1640 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1644 /// This function is based by a delegate to the FindMembers routine
1646 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1652 /// This filter is used by FindMembers, and we just keep
1653 /// a global for the filter to `AlwaysAccept'
1655 static MemberFilter accepting_filter;
1658 static TypeContainer ()
1660 accepting_filter = new MemberFilter (AlwaysAccept);
1663 public MethodInfo[] GetMethods ()
1665 ArrayList members = new ArrayList ();
1669 if (methods != null) {
1670 int len = methods.Count;
1671 for (int i = 0; i < len; i++) {
1672 Method m = (Method) methods [i];
1674 members.Add (m.MethodBuilder);
1678 if (operators != null) {
1679 int len = operators.Count;
1680 for (int i = 0; i < len; i++) {
1681 Operator o = (Operator) operators [i];
1683 members.Add (o.MethodBuilder);
1687 if (properties != null) {
1688 int len = properties.Count;
1689 for (int i = 0; i < len; i++) {
1690 Property p = (Property) properties [i];
1692 if (p.GetBuilder != null)
1693 members.Add (p.GetBuilder);
1694 if (p.SetBuilder != null)
1695 members.Add (p.SetBuilder);
1699 if (indexers != null) {
1700 int len = indexers.Count;
1701 for (int i = 0; i < len; i++) {
1702 Indexer ix = (Indexer) indexers [i];
1704 if (ix.GetBuilder != null)
1705 members.Add (ix.GetBuilder);
1706 if (ix.SetBuilder != null)
1707 members.Add (ix.SetBuilder);
1711 if (events != null) {
1712 int len = events.Count;
1713 for (int i = 0; i < len; i++) {
1714 Event e = (Event) events [i];
1716 if (e.AddBuilder != null)
1717 members.Add (e.AddBuilder);
1718 if (e.RemoveBuilder != null)
1719 members.Add (e.RemoveBuilder);
1723 MethodInfo[] retMethods = new MethodInfo [members.Count];
1724 members.CopyTo (retMethods, 0);
1728 // Indicated whether container has StructLayout attribute set Explicit
1729 public bool HasExplicitLayout {
1730 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1731 set { caching_flags |= Flags.HasExplicitLayout; }
1735 // Return the nested type with name @name. Ensures that the nested type
1736 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1738 public Type FindNestedType (string name)
1740 if (PartialContainer != this)
1741 throw new InternalErrorException ("should not happen");
1743 ArrayList [] lists = { types, delegates };
1745 for (int j = 0; j < lists.Length; ++j) {
1746 ArrayList list = lists [j];
1750 int len = list.Count;
1751 for (int i = 0; i < len; ++i) {
1752 DeclSpace ds = (DeclSpace) list [i];
1753 if (ds.Basename == name) {
1754 return ds.DefineType ();
1762 private void FindMembers_NestedTypes (int modflags,
1763 BindingFlags bf, MemberFilter filter, object criteria,
1764 ref ArrayList members)
1766 ArrayList [] lists = { types, delegates };
1768 for (int j = 0; j < lists.Length; ++j) {
1769 ArrayList list = lists [j];
1773 int len = list.Count;
1774 for (int i = 0; i < len; i++) {
1775 DeclSpace ds = (DeclSpace) list [i];
1777 if ((ds.ModFlags & modflags) == 0)
1780 TypeBuilder tb = ds.TypeBuilder;
1782 if (!(criteria is string) || ds.Basename.Equals (criteria))
1783 tb = ds.DefineType ();
1786 if (tb != null && (filter (tb, criteria) == true)) {
1787 if (members == null)
1788 members = new ArrayList ();
1797 /// This method returns the members of this type just like Type.FindMembers would
1798 /// Only, we need to use this for types which are _being_ defined because MS'
1799 /// implementation can't take care of that.
1802 // FIXME: return an empty static array instead of null, that cleans up
1803 // some code and is consistent with some coding conventions I just found
1807 // Notice that in various cases we check if our field is non-null,
1808 // something that would normally mean that there was a bug elsewhere.
1810 // The problem happens while we are defining p-invoke methods, as those
1811 // will trigger a FindMembers, but this happens before things are defined
1813 // Since the whole process is a no-op, it is fine to check for null here.
1815 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1816 MemberFilter filter, object criteria)
1818 ArrayList members = null;
1821 if ((bf & BindingFlags.Public) != 0)
1822 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1824 if ((bf & BindingFlags.NonPublic) != 0)
1825 modflags |= Modifiers.PRIVATE;
1827 int static_mask = 0, static_flags = 0;
1828 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1829 case BindingFlags.Static:
1830 static_mask = static_flags = Modifiers.STATIC;
1833 case BindingFlags.Instance:
1834 static_mask = Modifiers.STATIC;
1839 static_mask = static_flags = 0;
1843 Timer.StartTimer (TimerType.TcFindMembers);
1846 filter = accepting_filter;
1848 if ((mt & MemberTypes.Field) != 0) {
1849 if (fields != null) {
1850 int len = fields.Count;
1851 for (int i = 0; i < len; i++) {
1852 FieldBase f = (FieldBase) fields [i];
1854 if ((f.ModFlags & modflags) == 0)
1856 if ((f.ModFlags & static_mask) != static_flags)
1859 FieldBuilder fb = f.FieldBuilder;
1860 if (fb != null && filter (fb, criteria) == true) {
1861 if (members == null)
1862 members = new ArrayList ();
1869 if (constants != null) {
1870 int len = constants.Count;
1871 for (int i = 0; i < len; i++) {
1872 Const con = (Const) constants [i];
1874 if ((con.ModFlags & modflags) == 0)
1876 if ((con.ModFlags & static_mask) != static_flags)
1879 FieldBuilder fb = con.FieldBuilder;
1882 fb = con.FieldBuilder;
1884 if (fb != null && filter (fb, criteria) == true) {
1885 if (members == null)
1886 members = new ArrayList ();
1894 if ((mt & MemberTypes.Method) != 0) {
1895 if (methods != null) {
1896 int len = methods.Count;
1897 for (int i = 0; i < len; i++) {
1898 Method m = (Method) methods [i];
1900 if ((m.ModFlags & modflags) == 0)
1902 if ((m.ModFlags & static_mask) != static_flags)
1905 MethodBuilder mb = m.MethodBuilder;
1907 if (mb != null && filter (mb, criteria) == true) {
1908 if (members == null)
1909 members = new ArrayList ();
1916 if (operators != null) {
1917 int len = operators.Count;
1918 for (int i = 0; i < len; i++) {
1919 Operator o = (Operator) operators [i];
1921 if ((o.ModFlags & modflags) == 0)
1923 if ((o.ModFlags & static_mask) != static_flags)
1926 MethodBuilder ob = o.MethodBuilder;
1927 if (ob != null && filter (ob, criteria) == true) {
1928 if (members == null)
1929 members = new ArrayList ();
1936 if (events != null) {
1937 foreach (Event e in events) {
1938 if ((e.ModFlags & modflags) == 0)
1940 if ((e.ModFlags & static_mask) != static_flags)
1943 MethodBuilder b = e.AddBuilder;
1944 if (b != null && filter (b, criteria)) {
1945 if (members == null)
1946 members = new ArrayList (4);
1951 b = e.RemoveBuilder;
1952 if (b != null && filter (b, criteria)) {
1953 if (members == null)
1954 members = new ArrayList (4);
1961 if (properties != null) {
1962 int len = properties.Count;
1963 for (int i = 0; i < len; i++) {
1964 Property p = (Property) properties [i];
1966 if ((p.ModFlags & modflags) == 0)
1968 if ((p.ModFlags & static_mask) != static_flags)
1974 if (b != null && filter (b, criteria) == true) {
1975 if (members == null)
1976 members = new ArrayList ();
1982 if (b != null && filter (b, criteria) == true) {
1983 if (members == null)
1984 members = new ArrayList ();
1991 if (indexers != null) {
1992 int len = indexers.Count;
1993 for (int i = 0; i < len; i++) {
1994 Indexer ix = (Indexer) indexers [i];
1996 if ((ix.ModFlags & modflags) == 0)
1998 if ((ix.ModFlags & static_mask) != static_flags)
2004 if (b != null && filter (b, criteria) == true) {
2005 if (members == null)
2006 members = new ArrayList ();
2012 if (b != null && filter (b, criteria) == true) {
2013 if (members == null)
2014 members = new ArrayList ();
2022 if ((mt & MemberTypes.Event) != 0) {
2023 if (events != null) {
2024 int len = events.Count;
2025 for (int i = 0; i < len; i++) {
2026 Event e = (Event) events [i];
2028 if ((e.ModFlags & modflags) == 0)
2030 if ((e.ModFlags & static_mask) != static_flags)
2033 MemberInfo eb = e.EventBuilder;
2034 if (eb != null && filter (eb, criteria) == true) {
2035 if (members == null)
2036 members = new ArrayList ();
2038 members.Add (e.EventBuilder);
2044 if ((mt & MemberTypes.Property) != 0){
2045 if (properties != null) {
2046 int len = properties.Count;
2047 for (int i = 0; i < len; i++) {
2048 Property p = (Property) properties [i];
2050 if ((p.ModFlags & modflags) == 0)
2052 if ((p.ModFlags & static_mask) != static_flags)
2055 MemberInfo pb = p.PropertyBuilder;
2056 if (pb != null && filter (pb, criteria) == true) {
2057 if (members == null)
2058 members = new ArrayList ();
2060 members.Add (p.PropertyBuilder);
2065 if (indexers != null) {
2066 int len = indexers.Count;
2067 for (int i = 0; i < len; i++) {
2068 Indexer ix = (Indexer) indexers [i];
2070 if ((ix.ModFlags & modflags) == 0)
2072 if ((ix.ModFlags & static_mask) != static_flags)
2075 MemberInfo ib = ix.PropertyBuilder;
2076 if (ib != null && filter (ib, criteria) == true) {
2077 if (members == null)
2078 members = new ArrayList ();
2080 members.Add (ix.PropertyBuilder);
2086 if ((mt & MemberTypes.NestedType) != 0)
2087 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2089 if ((mt & MemberTypes.Constructor) != 0){
2090 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2091 int len = instance_constructors.Count;
2092 for (int i = 0; i < len; i++) {
2093 Constructor c = (Constructor) instance_constructors [i];
2095 ConstructorBuilder cb = c.ConstructorBuilder;
2096 if (cb != null && filter (cb, criteria) == true) {
2097 if (members == null)
2098 members = new ArrayList ();
2105 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2106 ConstructorBuilder cb =
2107 default_static_constructor.ConstructorBuilder;
2109 if (cb != null && filter (cb, criteria) == true) {
2110 if (members == null)
2111 members = new ArrayList ();
2119 // Lookup members in base if requested.
2121 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2122 if (TypeBuilder.BaseType != null) {
2123 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2124 if (list.Count > 0) {
2125 if (members == null)
2126 members = new ArrayList ();
2128 members.AddRange (list);
2133 Timer.StopTimer (TimerType.TcFindMembers);
2135 if (members == null)
2136 return MemberList.Empty;
2138 return new MemberList (members);
2141 public override MemberCache MemberCache {
2143 return member_cache;
2147 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2148 MemberFilter filter, object criteria)
2150 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2153 return ds.FindMembers (mt, bf, filter, criteria);
2155 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2159 /// Emits the values for the constants
2161 public void EmitConstants ()
2163 if (constants != null)
2164 foreach (Const con in constants)
2169 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2174 foreach (MemberCore mc in al) {
2175 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2179 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2184 public virtual void VerifyMembers ()
2187 // Check for internal or private fields that were never assigned
2189 if (Report.WarningLevel >= 3) {
2190 CheckMemberUsage (properties, "property");
2191 CheckMemberUsage (methods, "method");
2192 CheckMemberUsage (constants, "constant");
2194 if (fields != null){
2195 foreach (FieldBase f in fields) {
2196 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2200 if ((f.caching_flags & Flags.IsAssigned) == 0)
2201 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2204 const int error_code = 414;
2206 const int error_code = 169;
2208 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2209 f.GetSignatureForError ());
2215 // Only report 649 on level 4
2217 if (Report.WarningLevel < 4)
2220 if ((f.caching_flags & Flags.IsAssigned) != 0)
2223 Constant c = New.Constantify (f.Type.Type);
2224 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2225 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2231 // TODO: move to ClassOrStruct
2232 void EmitConstructors ()
2234 if (instance_constructors == null)
2237 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2238 bool has_compliant_args = false;
2240 foreach (Constructor c in instance_constructors) {
2244 catch (Exception e) {
2245 throw new InternalErrorException (c, e);
2248 if (has_compliant_args)
2251 has_compliant_args = c.HasCompliantArgs;
2253 if (!has_compliant_args)
2254 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2256 foreach (Constructor c in instance_constructors) {
2260 catch (Exception e) {
2261 throw new InternalErrorException (c, e);
2268 /// Emits the code, this step is performed after all
2269 /// the types, enumerations, constructors
2271 public virtual void EmitType ()
2273 if (OptAttributes != null)
2274 OptAttributes.Emit ();
2278 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2279 for (int i = offset; i < gen_params.Length; i++)
2280 CurrentTypeParameters [i - offset].EmitAttributes ();
2285 // Structs with no fields need to have at least one byte.
2286 // The right thing would be to set the PackingSize in a DefineType
2287 // but there are no functions that allow interfaces *and* the size to
2291 if (Kind == Kind.Struct && first_nonstatic_field == null){
2292 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2293 FieldAttributes.Private);
2295 if (HasExplicitLayout){
2296 object [] ctor_args = new object [1];
2299 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2300 TypeManager.field_offset_attribute_ctor, ctor_args);
2301 fb.SetCustomAttribute (cba);
2307 EmitConstructors ();
2309 // Can not continue if constants are broken
2311 if (Report.Errors > 0)
2314 if (default_static_constructor != null)
2315 default_static_constructor.Emit ();
2317 if (methods != null){
2318 for (int i = 0; i < methods.Count; ++i)
2319 ((Method)methods[i]).Emit ();
2322 if (operators != null)
2323 foreach (Operator o in operators)
2326 if (properties != null)
2327 foreach (Property p in properties)
2330 if (indexers != null) {
2331 foreach (Indexer indx in indexers)
2337 foreach (FieldBase f in fields)
2340 if (events != null){
2341 foreach (Event e in Events)
2345 if (delegates != null) {
2346 foreach (Delegate d in Delegates) {
2351 if (pending != null)
2352 if (pending.VerifyPendingMethods ())
2355 if (Report.Errors > 0)
2358 if (compiler_generated != null) {
2359 foreach (CompilerGeneratedClass c in compiler_generated) {
2360 if (!c.DefineMembers ())
2361 throw new InternalErrorException ();
2363 foreach (CompilerGeneratedClass c in compiler_generated)
2368 public override void CloseType ()
2370 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2374 caching_flags |= Flags.CloseTypeCreated;
2375 TypeBuilder.CreateType ();
2376 } catch (TypeLoadException){
2378 // This is fine, the code still created the type
2380 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2381 // Console.WriteLine (e.Message);
2382 } catch (Exception e) {
2383 throw new InternalErrorException (this, e);
2387 foreach (TypeContainer tc in Types)
2388 if (tc.Kind == Kind.Struct)
2391 foreach (TypeContainer tc in Types)
2392 if (tc.Kind != Kind.Struct)
2396 if (Delegates != null)
2397 foreach (Delegate d in Delegates)
2400 if (CompilerGenerated != null)
2401 foreach (CompilerGeneratedClass c in CompilerGenerated)
2408 initialized_fields = null;
2409 initialized_static_fields = null;
2411 ordered_explicit_member_list = null;
2412 ordered_member_list = null;
2417 compiler_generated = null;
2418 default_constructor = null;
2419 default_static_constructor = null;
2421 OptAttributes = null;
2424 member_cache = null;
2428 // Performs the validation on a Method's modifiers (properties have
2429 // the same properties).
2431 public bool MethodModifiersValid (MemberCore mc)
2433 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2434 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2435 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2437 int flags = mc.ModFlags;
2440 // At most one of static, virtual or override
2442 if ((flags & Modifiers.STATIC) != 0){
2443 if ((flags & vao) != 0){
2444 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2445 mc.GetSignatureForError ());
2450 if (Kind == Kind.Struct){
2451 if ((flags & va) != 0){
2452 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2457 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2458 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2459 mc.GetSignatureForError ());
2464 // If the declaration includes the abstract modifier, then the
2465 // declaration does not include static, virtual or extern
2467 if ((flags & Modifiers.ABSTRACT) != 0){
2468 if ((flags & Modifiers.EXTERN) != 0){
2470 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2474 if ((flags & Modifiers.SEALED) != 0) {
2475 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2479 if ((flags & Modifiers.VIRTUAL) != 0){
2480 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2484 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2485 Report.SymbolRelatedToPreviousError (this);
2486 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2487 mc.GetSignatureForError (), GetSignatureForError ());
2492 if ((flags & Modifiers.PRIVATE) != 0){
2493 if ((flags & vao) != 0){
2494 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2499 if ((flags & Modifiers.SEALED) != 0){
2500 if ((flags & Modifiers.OVERRIDE) == 0){
2501 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2509 public Constructor DefaultStaticConstructor {
2510 get { return default_static_constructor; }
2513 protected override bool VerifyClsCompliance ()
2515 if (!base.VerifyClsCompliance ())
2520 Type base_type = TypeBuilder.BaseType;
2521 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2522 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2529 /// Checks whether container name is CLS Compliant
2531 void VerifyClsName ()
2533 Hashtable base_members = base_cache == null ?
2535 base_cache.GetPublicMembers ();
2536 Hashtable this_members = new Hashtable ();
2538 foreach (DictionaryEntry entry in defined_names) {
2539 MemberCore mc = (MemberCore)entry.Value;
2540 if (!mc.IsClsComplianceRequired ())
2543 string name = (string) entry.Key;
2544 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2546 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2547 object found = base_members [lcase];
2548 if (found == null) {
2549 found = this_members [lcase];
2550 if (found == null) {
2551 this_members.Add (lcase, mc);
2556 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2559 if (found is MemberInfo) {
2560 if (basename == ((MemberInfo) found).Name)
2562 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2564 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2567 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2569 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2576 /// Performs checks for an explicit interface implementation. First it
2577 /// checks whether the `interface_type' is a base inteface implementation.
2578 /// Then it checks whether `name' exists in the interface type.
2580 public virtual bool VerifyImplements (InterfaceMemberBase mb)
2582 if (ifaces != null) {
2583 foreach (Type t in ifaces){
2584 if (t == mb.InterfaceType)
2589 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2590 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2591 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2595 public override Type LookupAnyGeneric (string typeName)
2597 if (types != null) {
2598 foreach (TypeContainer tc in types) {
2602 int pos = tc.Basename.LastIndexOf ('`');
2603 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2604 return tc.TypeBuilder;
2608 return base.LookupAnyGeneric (typeName);
2611 public void Mark_HasEquals ()
2613 cached_method |= CachedMethods.Equals;
2616 public void Mark_HasGetHashCode ()
2618 cached_method |= CachedMethods.GetHashCode;
2622 /// Method container contains Equals method
2624 public bool HasEquals {
2626 return (cached_method & CachedMethods.Equals) != 0;
2631 /// Method container contains GetHashCode method
2633 public bool HasGetHashCode {
2635 return (cached_method & CachedMethods.GetHashCode) != 0;
2643 string IMemberContainer.Name {
2649 Type IMemberContainer.Type {
2655 MemberCache IMemberContainer.MemberCache {
2657 return member_cache;
2661 bool IMemberContainer.IsInterface {
2663 return Kind == Kind.Interface;
2667 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2669 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2671 if (GenericType != null)
2672 return TypeManager.FindMembers (GenericType, mt, new_bf,
2675 return FindMembers (mt, new_bf, null, null);
2679 // Generates xml doc comments (if any), and if required,
2680 // handle warning report.
2682 internal override void GenerateDocComment (DeclSpace ds)
2684 DocUtil.GenerateTypeDocComment (this, ds);
2687 public override string DocCommentHeader {
2688 get { return "T:"; }
2691 public virtual MemberCache BaseCache {
2693 if (base_cache != null)
2695 if (TypeBuilder.BaseType != null)
2696 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2697 if (TypeBuilder.IsInterface)
2698 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2703 private IDictionary anonymous_types;
2704 public IDictionary AnonymousTypes {
2706 if (anonymous_types == null)
2707 anonymous_types = new HybridDictionary();
2708 return anonymous_types;
2713 public abstract class ClassOrStruct : TypeContainer {
2714 ListDictionary declarative_security;
2716 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2717 MemberName name, Attributes attrs, Kind kind)
2718 : base (ns, parent, name, attrs, kind)
2722 protected override bool AddToContainer (MemberCore symbol, string name)
2724 if (name == MemberName.Name) {
2725 if (symbol is TypeParameter) {
2726 Report.Error (694, symbol.Location,
2727 "Type parameter `{0}' has same name as " +
2728 "containing type, or method", name);
2732 Report.SymbolRelatedToPreviousError (this);
2733 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2734 symbol.GetSignatureForError ());
2738 return base.AddToContainer (symbol, name);
2741 public override void VerifyMembers ()
2743 base.VerifyMembers ();
2745 if ((events != null) && Report.WarningLevel >= 3) {
2746 foreach (Event e in events){
2747 if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2750 if ((e.caching_flags & Flags.IsUsed) == 0)
2751 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2756 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2758 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2759 if (declarative_security == null)
2760 declarative_security = new ListDictionary ();
2762 a.ExtractSecurityPermissionSet (declarative_security);
2766 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2767 HasExplicitLayout = true;
2770 base.ApplyAttributeBuilder (a, cb);
2774 /// Defines the default constructors
2776 protected void DefineDefaultConstructor (bool is_static)
2778 // The default instance constructor is public
2779 // If the class is abstract, the default constructor is protected
2780 // The default static constructor is private
2784 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2786 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2789 Constructor c = new Constructor (this, MemberName.Name, mods,
2790 Parameters.EmptyReadOnlyParameters,
2791 new GeneratedBaseInitializer (Location),
2795 c.Block = new ToplevelBlock (null, Location);
2798 void DefineFieldInitializers ()
2800 if (initialized_fields != null) {
2801 for (int i = 0; i < initialized_fields.Count; ++i) {
2802 FieldInitializer fi = (FieldInitializer)initialized_fields[i];
2804 EmitContext ec = new EmitContext (fi.TypeContainer, fi.TypeContainer,
2805 Location, null, TypeManager.void_type, ModFlags);
2806 ec.IsFieldInitializer = true;
2808 fi.ResolveStatement (ec);
2809 if (fi.IsDefaultInitializer && RootContext.Optimize) {
2810 // Field is re-initialized to its default value => removed
2811 initialized_fields.RemoveAt (i);
2817 if (initialized_static_fields != null) {
2818 bool has_complex_initializer = false;
2820 foreach (FieldInitializer fi in initialized_static_fields) {
2821 EmitContext ec = new EmitContext (fi.TypeContainer, fi.TypeContainer,
2822 Location, null, TypeManager.void_type, ModFlags);
2824 ec.IsFieldInitializer = true;
2826 fi.ResolveStatement (ec);
2827 if (!fi.IsComplexInitializer)
2830 has_complex_initializer = true;
2833 // Need special check to not optimize code like this
2834 // static int a = b = 5;
2835 // static int b = 0;
2836 if (!has_complex_initializer && RootContext.Optimize) {
2837 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2838 FieldInitializer fi = (FieldInitializer)initialized_static_fields[i];
2839 if (fi.IsDefaultInitializer) {
2840 initialized_static_fields.RemoveAt (i);
2846 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2847 DefineDefaultConstructor (true);
2853 public override bool Define ()
2855 DefineFieldInitializers ();
2857 if (default_static_constructor != null)
2858 default_static_constructor.Define ();
2860 return base.Define ();
2863 public override void Emit ()
2867 if (declarative_security != null) {
2868 foreach (DictionaryEntry de in declarative_security) {
2869 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2874 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
2876 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name);
2879 protected override TypeAttributes TypeAttr {
2881 if (default_static_constructor == null)
2882 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2884 return base.TypeAttr;
2890 // TODO: should be sealed
2891 public class Class : ClassOrStruct {
2892 const int AllowedModifiers =
2895 Modifiers.PROTECTED |
2896 Modifiers.INTERNAL |
2898 Modifiers.ABSTRACT |
2903 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2905 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2907 : base (ns, parent, name, attrs, Kind.Class)
2909 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2910 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2912 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2913 Report.FeatureIsNotISO1 (Location, "static classes");
2917 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2919 if (a.Type == TypeManager.attribute_usage_type) {
2920 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2921 TypeBuilder.FullName != "System.Attribute") {
2922 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2926 if (a.Type == TypeManager.conditional_attribute_type &&
2927 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2928 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2932 if (a.Type == TypeManager.comimport_attr_type &&
2933 !attributes.Contains (TypeManager.guid_attr_type)) {
2934 a.Error_MissingGuidAttribute ();
2938 if (a.Type == TypeManager.extension_attribute_type) {
2939 a.Error_MisusedExtensionAttribute ();
2943 if (AttributeTester.IsAttributeExcluded (a.Type))
2946 base.ApplyAttributeBuilder (a, cb);
2949 public override AttributeTargets AttributeTargets {
2951 return AttributeTargets.Class;
2955 protected override void DefineContainerMembers (MemberCoreArrayList list)
2961 base.DefineContainerMembers (list);
2965 foreach (MemberCore m in list) {
2966 if (m is Operator) {
2967 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2971 if (m is Destructor) {
2972 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2976 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2977 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2982 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2986 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2989 if (m is Constructor) {
2990 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2994 Method method = m as Method;
2995 if (method != null && method.Parameters.HasExtensionMethodType) {
2996 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
3000 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3003 base.DefineContainerMembers (list);
3006 public override TypeBuilder DefineType ()
3008 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3009 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3013 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3014 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3018 return base.DefineType ();
3021 protected override bool DoDefineMembers ()
3023 if (InstanceConstructors == null && !IsStatic)
3024 DefineDefaultConstructor (false);
3026 return base.DoDefineMembers ();
3029 public override void Emit ()
3033 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
3034 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
3037 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3039 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3041 if (base_class == null) {
3042 if (RootContext.StdLib)
3043 base_class = TypeManager.system_object_expr;
3044 else if (Name != "System.Object")
3045 base_class = TypeManager.system_object_expr;
3047 if (Kind == Kind.Class && base_class is TypeParameterExpr){
3049 689, base_class.Location,
3050 "Cannot derive from `{0}' because it is a type parameter",
3051 base_class.GetSignatureForError ());
3055 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
3056 Report.Error (1521, base_class.Location, "Invalid base type");
3060 if (base_class.IsSealed){
3061 Report.SymbolRelatedToPreviousError (base_class.Type);
3062 if (base_class.Type.IsAbstract) {
3063 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3064 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3066 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3067 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3072 if (!base_class.CanInheritFrom ()){
3073 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3074 GetSignatureForError (), base_class.GetSignatureForError ());
3078 if (!base_class.AsAccessible (this, ModFlags)) {
3079 Report.SymbolRelatedToPreviousError (base_class.Type);
3080 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3081 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3086 if (base_class != TypeManager.system_object_expr) {
3087 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3088 GetSignatureForError (), base_class.GetSignatureForError ());
3092 if (ifaces != null) {
3093 foreach (TypeExpr t in ifaces)
3094 Report.SymbolRelatedToPreviousError (t.Type);
3095 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3102 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3103 /// Valid only for attribute classes.
3104 public bool IsExcluded ()
3106 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3107 return (caching_flags & Flags.Excluded) != 0;
3109 caching_flags &= ~Flags.Excluded_Undetected;
3111 if (OptAttributes == null)
3114 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3119 foreach (Attribute a in attrs) {
3120 string condition = a.GetConditionalAttributeValue ();
3121 if (RootContext.AllDefines.Contains (condition))
3125 caching_flags |= Flags.Excluded;
3131 return (ModFlags & Modifiers.STATIC) != 0;
3136 // FIXME: How do we deal with the user specifying a different
3139 protected override TypeAttributes TypeAttr {
3141 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3143 ta |= StaticClassAttribute;
3149 public sealed class Struct : ClassOrStruct {
3151 // Modifiers allowed in a struct declaration
3153 const int AllowedModifiers =
3156 Modifiers.PROTECTED |
3157 Modifiers.INTERNAL |
3161 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3162 int mod, Attributes attrs)
3163 : base (ns, parent, name, attrs, Kind.Struct)
3167 if (parent.Parent == null)
3168 accmods = Modifiers.INTERNAL;
3170 accmods = Modifiers.PRIVATE;
3172 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3174 this.ModFlags |= Modifiers.SEALED;
3177 public override AttributeTargets AttributeTargets {
3179 return AttributeTargets.Struct;
3183 const TypeAttributes DefaultTypeAttributes =
3184 TypeAttributes.SequentialLayout |
3185 TypeAttributes.Sealed |
3186 TypeAttributes.BeforeFieldInit;
3189 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3191 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3193 // If we are compiling our runtime,
3194 // and we are defining ValueType, then our
3195 // base is `System.Object'.
3197 if (base_class == null) {
3198 if (!RootContext.StdLib && Name == "System.ValueType")
3199 base_class = TypeManager.system_object_expr;
3201 base_class = TypeManager.system_valuetype_expr;
3208 // FIXME: Allow the user to specify a different set of attributes
3209 // in some cases (Sealed for example is mandatory for a class,
3210 // but what SequentialLayout can be changed
3212 protected override TypeAttributes TypeAttr {
3214 return base.TypeAttr | DefaultTypeAttributes;
3218 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3220 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3221 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3222 field.GetSignatureForError ());
3225 base.RegisterFieldForInitialization (field, expression);
3233 public sealed class Interface : TypeContainer, IMemberContainer {
3236 /// Modifiers allowed in a class declaration
3238 public const int AllowedModifiers =
3241 Modifiers.PROTECTED |
3242 Modifiers.INTERNAL |
3246 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3248 : base (ns, parent, name, attrs, Kind.Interface)
3252 if (parent.Parent == null)
3253 accmods = Modifiers.INTERNAL;
3255 accmods = Modifiers.PRIVATE;
3257 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3260 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3262 if (a.Type == TypeManager.comimport_attr_type &&
3263 !attributes.Contains (TypeManager.guid_attr_type)) {
3264 a.Error_MissingGuidAttribute ();
3267 base.ApplyAttributeBuilder (a, cb);
3271 public override AttributeTargets AttributeTargets {
3273 return AttributeTargets.Interface;
3277 const TypeAttributes DefaultTypeAttributes =
3278 TypeAttributes.AutoLayout |
3279 TypeAttributes.Abstract |
3280 TypeAttributes.Interface;
3282 protected override TypeAttributes TypeAttr {
3284 return base.TypeAttr | DefaultTypeAttributes;
3288 protected override bool VerifyClsCompliance ()
3290 if (!base.VerifyClsCompliance ())
3293 if (ifaces != null) {
3294 foreach (Type t in ifaces) {
3295 if (AttributeTester.IsClsCompliant (t))
3298 Report.SymbolRelatedToPreviousError (t);
3299 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3300 GetSignatureForError (), TypeManager.CSharpName (t));
3308 // It is used as a base class for all property based members
3309 // This includes properties, indexers, and events
3310 public abstract class PropertyBasedMember : InterfaceMemberBase
3312 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3313 Expression type, int mod, int allowed_mod, bool is_iface,
3314 MemberName name, Attributes attrs)
3315 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3319 protected override bool CheckForDuplications ()
3321 throw new NotSupportedException ();
3324 protected override bool VerifyClsCompliance ()
3326 if (!base.VerifyClsCompliance ())
3329 if (!AttributeTester.IsClsCompliant (MemberType)) {
3330 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3331 GetSignatureForError ());
3339 public abstract class MethodCore : InterfaceMemberBase
3341 public readonly Parameters Parameters;
3342 protected ToplevelBlock block;
3344 public MethodCore (DeclSpace parent, GenericMethod generic,
3345 Expression type, int mod, int allowed_mod, bool is_iface,
3346 MemberName name, Attributes attrs, Parameters parameters)
3347 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3349 Parameters = parameters;
3353 // Returns the System.Type array for the parameters of this method
3355 public Type [] ParameterTypes {
3357 return Parameters.Types;
3361 public Parameters ParameterInfo
3368 public ToplevelBlock Block {
3378 protected override bool CheckBase ()
3380 // Check whether arguments were correct.
3381 if (!DefineParameters (Parameters))
3384 if (!base.CheckBase ())
3390 // TODO: create a special method for operators only to make code better
3391 protected bool IsDuplicateImplementation (MethodCore method)
3396 Operator op2 = null;
3397 Operator op1 = null;
3399 if (!(method.MemberName.Equals (MemberName)))
3401 op1 = this as Operator;
3402 if (op1 == null || !(op1.OperatorType == Operator.OpType.Explicit || op1.OperatorType == Operator.OpType.Implicit))
3405 op2 = method as Operator;
3406 if (op2 == null || !(op2.OperatorType == Operator.OpType.Explicit || op2.OperatorType == Operator.OpType.Implicit))
3409 op1 = this as Operator;
3410 op2 = method as Operator;
3413 Type[] param_types = method.ParameterTypes;
3414 // This never happen. Rewrite this as Equal
3415 if (param_types == null && ParameterTypes == null)
3417 if (param_types == null || ParameterTypes == null)
3420 if (param_types.Length != ParameterTypes.Length)
3423 if (method.Parameters.HasArglist != Parameters.HasArglist)
3428 for (int i = 0; i < param_types.Length; i++) {
3429 if (param_types [i] != ParameterTypes [i])
3433 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3436 // TODO: make operator compatible with MethodCore to avoid this
3437 if (op1 != null && op2 != null) {
3438 if (MemberType != method.MemberType)
3444 // Try to report 663: method only differs on out/ref
3446 Parameters info = ParameterInfo;
3447 Parameters other_info = method.ParameterInfo;
3448 for (int i = 0; i < info.Count; i++){
3449 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3450 Report.SymbolRelatedToPreviousError (method);
3451 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3452 GetSignatureForError ());
3457 Report.SymbolRelatedToPreviousError (method);
3458 if (this is Operator && method is Operator)
3459 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3461 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3470 // Returns a string that represents the signature for this
3471 // member which should be used in XML documentation.
3473 public override string GetDocCommentName (DeclSpace ds)
3475 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3479 // Raised (and passed an XmlElement that contains the comment)
3480 // when GenerateDocComment is writing documentation expectedly.
3482 // FIXME: with a few effort, it could be done with XmlReader,
3483 // that means removal of DOM use.
3485 internal override void OnGenerateDocComment (XmlElement el)
3487 DocUtil.OnMethodGenerateDocComment (this, el);
3491 // Represents header string for documentation comment.
3493 public override string DocCommentHeader
3495 get { return "M:"; }
3498 public virtual void SetYields ()
3500 ModFlags |= Modifiers.METHOD_YIELDS;
3503 protected override bool VerifyClsCompliance ()
3505 if (!base.VerifyClsCompliance ())
3508 if (Parameters.HasArglist) {
3509 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3512 if (!AttributeTester.IsClsCompliant (MemberType)) {
3513 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3514 GetSignatureForError ());
3517 Parameters.VerifyClsCompliance ();
3523 public abstract class InterfaceMemberBase : MemberBase {
3525 // Whether this is an interface member.
3527 public bool IsInterface;
3530 // If true, this is an explicit interface implementation
3532 public bool IsExplicitImpl;
3534 protected bool is_external_implementation;
3537 // The interface type we are explicitly implementing
3539 public Type InterfaceType;
3542 // The method we're overriding if this is an override method.
3544 protected MethodInfo base_method;
3546 readonly int explicit_mod_flags;
3547 public MethodAttributes flags;
3549 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3550 Expression type, int mod, int allowed_mod, bool is_iface,
3551 MemberName name, Attributes attrs)
3552 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3555 IsInterface = is_iface;
3556 IsExplicitImpl = (MemberName.Left != null);
3557 explicit_mod_flags = mod;
3560 protected override bool CheckBase ()
3562 if (!base.CheckBase ())
3565 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3571 // Is null for System.Object while compiling corlib and base interfaces
3572 if (Parent.PartialContainer.BaseCache == null) {
3573 if ((ModFlags & Modifiers.NEW) != 0) {
3574 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3579 Type base_ret_type = null;
3580 base_method = FindOutBaseMethod (ref base_ret_type);
3582 // method is override
3583 if (base_method != null) {
3584 if (!CheckMethodAgainstBase (base_ret_type))
3587 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3588 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3590 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3591 Report.SymbolRelatedToPreviousError (base_method);
3592 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3593 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3596 if (OptAttributes != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3597 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3598 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3605 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3606 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3607 if (conflict_symbol != null) {
3608 Report.SymbolRelatedToPreviousError (conflict_symbol);
3610 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3611 else if (this is PropertyBase)
3612 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3614 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3616 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3617 GetSignatureForError (), SimpleName.GetMemberType (this));
3622 if (conflict_symbol == null) {
3623 if ((ModFlags & Modifiers.NEW) != 0) {
3624 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3629 if ((ModFlags & Modifiers.NEW) == 0) {
3630 if (this is Method && conflict_symbol is MethodBase)
3633 Report.SymbolRelatedToPreviousError (conflict_symbol);
3634 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3635 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3642 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3643 // that have been defined.
3645 // `name' is the user visible name for reporting errors (this is used to
3646 // provide the right name regarding method names and properties)
3648 bool CheckMethodAgainstBase (Type base_method_type)
3652 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3653 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3654 Report.Error (506, Location,
3655 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3656 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3660 // Now we check that the overriden method is not final
3662 if (base_method.IsFinal) {
3663 Report.SymbolRelatedToPreviousError (base_method);
3664 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3665 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3669 // Check that the permissions are not being changed
3671 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3672 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3674 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3675 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3679 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3680 Report.SymbolRelatedToPreviousError (base_method);
3681 if (this is PropertyBasedMember) {
3682 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3683 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3686 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3687 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3693 if ((ModFlags & Modifiers.NEW) == 0) {
3694 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3695 ModFlags |= Modifiers.NEW;
3696 Report.SymbolRelatedToPreviousError (base_method);
3697 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3698 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",
3699 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3701 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3702 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3706 if (base_method.IsAbstract && !IsInterface) {
3707 Report.SymbolRelatedToPreviousError (base_method);
3708 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3709 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3717 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3719 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3721 // when overriding protected internal, the method can be declared
3722 // protected internal only within the same assembly
3725 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3726 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3728 // assemblies differ - report an error
3732 } else if (thisp != base_classp) {
3734 // same assembly, but other attributes differ - report an error
3739 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3741 // if it's not "protected internal", it must be "protected"
3745 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3747 // protected within the same assembly - an error
3750 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3751 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3753 // protected ok, but other attributes differ - report an error
3759 return (thisp == base_classp);
3763 protected bool DefineParameters (Parameters parameters)
3765 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3767 if (!parameters.Resolve (rc))
3771 foreach (Parameter p in parameters.FixedParameters) {
3772 if (p.CheckAccessibility (this))
3775 Report.SymbolRelatedToPreviousError (p.ParameterType);
3776 if (this is Indexer)
3777 Report.Error (55, Location,
3778 "Inconsistent accessibility: parameter type `" +
3779 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3780 "accessible than indexer `" + GetSignatureForError () + "'");
3781 else if (this is Operator)
3782 Report.Error (57, Location,
3783 "Inconsistent accessibility: parameter type `" +
3784 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3785 "accessible than operator `" + GetSignatureForError () + "'");
3787 Report.Error (51, Location,
3788 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3789 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3795 protected override bool DoDefine()
3797 if (!base.DoDefine ())
3800 if (IsExplicitImpl) {
3801 Expression expr = MemberName.Left.GetTypeExpression ();
3802 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
3806 InterfaceType = texpr.Type;
3808 if (!InterfaceType.IsInterface) {
3809 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3813 if (!Parent.PartialContainer.VerifyImplements (this))
3820 protected virtual bool DoDefineBase ()
3823 throw new InternalErrorException ();
3826 ModFlags = Modifiers.PUBLIC |
3827 Modifiers.ABSTRACT |
3828 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3830 flags = MethodAttributes.Public |
3831 MethodAttributes.Abstract |
3832 MethodAttributes.HideBySig |
3833 MethodAttributes.NewSlot |
3834 MethodAttributes.Virtual;
3836 if (!Parent.PartialContainer.MethodModifiersValid (this))
3839 flags = Modifiers.MethodAttr (ModFlags);
3842 if (IsExplicitImpl) {
3843 Expression expr = MemberName.Left.GetTypeExpression ();
3844 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
3845 if (iface_texpr == null)
3848 InterfaceType = iface_texpr.Type;
3850 if (!InterfaceType.IsInterface) {
3851 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3855 if (!Parent.PartialContainer.VerifyImplements (this))
3858 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3864 public override void Emit()
3866 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3867 // We are more strict than Microsoft and report CS0626 as error
3868 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3869 Report.Error (626, Location,
3870 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3871 GetSignatureForError ());
3877 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3879 Report.SymbolRelatedToPreviousError (base_method);
3880 string base_name = TypeManager.GetFullNameSignature (base_method);
3881 string this_name = GetSignatureForError ();
3882 if (suffix != null) {
3883 base_name += suffix;
3884 this_name += suffix;
3887 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3888 this_name, Modifiers.GetDescription (ma), base_name);
3891 protected static string Error722 {
3893 return "`{0}': static types cannot be used as return types";
3898 /// For custom member duplication search in a container
3900 protected abstract bool CheckForDuplications ();
3903 /// Gets base method and its return type
3905 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3908 // The "short" name of this property / indexer / event. This is the
3909 // name without the explicit interface.
3911 public string ShortName
3913 get { return MemberName.Name; }
3914 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3917 protected override bool VerifyClsCompliance ()
3919 if (!base.VerifyClsCompliance ()) {
3920 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3921 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3924 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3925 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3930 if (GenericMethod != null)
3931 GenericMethod.VerifyClsCompliance ();
3936 public override bool IsUsed
3938 get { return IsExplicitImpl || base.IsUsed; }
3943 public abstract class MethodOrOperator : MethodCore, IMethodData
3945 public MethodBuilder MethodBuilder;
3946 ReturnParameter return_attributes;
3947 ListDictionary declarative_security;
3948 protected MethodData MethodData;
3951 ArrayList anonymous_methods;
3953 static string[] attribute_targets = new string [] { "method", "return" };
3955 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3956 int allowed_mod, bool is_interface, MemberName name,
3957 Attributes attrs, Parameters parameters)
3958 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3963 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3965 if (a.Target == AttributeTargets.ReturnValue) {
3966 if (return_attributes == null)
3967 return_attributes = new ReturnParameter (MethodBuilder, Location);
3969 return_attributes.ApplyAttributeBuilder (a, cb);
3973 if (a.IsInternalMethodImplAttribute) {
3974 is_external_implementation = true;
3977 if (a.Type == TypeManager.dllimport_type) {
3978 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3979 if ((ModFlags & extern_static) != extern_static) {
3980 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3982 is_external_implementation = true;
3985 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3986 if (declarative_security == null)
3987 declarative_security = new ListDictionary ();
3988 a.ExtractSecurityPermissionSet (declarative_security);
3992 MethodBuilder.SetCustomAttribute (cb);
3995 public override AttributeTargets AttributeTargets {
3997 return AttributeTargets.Method;
4001 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
4003 return new EmitContext (
4004 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
4007 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4009 if (anonymous_methods == null)
4010 anonymous_methods = new ArrayList ();
4011 anonymous_methods.Add (anonymous);
4014 protected bool DefineGenericMethod ()
4016 if (!DoDefineBase ())
4020 if (GenericMethod != null) {
4021 string method_name = MemberName.Name;
4023 if (IsExplicitImpl) {
4024 method_name = TypeManager.CSharpName (InterfaceType) +
4029 MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags, ReturnType, null);
4031 MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags);
4034 if (!GenericMethod.Define (MethodBuilder, block))
4042 public bool ResolveMembers ()
4044 if (!DefineGenericMethod ())
4047 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4048 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
4049 if (iterator == null)
4053 if (anonymous_methods != null) {
4054 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4055 if (!ame.CreateAnonymousHelpers ())
4063 public override bool Define ()
4068 if (!CheckAbstractAndExtern (block != null))
4074 MethodData = new MethodData (
4075 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
4077 if (!MethodData.Define (Parent.PartialContainer))
4080 MethodBuilder = MethodData.MethodBuilder;
4082 if (!TypeManager.IsGenericParameter (MemberType)) {
4083 if (MemberType.IsAbstract && MemberType.IsSealed) {
4084 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4092 public override void Emit ()
4095 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
4096 MethodBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
4098 if (OptAttributes != null)
4099 OptAttributes.Emit ();
4101 if (declarative_security != null) {
4102 foreach (DictionaryEntry de in declarative_security) {
4103 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4110 protected void Error_ConditionalAttributeIsNotValid ()
4112 Report.Error (577, Location,
4113 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4114 GetSignatureForError ());
4117 public override bool MarkForDuplicationCheck ()
4119 caching_flags |= Flags.TestMethodDuplication;
4123 public override string[] ValidAttributeTargets {
4125 return attribute_targets;
4129 #region IMethodData Members
4131 public CallingConventions CallingConventions {
4133 CallingConventions cc = Parameters.CallingConvention;
4134 if (Parameters.HasArglist && block != null)
4135 block.HasVarargs = true;
4138 if ((ModFlags & Modifiers.STATIC) == 0)
4139 cc |= CallingConventions.HasThis;
4141 // FIXME: How is `ExplicitThis' used in C#?
4147 public Type ReturnType {
4153 public MemberName MethodName {
4159 public Iterator Iterator {
4160 get { return iterator; }
4163 public new Location Location {
4165 return base.Location;
4169 protected override bool CheckBase ()
4171 if (!base.CheckBase ())
4174 // TODO: Destructor should derive from MethodCore
4175 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4176 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4177 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4185 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4187 public bool IsExcluded () {
4188 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4189 return (caching_flags & Flags.Excluded) != 0;
4191 caching_flags &= ~Flags.Excluded_Undetected;
4193 if (base_method == null) {
4194 if (OptAttributes == null)
4197 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4202 foreach (Attribute a in attrs) {
4203 string condition = a.GetConditionalAttributeValue ();
4204 if (condition == null)
4207 if (RootContext.AllDefines.Contains (condition))
4211 caching_flags |= Flags.Excluded;
4215 IMethodData md = TypeManager.GetMethod (base_method);
4217 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4218 caching_flags |= Flags.Excluded;
4224 if (md.IsExcluded ()) {
4225 caching_flags |= Flags.Excluded;
4231 GenericMethod IMethodData.GenericMethod {
4233 return GenericMethod;
4241 public class SourceMethod : ISourceMethod
4246 protected SourceMethod (DeclSpace parent, MethodBase builder,
4247 ISourceFile file, Location start, Location end)
4249 this.parent = parent;
4250 this.builder = builder;
4252 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
4255 public string Name {
4256 get { return builder.Name; }
4259 public int NamespaceID {
4260 get { return parent.NamespaceEntry.SymbolFileID; }
4265 if (builder is MethodBuilder)
4266 return ((MethodBuilder) builder).GetToken ().Token;
4267 else if (builder is ConstructorBuilder)
4268 return ((ConstructorBuilder) builder).GetToken ().Token;
4270 throw new NotSupportedException ();
4274 public void CloseMethod ()
4276 if (CodeGen.SymbolWriter != null)
4277 CodeGen.SymbolWriter.CloseMethod ();
4280 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
4282 if (CodeGen.SymbolWriter == null)
4287 Location start_loc = block.StartLocation;
4288 if (start_loc.IsNull)
4291 Location end_loc = block.EndLocation;
4295 ISourceFile file = start_loc.SourceFile;
4299 return new SourceMethod (
4300 parent, builder, file, start_loc, end_loc);
4304 public class Method : MethodOrOperator, IAnonymousHost {
4307 /// Modifiers allowed in a class declaration
4309 const int AllowedModifiers =
4312 Modifiers.PROTECTED |
4313 Modifiers.INTERNAL |
4318 Modifiers.OVERRIDE |
4319 Modifiers.ABSTRACT |
4321 Modifiers.METHOD_YIELDS |
4324 const int AllowedInterfaceModifiers =
4325 Modifiers.NEW | Modifiers.UNSAFE;
4328 // return_type can be "null" for VOID values.
4330 public Method (DeclSpace parent, GenericMethod generic,
4331 Expression return_type, int mod, bool is_iface,
4332 MemberName name, Parameters parameters, Attributes attrs)
4333 : base (parent, generic, return_type, mod,
4334 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4335 is_iface, name, attrs, parameters)
4339 public override string GetSignatureForError()
4341 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4344 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4346 Report.Error (17, location,
4347 "Program `{0}' has more than one entry point defined: `{1}'",
4348 CodeGen.FileName, TypeManager.CSharpSignature(b));
4351 bool IsEntryPoint ()
4353 if (ReturnType != TypeManager.void_type &&
4354 ReturnType != TypeManager.int32_type)
4357 if (Parameters.Count == 0)
4360 if (Parameters.Count > 1)
4363 Type t = Parameters.ParameterType (0);
4364 return t.IsArray && t.GetArrayRank () == 1 &&
4365 TypeManager.GetElementType (t) == TypeManager.string_type &&
4366 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4369 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4371 if (a.Type == TypeManager.conditional_attribute_type) {
4372 if (IsExplicitImpl) {
4373 Error_ConditionalAttributeIsNotValid ();
4377 if (ReturnType != TypeManager.void_type) {
4378 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4382 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4383 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4388 Report.Error (582, Location, "Conditional not valid on interface members");
4392 if (MethodData.implementing != null) {
4393 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4394 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4395 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4399 for (int i = 0; i < Parameters.Count; ++i) {
4400 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4401 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4407 if (a.Type == TypeManager.extension_attribute_type) {
4408 a.Error_MisusedExtensionAttribute ();
4412 base.ApplyAttributeBuilder (a, cb);
4415 protected override bool CheckForDuplications ()
4417 ArrayList ar = Parent.PartialContainer.Methods;
4419 int arLen = ar.Count;
4421 for (int i = 0; i < arLen; i++) {
4422 Method m = (Method) ar [i];
4423 if (IsDuplicateImplementation (m))
4428 ar = Parent.PartialContainer.Properties;
4430 for (int i = 0; i < ar.Count; ++i) {
4431 PropertyBase pb = (PropertyBase) ar [i];
4432 if (pb.AreAccessorsDuplicateImplementation (this))
4437 ar = Parent.PartialContainer.Indexers;
4439 for (int i = 0; i < ar.Count; ++i) {
4440 PropertyBase pb = (PropertyBase) ar [i];
4441 if (pb.AreAccessorsDuplicateImplementation (this))
4446 ar = Parent.PartialContainer.Events;
4448 for (int i = 0; i < ar.Count; ++i) {
4449 Event ev = (Event) ar [i];
4450 if (ev.AreAccessorsDuplicateImplementation (this))
4461 public override bool Define ()
4463 if (!base.Define ())
4466 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4467 Error1599 (Location, ReturnType);
4471 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4472 Name == "Finalize" && !(this is Destructor)) {
4473 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4476 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4477 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4478 Parent.PartialContainer.Mark_HasEquals ();
4479 else if (Parameters.Empty && Name == "GetHashCode")
4480 Parent.PartialContainer.Mark_HasGetHashCode ();
4483 if ((ModFlags & Modifiers.STATIC) == 0)
4486 if (Parameters.HasExtensionMethodType) {
4487 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4488 if (!Parent.IsTopLevel)
4489 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4490 GetSignatureForError ());
4492 if (TypeManager.extension_attribute_type == null)
4493 Report.Error (1110, Location,
4494 "`{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",
4495 GetSignatureForError ());
4497 ModFlags |= Modifiers.METHOD_EXTENSION;
4498 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4499 CodeGen.Assembly.HasExtensionMethods = true;
4501 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4502 GetSignatureForError ());
4507 // This is used to track the Entry Point,
4509 if (RootContext.NeedsEntryPoint &&
4511 (RootContext.MainClass == null ||
4512 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4513 if (IsEntryPoint ()) {
4515 if (RootContext.EntryPoint == null) {
4516 if (Parent.IsGeneric || MemberName.IsGeneric) {
4517 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4518 GetSignatureForError ());
4520 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4521 md.SetMemberIsUsed ();
4523 RootContext.EntryPoint = MethodBuilder;
4524 RootContext.EntryPointLocation = Location;
4527 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4528 Error_DuplicateEntryPoint (MethodBuilder, Location);
4531 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4532 GetSignatureForError ());
4542 public override void Emit ()
4544 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4545 MethodData.Emit (Parent);
4548 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4549 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4555 public static void Error1599 (Location loc, Type t)
4557 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4560 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4562 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4563 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4568 if (mi.IsSpecialName)
4571 base_ret_type = mi.ReturnType;
4575 protected override bool VerifyClsCompliance ()
4577 if (!base.VerifyClsCompliance ())
4580 if (ParameterInfo.Count > 0) {
4581 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4583 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4590 public abstract class ConstructorInitializer {
4591 readonly ArrayList argument_list;
4592 MethodGroupExpr base_constructor_group;
4593 readonly Location loc;
4595 public ConstructorInitializer (ArrayList argument_list, Location loc)
4597 this.argument_list = argument_list;
4601 public ArrayList Arguments {
4603 return argument_list;
4607 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4611 ec.CurrentBlock = block;
4613 if (argument_list != null){
4614 foreach (Argument a in argument_list){
4615 if (!a.Resolve (ec, loc))
4619 ec.CurrentBlock = null;
4621 if (this is ConstructorBaseInitializer) {
4622 if (ec.ContainerType.BaseType == null)
4625 t = ec.ContainerType.BaseType;
4626 if (ec.ContainerType.IsValueType) {
4627 Report.Error (522, loc,
4628 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4633 // It is legal to have "this" initializers that take no arguments
4634 // in structs, they are just no-ops.
4636 // struct D { public D (int a) : this () {}
4638 if (ec.ContainerType.IsValueType && argument_list == null)
4641 t = ec.ContainerType;
4644 base_constructor_group = Expression.MemberLookup (
4645 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4646 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4647 loc) as MethodGroupExpr;
4649 bool error_non_public = false;
4650 if (base_constructor_group == null) {
4651 error_non_public = true;
4652 base_constructor_group = Expression.MemberLookup (
4653 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4654 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4655 loc) as MethodGroupExpr;
4657 // TODO: because of MemberLookup is so broken. It does not return private members
4658 // even if you ask for them.
4659 if (base_constructor_group == null) {
4660 Expression.MemberLookupFailed (ec.ContainerType, t, t, ".ctor", null, true, loc);
4665 base_constructor_group = base_constructor_group.OverloadResolve (
4666 ec, argument_list, false, loc);
4668 if (base_constructor_group == null)
4671 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4673 if (base_ctor == caller_builder){
4674 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4677 if (error_non_public) {
4678 Report.SymbolRelatedToPreviousError (base_ctor);
4679 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_ctor));
4685 public void Emit (EmitContext ec)
4687 // It can be null for static initializers
4688 if (base_constructor_group == null)
4691 ec.Mark (loc, false);
4693 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4695 base_constructor_group.EmitCall (ec, argument_list);
4699 public class ConstructorBaseInitializer : ConstructorInitializer {
4700 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4701 base (argument_list, l)
4706 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4707 public GeneratedBaseInitializer (Location loc):
4713 public class ConstructorThisInitializer : ConstructorInitializer {
4714 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4715 base (argument_list, l)
4720 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4721 public ConstructorBuilder ConstructorBuilder;
4722 public ConstructorInitializer Initializer;
4723 ListDictionary declarative_security;
4724 ArrayList anonymous_methods;
4727 // Modifiers allowed for a constructor.
4729 public const int AllowedModifiers =
4731 Modifiers.PROTECTED |
4732 Modifiers.INTERNAL |
4738 static string[] attribute_targets = new string [] { "method" };
4740 public Iterator Iterator {
4741 get { return null; }
4744 bool has_compliant_args = false;
4746 // The spec claims that static is not permitted, but
4747 // my very own code has static constructors.
4749 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4750 ConstructorInitializer init, Location loc)
4751 : base (parent, null, null, mod, AllowedModifiers, false,
4752 new MemberName (name, loc), null, args)
4757 public bool HasCompliantArgs {
4758 get { return has_compliant_args; }
4761 public override AttributeTargets AttributeTargets {
4762 get { return AttributeTargets.Constructor; }
4767 // Returns true if this is a default constructor
4769 public bool IsDefault ()
4771 if ((ModFlags & Modifiers.STATIC) != 0)
4772 return Parameters.Empty;
4774 return Parameters.Empty &&
4775 (Initializer is ConstructorBaseInitializer) &&
4776 (Initializer.Arguments == null);
4779 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4781 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4782 if (declarative_security == null) {
4783 declarative_security = new ListDictionary ();
4785 a.ExtractSecurityPermissionSet (declarative_security);
4789 if (a.IsInternalMethodImplAttribute) {
4790 is_external_implementation = true;
4793 ConstructorBuilder.SetCustomAttribute (cb);
4796 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4798 if (anonymous_methods == null)
4799 anonymous_methods = new ArrayList ();
4800 anonymous_methods.Add (anonymous);
4803 public bool ResolveMembers ()
4805 if (anonymous_methods != null) {
4806 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4807 if (!ame.CreateAnonymousHelpers ())
4815 protected override bool CheckForDuplications ()
4817 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4819 int arLen = ar.Count;
4821 for (int i = 0; i < arLen; i++) {
4822 Constructor m = (Constructor) ar [i];
4823 if (IsDuplicateImplementation (m))
4830 protected override bool CheckBase ()
4832 if ((ModFlags & Modifiers.STATIC) != 0) {
4833 if (!Parameters.Empty) {
4834 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4835 GetSignatureForError ());
4839 // the rest can be ignored
4843 // Check whether arguments were correct.
4844 if (!DefineParameters (Parameters))
4847 if (!CheckForDuplications ())
4850 if (Parent.PartialContainer.Kind == Kind.Struct) {
4851 if (ParameterTypes.Length == 0) {
4852 Report.Error (568, Location,
4853 "Structs cannot contain explicit parameterless constructors");
4857 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4858 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4863 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0) {
4864 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4871 // Creates the ConstructorBuilder
4873 public override bool Define ()
4875 if (ConstructorBuilder != null)
4878 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4879 MethodAttributes.SpecialName);
4881 if ((ModFlags & Modifiers.STATIC) != 0) {
4882 ca |= MethodAttributes.Static | MethodAttributes.Private;
4884 ca |= MethodAttributes.HideBySig;
4886 if ((ModFlags & Modifiers.PUBLIC) != 0)
4887 ca |= MethodAttributes.Public;
4888 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4889 if ((ModFlags & Modifiers.INTERNAL) != 0)
4890 ca |= MethodAttributes.FamORAssem;
4892 ca |= MethodAttributes.Family;
4893 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4894 ca |= MethodAttributes.Assembly;
4896 ca |= MethodAttributes.Private;
4899 if (!CheckAbstractAndExtern (block != null))
4902 // Check if arguments were correct.
4906 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4907 ca, CallingConventions,
4910 if ((ModFlags & Modifiers.UNSAFE) != 0)
4911 ConstructorBuilder.InitLocals = false;
4913 if (Parent.PartialContainer.IsComImport) {
4914 if (!IsDefault ()) {
4915 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4916 Parent.GetSignatureForError ());
4919 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4922 TypeManager.AddMethod (ConstructorBuilder, this);
4930 public override void Emit ()
4932 if (OptAttributes != null)
4933 OptAttributes.Emit ();
4935 EmitContext ec = CreateEmitContext (null, null);
4937 if (block != null) {
4938 // If this is a non-static `struct' constructor and doesn't have any
4939 // initializer, it must initialize all of the struct's fields.
4940 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4941 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4942 block.AddThisVariable (Parent, Location);
4944 if (!block.ResolveMeta (ec, ParameterInfo))
4948 if ((ModFlags & Modifiers.STATIC) == 0){
4949 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4950 Initializer = new GeneratedBaseInitializer (Location);
4954 // Spec mandates that Initializers will not have
4958 if ((Initializer != null) &&
4959 !Initializer.Resolve (ConstructorBuilder, block, ec))
4961 ec.IsStatic = false;
4964 Parameters.ApplyAttributes (ConstructorBuilder);
4966 SourceMethod source = SourceMethod.Create (
4967 Parent, ConstructorBuilder, block);
4970 // Classes can have base initializers and instance field initializers.
4972 if (Parent.PartialContainer.Kind == Kind.Class){
4973 if ((ModFlags & Modifiers.STATIC) == 0){
4976 // If we use a "this (...)" constructor initializer, then
4977 // do not emit field initializers, they are initialized in the other constructor
4979 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4980 Parent.PartialContainer.EmitFieldInitializers (ec);
4984 bool unreachable = false;
4985 if (block != null) {
4986 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4988 ec.EmitMeta (block);
4990 if (block.ScopeInfo != null) {
4991 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4992 init.EmitStatement (ec);
4996 if (Initializer != null) {
4997 Initializer.Emit (ec);
5000 if ((ModFlags & Modifiers.STATIC) != 0)
5001 Parent.PartialContainer.EmitFieldInitializers (ec);
5004 ec.EmitResolvedTopBlock (block, unreachable);
5007 source.CloseMethod ();
5011 if (declarative_security != null) {
5012 foreach (DictionaryEntry de in declarative_security) {
5013 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5020 // Is never override
5021 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5026 public override string GetSignatureForError()
5028 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
5031 public override string[] ValidAttributeTargets {
5033 return attribute_targets;
5037 protected override bool VerifyClsCompliance ()
5039 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
5043 if (ParameterInfo.Count > 0) {
5044 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
5046 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
5048 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
5049 foreach (Type param in ParameterTypes) {
5050 if (param.IsArray) {
5056 has_compliant_args = true;
5060 #region IMethodData Members
5062 public System.Reflection.CallingConventions CallingConventions {
5064 CallingConventions cc = Parameters.CallingConvention;
5066 if (Parent.PartialContainer.Kind == Kind.Class)
5067 if ((ModFlags & Modifiers.STATIC) == 0)
5068 cc |= CallingConventions.HasThis;
5070 // FIXME: How is `ExplicitThis' used in C#?
5076 public new Location Location {
5078 return base.Location;
5082 public MemberName MethodName {
5088 public Type ReturnType {
5094 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5096 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5097 return new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5100 public bool IsExcluded()
5105 GenericMethod IMethodData.GenericMethod {
5115 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5117 public interface IMethodData
5119 CallingConventions CallingConventions { get; }
5120 Location Location { get; }
5121 MemberName MethodName { get; }
5122 Type ReturnType { get; }
5123 GenericMethod GenericMethod { get; }
5124 Parameters ParameterInfo { get; }
5126 Iterator Iterator { get; }
5128 Attributes OptAttributes { get; }
5129 ToplevelBlock Block { get; set; }
5131 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5132 ObsoleteAttribute GetObsoleteAttribute ();
5133 string GetSignatureForError ();
5135 bool IsClsComplianceRequired ();
5136 void SetMemberIsUsed ();
5140 // Encapsulates most of the Method's state
5142 public class MethodData {
5144 readonly IMethodData method;
5146 public readonly GenericMethod GenericMethod;
5149 // Are we implementing an interface ?
5151 public MethodInfo implementing;
5156 protected InterfaceMemberBase member;
5157 protected int modifiers;
5158 protected MethodAttributes flags;
5159 protected Type declaring_type;
5160 protected MethodInfo parent_method;
5162 MethodBuilder builder = null;
5163 public MethodBuilder MethodBuilder {
5169 public Type DeclaringType {
5171 return declaring_type;
5175 public MethodData (InterfaceMemberBase member,
5176 int modifiers, MethodAttributes flags, IMethodData method)
5178 this.member = member;
5179 this.modifiers = modifiers;
5182 this.method = method;
5185 public MethodData (InterfaceMemberBase member,
5186 int modifiers, MethodAttributes flags,
5187 IMethodData method, MethodBuilder builder,
5188 GenericMethod generic, MethodInfo parent_method)
5189 : this (member, modifiers, flags, method)
5191 this.builder = builder;
5192 this.GenericMethod = generic;
5193 this.parent_method = parent_method;
5196 public bool Define (DeclSpace parent)
5198 string name = method.MethodName.Basename;
5199 string method_name = method.MethodName.FullName;
5201 TypeContainer container = parent.PartialContainer;
5203 PendingImplementation pending = container.PendingImplementations;
5204 if (pending != null){
5205 if (member is Indexer) // TODO: test it, but it should work without this IF
5206 implementing = pending.IsInterfaceIndexer (
5207 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5209 implementing = pending.IsInterfaceMethod (
5210 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5212 if (member.InterfaceType != null){
5213 if (implementing == null){
5214 if (member is PropertyBase) {
5215 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5216 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5217 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5220 Report.Error (539, method.Location,
5221 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5222 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5226 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5227 Report.SymbolRelatedToPreviousError (implementing);
5228 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5229 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5233 method_name = member.InterfaceType.FullName +
5236 if (implementing != null) {
5237 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5238 if (prop_method == null) {
5239 if (implementing.IsSpecialName) {
5240 Report.SymbolRelatedToPreviousError (implementing);
5241 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5242 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5243 implementing.Name.StartsWith ("get_") ? "get" : "set");
5246 } else if (implementing.DeclaringType.IsInterface) {
5247 if (!implementing.IsSpecialName) {
5248 Report.SymbolRelatedToPreviousError (implementing);
5249 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5250 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5253 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5254 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5255 Report.SymbolRelatedToPreviousError (implementing);
5256 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5257 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5266 // For implicit implementations, make sure we are public, for
5267 // explicit implementations, make sure we are private.
5269 if (implementing != null){
5271 // Setting null inside this block will trigger a more
5272 // verbose error reporting for missing interface implementations
5274 // The "candidate" function has been flagged already
5275 // but it wont get cleared
5277 if (member.IsExplicitImpl){
5278 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5279 Report.SymbolRelatedToPreviousError (implementing);
5280 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5281 method.GetSignatureForError ());
5285 if (implementing.DeclaringType.IsInterface) {
5287 // If this is an interface method implementation,
5288 // check for public accessibility
5290 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5292 implementing = null;
5294 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5295 // We may never be private.
5296 implementing = null;
5298 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5300 // We may be protected if we're overriding something.
5302 implementing = null;
5307 // Static is not allowed
5309 if ((modifiers & Modifiers.STATIC) != 0){
5310 implementing = null;
5315 // If implementing is still valid, set flags
5317 if (implementing != null){
5319 // When implementing interface methods, set NewSlot
5320 // unless, we are overwriting a method.
5322 if (implementing.DeclaringType.IsInterface){
5323 if ((modifiers & Modifiers.OVERRIDE) == 0)
5324 flags |= MethodAttributes.NewSlot;
5327 MethodAttributes.Virtual |
5328 MethodAttributes.HideBySig;
5330 // Set Final unless we're virtual, abstract or already overriding a method.
5331 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5332 flags |= MethodAttributes.Final;
5335 EmitContext ec = method.CreateEmitContext (container, null);
5337 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
5339 if (builder == null)
5342 if (container.CurrentType != null)
5343 declaring_type = container.CurrentType;
5345 declaring_type = container.TypeBuilder;
5347 if ((modifiers & Modifiers.UNSAFE) != 0)
5348 builder.InitLocals = false;
5351 if (implementing != null){
5353 // clear the pending implemntation flag
5355 if (member is Indexer) {
5356 pending.ImplementIndexer (
5357 member.InterfaceType, builder, method.ReturnType,
5358 method.ParameterInfo, member.IsExplicitImpl);
5360 pending.ImplementMethod (
5361 member.InterfaceType, name, method.ReturnType,
5362 method.ParameterInfo, member.IsExplicitImpl);
5364 if (member.IsExplicitImpl)
5365 container.TypeBuilder.DefineMethodOverride (
5366 builder, implementing);
5369 TypeManager.AddMethod (builder, method);
5371 if (GenericMethod != null) {
5372 bool is_override = member.IsExplicitImpl |
5373 ((modifiers & Modifiers.OVERRIDE) != 0);
5375 if (implementing != null)
5376 parent_method = implementing;
5378 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5387 /// Create the MethodBuilder for the method
5389 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5391 if (builder == null) {
5392 builder = container.TypeBuilder.DefineMethod (
5393 method_name, flags, method.CallingConventions,
5394 method.ReturnType, ParameterTypes);
5398 #if GMCS_SOURCE && !MS_COMPATIBLE
5399 builder.SetGenericMethodSignature (
5400 flags, method.CallingConventions,
5401 method.ReturnType, ParameterTypes);
5408 public void Emit (DeclSpace parent)
5410 ToplevelBlock block = method.Block;
5414 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5416 ec = method.CreateEmitContext (parent, null);
5418 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5420 if (GenericMethod != null)
5421 GenericMethod.EmitAttributes ();
5423 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5426 // Handle destructors specially
5428 // FIXME: This code generates buggy code
5430 if (member is Destructor)
5431 EmitDestructor (ec, block);
5433 ec.EmitTopBlock (method, block);
5436 source.CloseMethod ();
5439 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5441 ILGenerator ig = ec.ig;
5443 Label finish = ig.DefineLabel ();
5445 block.SetDestructor ();
5447 ig.BeginExceptionBlock ();
5448 ec.ReturnLabel = finish;
5449 ec.HasReturnLabel = true;
5450 ec.EmitTopBlock (method, block);
5452 // ig.MarkLabel (finish);
5453 ig.BeginFinallyBlock ();
5455 if (ec.ContainerType.BaseType != null) {
5456 Expression member_lookup = Expression.MemberLookup (
5457 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5458 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5460 if (member_lookup != null){
5461 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5463 ig.Emit (OpCodes.Ldarg_0);
5464 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5468 ig.EndExceptionBlock ();
5469 //ig.MarkLabel (ec.ReturnLabel);
5470 ig.Emit (OpCodes.Ret);
5474 // TODO: Should derive from MethodCore
5475 public class Destructor : Method {
5477 static string[] attribute_targets = new string [] { "method" };
5479 public Destructor (DeclSpace parent, Expression return_type, int mod,
5480 string name, Parameters parameters, Attributes attrs,
5482 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5486 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5488 if (a.Type == TypeManager.conditional_attribute_type) {
5489 Error_ConditionalAttributeIsNotValid ();
5493 base.ApplyAttributeBuilder (a, cb);
5496 public override string GetSignatureForError ()
5498 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5501 public override string[] ValidAttributeTargets {
5503 return attribute_targets;
5508 abstract public class MemberBase : MemberCore {
5509 public Expression Type;
5510 public readonly DeclSpace ds;
5511 public readonly GenericMethod GenericMethod;
5514 // The type of this property / indexer / event
5516 protected Type member_type;
5517 public Type MemberType {
5519 if (member_type == null && Type != null) {
5520 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5521 Type = Type.ResolveAsTypeTerminal (rc, false);
5523 member_type = Type.Type;
5531 // The constructor is only exposed to our children
5533 protected MemberBase (DeclSpace parent, GenericMethod generic,
5534 Expression type, int mod, int allowed_mod, int def_mod,
5535 MemberName name, Attributes attrs)
5536 : base (parent, name, attrs)
5538 this.ds = generic != null ? generic : (DeclSpace) parent;
5540 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5541 GenericMethod = generic;
5542 if (GenericMethod != null)
5543 GenericMethod.ModFlags = ModFlags;
5546 protected virtual bool CheckBase ()
5548 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5549 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5553 if (Report.WarningLevel >= 4 &&
5554 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5555 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5556 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5557 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5562 protected virtual bool DoDefine ()
5564 if (MemberType == null)
5567 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5568 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5569 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5570 GetSignatureForError (), Parent.GetSignatureForError ());
5574 // verify accessibility
5575 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5576 Report.SymbolRelatedToPreviousError (MemberType);
5577 if (this is Property)
5578 Report.Error (53, Location,
5579 "Inconsistent accessibility: property type `" +
5580 TypeManager.CSharpName (MemberType) + "' is less " +
5581 "accessible than property `" + GetSignatureForError () + "'");
5582 else if (this is Indexer)
5583 Report.Error (54, Location,
5584 "Inconsistent accessibility: indexer return type `" +
5585 TypeManager.CSharpName (MemberType) + "' is less " +
5586 "accessible than indexer `" + GetSignatureForError () + "'");
5587 else if (this is MethodCore) {
5588 if (this is Operator)
5589 Report.Error (56, Location,
5590 "Inconsistent accessibility: return type `" +
5591 TypeManager.CSharpName (MemberType) + "' is less " +
5592 "accessible than operator `" + GetSignatureForError () + "'");
5594 Report.Error (50, Location,
5595 "Inconsistent accessibility: return type `" +
5596 TypeManager.CSharpName (MemberType) + "' is less " +
5597 "accessible than method `" + GetSignatureForError () + "'");
5599 Report.Error (52, Location,
5600 "Inconsistent accessibility: field type `" +
5601 TypeManager.CSharpName (MemberType) + "' is less " +
5602 "accessible than field `" + GetSignatureForError () + "'");
5610 protected bool IsTypePermitted ()
5612 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5613 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5621 // Abstract class for all fields
5623 abstract public class FieldBase : MemberBase {
5624 public FieldBuilder FieldBuilder;
5625 public Status status;
5626 protected Expression initializer;
5629 public enum Status : byte {
5630 HAS_OFFSET = 4 // Used by FieldMember.
5633 static readonly string[] attribute_targets = new string [] { "field" };
5635 protected FieldBase (DeclSpace parent, Expression type, int mod,
5636 int allowed_mod, MemberName name, Attributes attrs)
5637 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5640 if ((mod & Modifiers.ABSTRACT) != 0)
5641 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5644 public override AttributeTargets AttributeTargets {
5646 return AttributeTargets.Field;
5650 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5652 if (a.Type == TypeManager.field_offset_attribute_type) {
5653 status |= Status.HAS_OFFSET;
5655 if (!Parent.PartialContainer.HasExplicitLayout) {
5656 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5660 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5661 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5667 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5668 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5673 if (a.Type == TypeManager.marshal_as_attr_type) {
5674 UnmanagedMarshal marshal = a.GetMarshal (this);
5675 if (marshal != null) {
5676 FieldBuilder.SetMarshal (marshal);
5681 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5682 a.Error_InvalidSecurityParent ();
5686 FieldBuilder.SetCustomAttribute (cb);
5689 protected override bool CheckBase ()
5691 if (!base.CheckBase ())
5694 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5695 if (conflict_symbol == null) {
5696 if ((ModFlags & Modifiers.NEW) != 0) {
5697 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5702 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5703 Report.SymbolRelatedToPreviousError (conflict_symbol);
5704 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5705 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5711 public override bool Define()
5713 if (MemberType == null || Type == null)
5716 if (TypeManager.IsGenericParameter (MemberType))
5719 if (MemberType == TypeManager.void_type) {
5720 // TODO: wrong location
5721 Expression.Error_VoidInvalidInTheContext (Location);
5725 if (MemberType.IsSealed && MemberType.IsAbstract) {
5726 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5733 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5734 Report.Error (52, Location,
5735 "Inconsistent accessibility: field type `" +
5736 TypeManager.CSharpName (MemberType) + "' is less " +
5737 "accessible than field `" + GetSignatureForError () + "'");
5741 if (!IsTypePermitted ())
5748 // Represents header string for documentation comment.
5750 public override string DocCommentHeader {
5751 get { return "F:"; }
5754 public override void Emit ()
5757 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5758 FieldBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
5762 if (OptAttributes != null) {
5763 OptAttributes.Emit ();
5766 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5767 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5773 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5775 Report.SymbolRelatedToPreviousError (static_class);
5776 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5780 public Expression Initializer {
5782 if (value != null) {
5783 this.initializer = value;
5788 protected virtual bool IsFieldClsCompliant {
5790 if (FieldBuilder == null)
5793 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5797 public override string[] ValidAttributeTargets
5800 return attribute_targets;
5804 protected override bool VerifyClsCompliance ()
5806 if (!base.VerifyClsCompliance ())
5809 if (!IsFieldClsCompliant) {
5810 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5815 public void SetAssigned ()
5817 caching_flags |= Flags.IsAssigned;
5821 interface IFixedBuffer
5823 FieldInfo Element { get; }
5824 Type ElementType { get; }
5827 public class FixedFieldExternal: IFixedBuffer
5829 FieldInfo element_field;
5831 public FixedFieldExternal (FieldInfo fi)
5833 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5836 #region IFixedField Members
5838 public FieldInfo Element {
5840 return element_field;
5844 public Type ElementType {
5846 return element_field.FieldType;
5854 /// Fixed buffer implementation
5856 public class FixedField : FieldBase, IFixedBuffer
5858 public const string FixedElementName = "FixedElementField";
5859 static int GlobalCounter = 0;
5860 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5861 static FieldInfo[] fi;
5863 TypeBuilder fixed_buffer_type;
5864 FieldBuilder element;
5865 Expression size_expr;
5868 const int AllowedModifiers =
5871 Modifiers.PROTECTED |
5872 Modifiers.INTERNAL |
5875 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5876 Expression size_expr, Attributes attrs, Location loc):
5877 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5879 if (RootContext.Version == LanguageVersion.ISO_1)
5880 Report.FeatureIsNotISO1 (loc, "fixed size buffers");
5882 if ((mod & Modifiers.VOLATILE) != 0)
5883 Modifiers.Error_InvalidModifier (loc, Modifiers.Name (Modifiers.VOLATILE));
5885 this.size_expr = size_expr;
5888 public override bool Define()
5891 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5892 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5895 if (Parent.PartialContainer.Kind != Kind.Struct) {
5896 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5897 GetSignatureForError ());
5900 if (!Parent.IsInUnsafeScope)
5901 Expression.UnsafeError (Location);
5903 if (!base.Define ())
5906 if (!TypeManager.IsPrimitiveType (MemberType)) {
5907 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",
5908 GetSignatureForError ());
5912 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5913 Constant c = size_expr.ResolveAsConstant (ec, this);
5917 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5918 if (buffer_size_const == null)
5921 buffer_size = buffer_size_const.Value;
5923 if (buffer_size <= 0) {
5924 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5928 int type_size = Expression.GetTypeSize (MemberType);
5930 if (buffer_size > int.MaxValue / type_size) {
5931 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5932 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5936 buffer_size *= type_size;
5939 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5941 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5942 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5943 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5944 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5946 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5947 TypeManager.RegisterFieldBase (FieldBuilder, this);
5952 public override void Emit()
5955 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5957 object[] fi_val = new object[1];
5958 fi_val [0] = buffer_size;
5960 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5961 ctor_args, fi, fi_val);
5962 fixed_buffer_type.SetCustomAttribute (cab);
5965 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5966 FieldBuilder.SetCustomAttribute (cab);
5971 protected override bool IsFieldClsCompliant {
5977 #region IFixedField Members
5979 public FieldInfo Element {
5985 public Type ElementType {
5995 // The Field class is used to represents class/struct fields during parsing.
5997 public class Field : FieldBase {
5999 // Modifiers allowed in a class declaration
6001 const int AllowedModifiers =
6004 Modifiers.PROTECTED |
6005 Modifiers.INTERNAL |
6008 Modifiers.VOLATILE |
6012 public Field (DeclSpace parent, Expression type, int mod, string name,
6013 Attributes attrs, Location loc)
6014 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6019 public override bool Define ()
6021 if (!base.Define ())
6024 if ((ModFlags & Modifiers.VOLATILE) != 0){
6025 if (!MemberType.IsClass){
6026 Type vt = MemberType;
6028 if (TypeManager.IsEnumType (vt))
6029 vt = TypeManager.EnumToUnderlying (MemberType);
6031 if (!((vt == TypeManager.bool_type) ||
6032 (vt == TypeManager.sbyte_type) ||
6033 (vt == TypeManager.byte_type) ||
6034 (vt == TypeManager.short_type) ||
6035 (vt == TypeManager.ushort_type) ||
6036 (vt == TypeManager.int32_type) ||
6037 (vt == TypeManager.uint32_type) ||
6038 (vt == TypeManager.char_type) ||
6039 (vt == TypeManager.float_type) ||
6040 (!vt.IsValueType))){
6041 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6042 GetSignatureForError (), TypeManager.CSharpName (vt));
6047 if ((ModFlags & Modifiers.READONLY) != 0){
6048 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6049 GetSignatureForError ());
6054 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6056 if (Parent.PartialContainer.Kind == Kind.Struct &&
6057 ((fa & FieldAttributes.Static) == 0) &&
6058 MemberType == Parent.TypeBuilder &&
6059 !TypeManager.IsBuiltinType (MemberType)){
6060 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6061 "' causes a cycle in the structure layout");
6066 FieldBuilder = Parent.TypeBuilder.DefineField (
6067 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6069 TypeManager.RegisterFieldBase (FieldBuilder, this);
6071 catch (ArgumentException) {
6072 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6076 if (initializer != null)
6077 Parent.PartialContainer.RegisterFieldForInitialization (this,
6078 new FieldInitializer (FieldBuilder, initializer, Parent));
6083 protected override bool VerifyClsCompliance ()
6085 if (!base.VerifyClsCompliance ())
6088 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6089 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6097 // `set' and `get' accessors are represented with an Accessor.
6099 public class Accessor : IAnonymousHost {
6101 // Null if the accessor is empty, or a Block if not
6103 public const int AllowedModifiers =
6105 Modifiers.PROTECTED |
6106 Modifiers.INTERNAL |
6109 public ToplevelBlock Block;
6110 public Attributes Attributes;
6111 public Location Location;
6112 public int ModFlags;
6114 public ArrayList AnonymousMethods;
6116 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6121 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6124 public void SetYields ()
6129 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6131 if (AnonymousMethods == null)
6132 AnonymousMethods = new ArrayList ();
6133 AnonymousMethods.Add (ame);
6137 // Ooouh Martin, templates are missing here.
6138 // When it will be possible move here a lot of child code and template method type.
6139 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6140 protected MethodData method_data;
6141 protected ToplevelBlock block;
6142 protected ListDictionary declarative_security;
6144 // The accessor are created event if they are not wanted.
6145 // But we need them because their names are reserved.
6146 // Field says whether accessor will be emited or not
6147 public readonly bool IsDummy;
6149 protected readonly string prefix;
6151 ReturnParameter return_attributes;
6153 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6154 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6156 this.prefix = prefix;
6160 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6162 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6163 accessor.Attributes)
6165 this.prefix = prefix;
6166 this.block = accessor.Block;
6169 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6171 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6174 public void UpdateName (InterfaceMemberBase member)
6176 SetMemberName (SetupName (prefix, member, Location));
6179 #region IMethodData Members
6181 public abstract Iterator Iterator {
6185 public ToplevelBlock Block {
6195 public CallingConventions CallingConventions {
6197 return CallingConventions.Standard;
6201 public bool IsExcluded ()
6206 GenericMethod IMethodData.GenericMethod {
6212 public MemberName MethodName {
6218 public Type[] ParameterTypes {
6220 return ParameterInfo.Types;
6224 public abstract Parameters ParameterInfo { get ; }
6225 public abstract Type ReturnType { get; }
6226 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6230 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6232 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6233 a.Type == TypeManager.conditional_attribute_type) {
6234 Report.Error (1667, a.Location,
6235 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6236 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6240 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6241 if (declarative_security == null)
6242 declarative_security = new ListDictionary ();
6243 a.ExtractSecurityPermissionSet (declarative_security);
6247 if (a.Target == AttributeTargets.Method) {
6248 method_data.MethodBuilder.SetCustomAttribute (cb);
6252 if (a.Target == AttributeTargets.ReturnValue) {
6253 if (return_attributes == null)
6254 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6256 return_attributes.ApplyAttributeBuilder (a, cb);
6260 ApplyToExtraTarget (a, cb);
6263 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6265 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6268 // It is not supported for the accessors
6269 public sealed override bool Define()
6271 throw new NotSupportedException ();
6274 public void Emit (DeclSpace parent)
6276 EmitMethod (parent);
6279 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6280 method_data.MethodBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
6282 if (OptAttributes != null)
6283 OptAttributes.Emit ();
6285 if (declarative_security != null) {
6286 foreach (DictionaryEntry de in declarative_security) {
6287 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6294 protected virtual void EmitMethod (DeclSpace parent)
6296 method_data.Emit (parent);
6299 public override bool IsClsComplianceRequired()
6304 public bool IsDuplicateImplementation (MethodCore method)
6306 if (!MemberName.Equals (method.MemberName))
6309 Type[] param_types = method.ParameterTypes;
6311 if (param_types == null || param_types.Length != ParameterTypes.Length)
6314 for (int i = 0; i < param_types.Length; i++)
6315 if (param_types [i] != ParameterTypes [i])
6318 Report.SymbolRelatedToPreviousError (method);
6319 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6323 public override bool IsUsed
6333 public new Location Location {
6335 return base.Location;
6339 public virtual bool ResolveMembers ()
6345 // Represents header string for documentation comment.
6347 public override string DocCommentHeader {
6348 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6354 // Properties and Indexers both generate PropertyBuilders, we use this to share
6355 // their common bits.
6357 abstract public class PropertyBase : PropertyBasedMember {
6359 public class GetMethod : PropertyMethod
6361 static string[] attribute_targets = new string [] { "method", "return" };
6363 public GetMethod (PropertyBase method):
6364 base (method, "get_")
6368 public GetMethod (PropertyBase method, Accessor accessor):
6369 base (method, accessor, "get_")
6373 public override MethodBuilder Define (DeclSpace parent)
6375 if (!CheckForDuplications ())
6381 base.Define (parent);
6383 method_data = new MethodData (method, ModFlags, flags, this);
6385 if (!method_data.Define (parent))
6388 return method_data.MethodBuilder;
6391 public override Type ReturnType {
6393 return method.MemberType;
6397 public override Parameters ParameterInfo {
6399 return Parameters.EmptyReadOnlyParameters;
6403 public override string[] ValidAttributeTargets {
6405 return attribute_targets;
6410 public class SetMethod : PropertyMethod {
6412 static string[] attribute_targets = new string [] { "method", "param", "return" };
6413 ImplicitParameter param_attr;
6414 protected Parameters parameters;
6416 public SetMethod (PropertyBase method):
6417 base (method, "set_")
6421 public SetMethod (PropertyBase method, Accessor accessor):
6422 base (method, accessor, "set_")
6426 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6428 if (a.Target == AttributeTargets.Parameter) {
6429 if (param_attr == null)
6430 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6432 param_attr.ApplyAttributeBuilder (a, cb);
6436 base.ApplyAttributeBuilder (a, cb);
6439 public override Parameters ParameterInfo {
6441 if (parameters == null)
6442 DefineParameters ();
6447 protected virtual void DefineParameters ()
6449 parameters = Parameters.CreateFullyResolved (
6450 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6453 public override MethodBuilder Define (DeclSpace parent)
6455 if (!CheckForDuplications ())
6461 base.Define (parent);
6463 method_data = new MethodData (method, ModFlags, flags, this);
6465 if (!method_data.Define (parent))
6468 return method_data.MethodBuilder;
6471 public override Type ReturnType {
6473 return TypeManager.void_type;
6477 public override string[] ValidAttributeTargets {
6479 return attribute_targets;
6484 static string[] attribute_targets = new string [] { "property" };
6486 public abstract class PropertyMethod : AbstractPropertyEventMethod
6488 protected readonly PropertyBase method;
6489 protected MethodAttributes flags;
6491 ArrayList anonymous_methods;
6494 public PropertyMethod (PropertyBase method, string prefix)
6495 : base (method, prefix)
6497 this.method = method;
6500 public PropertyMethod (PropertyBase method, Accessor accessor,
6502 : base (method, accessor, prefix)
6504 this.method = method;
6505 this.ModFlags = accessor.ModFlags;
6506 yields = accessor.Yields;
6507 anonymous_methods = accessor.AnonymousMethods;
6509 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6510 Report.FeatureIsNotISO1 (Location, "access modifiers on properties");
6514 public override Iterator Iterator {
6515 get { return iterator; }
6518 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6520 if (a.IsInternalMethodImplAttribute) {
6521 method.is_external_implementation = true;
6524 base.ApplyAttributeBuilder (a, cb);
6527 public override AttributeTargets AttributeTargets {
6529 return AttributeTargets.Method;
6533 public override bool IsClsComplianceRequired ()
6535 return method.IsClsComplianceRequired ();
6538 public override bool ResolveMembers ()
6541 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6542 if (iterator == null)
6546 if (anonymous_methods != null) {
6547 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6548 if (!ame.CreateAnonymousHelpers ())
6556 public virtual MethodBuilder Define (DeclSpace parent)
6558 TypeContainer container = parent.PartialContainer;
6561 // Check for custom access modifier
6563 if ((ModFlags & Modifiers.Accessibility) == 0) {
6564 ModFlags |= method.ModFlags;
6565 flags = method.flags;
6567 if (container.Kind == Kind.Interface)
6568 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6569 GetSignatureForError ());
6571 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6572 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6575 CheckModifiers (ModFlags);
6576 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6577 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6578 flags = Modifiers.MethodAttr (ModFlags);
6579 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6582 CheckAbstractAndExtern (block != null);
6586 public bool HasCustomAccessModifier
6589 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6593 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6595 return new EmitContext (method,
6596 ds, method.ds, method.Location, ig, ReturnType,
6597 method.ModFlags, false);
6600 public override ObsoleteAttribute GetObsoleteAttribute ()
6602 return method.GetObsoleteAttribute ();
6605 public override string GetSignatureForError()
6607 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6610 void CheckModifiers (int modflags)
6612 modflags &= Modifiers.Accessibility;
6614 int mflags = method.ModFlags & Modifiers.Accessibility;
6616 if ((mflags & Modifiers.PUBLIC) != 0) {
6617 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6619 else if ((mflags & Modifiers.PROTECTED) != 0) {
6620 if ((mflags & Modifiers.INTERNAL) != 0)
6621 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6623 flags |= Modifiers.PRIVATE;
6625 else if ((mflags & Modifiers.INTERNAL) != 0)
6626 flags |= Modifiers.PRIVATE;
6628 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6629 Report.Error (273, Location,
6630 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6631 GetSignatureForError (), method.GetSignatureForError ());
6635 public override bool MarkForDuplicationCheck ()
6637 caching_flags |= Flags.TestMethodDuplication;
6641 protected bool CheckForDuplications ()
6643 if ((caching_flags & Flags.TestMethodDuplication) == 0)
6646 ArrayList ar = Parent.PartialContainer.Methods;
6648 int arLen = ar.Count;
6650 for (int i = 0; i < arLen; i++) {
6651 Method m = (Method) ar [i];
6652 if (IsDuplicateImplementation (m))
6661 public PropertyMethod Get, Set;
6662 public PropertyBuilder PropertyBuilder;
6663 public MethodBuilder GetBuilder, SetBuilder;
6665 protected bool define_set_first = false;
6667 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6668 int allowed_mod, bool is_iface, MemberName name,
6669 Attributes attrs, bool define_set_first)
6670 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6672 this.define_set_first = define_set_first;
6675 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6677 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6678 a.Error_InvalidSecurityParent ();
6682 PropertyBuilder.SetCustomAttribute (cb);
6685 public override AttributeTargets AttributeTargets {
6687 return AttributeTargets.Property;
6691 public override bool Define ()
6696 if (!IsTypePermitted ())
6702 protected override bool DoDefine ()
6704 if (!base.DoDefine ())
6708 // Accessors modifiers check
6710 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6711 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6712 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6713 GetSignatureForError ());
6717 if ((Get.IsDummy || Set.IsDummy)
6718 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6719 Report.Error (276, Location,
6720 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6721 GetSignatureForError ());
6725 if (MemberType.IsAbstract && MemberType.IsSealed) {
6726 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6735 GetBuilder = Get.Define (Parent);
6736 return (Get.IsDummy) ? true : GetBuilder != null;
6739 bool DefineSet (bool define)
6744 SetBuilder = Set.Define (Parent);
6745 return (Set.IsDummy) ? true : SetBuilder != null;
6748 protected bool DefineAccessors ()
6750 return DefineSet (define_set_first) &&
6752 DefineSet (!define_set_first);
6755 protected abstract PropertyInfo ResolveBaseProperty ();
6757 // TODO: rename to Resolve......
6758 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6760 PropertyInfo base_property = ResolveBaseProperty ();
6761 if (base_property == null)
6764 base_ret_type = base_property.PropertyType;
6765 MethodInfo get_accessor = base_property.GetGetMethod (true);
6766 MethodInfo set_accessor = base_property.GetSetMethod (true);
6767 MethodAttributes get_accessor_access, set_accessor_access;
6769 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6770 if (Get != null && !Get.IsDummy && get_accessor == null) {
6771 Report.SymbolRelatedToPreviousError (base_property);
6772 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6775 if (Set != null && !Set.IsDummy && set_accessor == null) {
6776 Report.SymbolRelatedToPreviousError (base_property);
6777 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6782 // Check base class accessors access
6785 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6786 get_accessor_access = set_accessor_access = 0;
6787 if ((ModFlags & Modifiers.NEW) == 0) {
6788 if (get_accessor != null) {
6789 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6790 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6792 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6793 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6796 if (set_accessor != null) {
6797 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6798 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6800 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6801 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6805 // When one accessor does not exist and property hides base one
6806 // we need to propagate this upwards
6807 if (set_accessor == null)
6808 set_accessor = get_accessor;
6811 // Get the less restrictive access
6813 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6816 public override void Emit ()
6819 // The PropertyBuilder can be null for explicit implementations, in that
6820 // case, we do not actually emit the ".property", so there is nowhere to
6821 // put the attribute
6823 if (PropertyBuilder != null && OptAttributes != null)
6824 OptAttributes.Emit ();
6836 /// Tests whether accessors are not in collision with some method (CS0111)
6838 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6840 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6843 public override bool IsUsed
6849 return Get.IsUsed | Set.IsUsed;
6853 protected override void SetMemberName (MemberName new_name)
6855 base.SetMemberName (new_name);
6857 Get.UpdateName (this);
6858 Set.UpdateName (this);
6861 public override string[] ValidAttributeTargets {
6863 return attribute_targets;
6868 // Represents header string for documentation comment.
6870 public override string DocCommentHeader {
6871 get { return "P:"; }
6875 public class Property : PropertyBase {
6876 const int AllowedModifiers =
6879 Modifiers.PROTECTED |
6880 Modifiers.INTERNAL |
6884 Modifiers.OVERRIDE |
6885 Modifiers.ABSTRACT |
6888 Modifiers.METHOD_YIELDS |
6891 const int AllowedInterfaceModifiers =
6894 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6897 Field field = new Field (
6899 Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & Modifiers.STATIC),
6900 CompilerGeneratedClass.MakeName (null, "CompilerGeneratedField"),
6902 ((TypeContainer)Parent).AddField (field);
6905 get_block.Block = new ToplevelBlock (block, null, Location);
6906 Return r = new Return (new SimpleName(field.Name, Location), Location);
6907 get_block.Block.AddStatement (r);
6908 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6911 Parameters parameters = new Parameters (new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location));
6912 set_block.Block = new ToplevelBlock (block, parameters, Location);
6913 Assign a = new Assign (new SimpleName(field.Name, Location), new SimpleName ("value", Location));
6914 set_block.Block.AddStatement (new StatementExpression(a));
6915 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6918 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6919 MemberName name, Attributes attrs, Accessor get_block,
6920 Accessor set_block, bool define_set_first)
6921 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6922 define_set_first, null)
6926 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6927 MemberName name, Attributes attrs, Accessor get_block,
6928 Accessor set_block, bool define_set_first, Block current_block)
6929 : base (parent, type, mod,
6930 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6931 is_iface, name, attrs, define_set_first)
6933 if (RootContext.Version >= LanguageVersion.LINQ &&
6935 (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6936 get_block != null && get_block.Block == null &&
6937 set_block != null && set_block.Block == null)
6938 CreateAutomaticProperty (current_block, get_block, set_block);
6940 if (get_block == null)
6941 Get = new GetMethod (this);
6943 Get = new GetMethod (this, get_block);
6945 if (set_block == null)
6946 Set = new SetMethod (this);
6948 Set = new SetMethod (this, set_block);
6951 public override bool Define ()
6953 if (!DoDefineBase ())
6956 if (!base.Define ())
6962 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6964 if (!DefineAccessors ())
6967 // FIXME - PropertyAttributes.HasDefault ?
6969 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6970 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6973 PropertyBuilder.SetGetMethod (GetBuilder);
6976 PropertyBuilder.SetSetMethod (SetBuilder);
6978 TypeManager.RegisterProperty (PropertyBuilder, this);
6982 protected override PropertyInfo ResolveBaseProperty ()
6984 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6985 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
6990 /// Gigantic workaround for lameness in SRE follows :
6991 /// This class derives from EventInfo and attempts to basically
6992 /// wrap around the EventBuilder so that FindMembers can quickly
6993 /// return this in it search for members
6995 public class MyEventBuilder : EventInfo {
6998 // We use this to "point" to our Builder which is
6999 // not really a MemberInfo
7001 EventBuilder MyBuilder;
7004 // We "catch" and wrap these methods
7006 MethodInfo raise, remove, add;
7008 EventAttributes attributes;
7009 Type declaring_type, reflected_type, event_type;
7014 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7016 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7018 // And now store the values in our own fields.
7020 declaring_type = type_builder;
7022 reflected_type = type_builder;
7024 attributes = event_attr;
7027 this.event_type = event_type;
7031 // Methods that you have to override. Note that you only need
7032 // to "implement" the variants that take the argument (those are
7033 // the "abstract" methods, the others (GetAddMethod()) are
7036 public override MethodInfo GetAddMethod (bool nonPublic)
7041 public override MethodInfo GetRemoveMethod (bool nonPublic)
7046 public override MethodInfo GetRaiseMethod (bool nonPublic)
7052 // These methods make "MyEventInfo" look like a Builder
7054 public void SetRaiseMethod (MethodBuilder raiseMethod)
7056 raise = raiseMethod;
7057 MyBuilder.SetRaiseMethod (raiseMethod);
7060 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7062 remove = removeMethod;
7063 MyBuilder.SetRemoveOnMethod (removeMethod);
7066 public void SetAddOnMethod (MethodBuilder addMethod)
7069 MyBuilder.SetAddOnMethod (addMethod);
7072 public void SetCustomAttribute (CustomAttributeBuilder cb)
7074 MyBuilder.SetCustomAttribute (cb);
7077 public override object [] GetCustomAttributes (bool inherit)
7079 // FIXME : There's nothing which can be seemingly done here because
7080 // we have no way of getting at the custom attribute objects of the
7085 public override object [] GetCustomAttributes (Type t, bool inherit)
7087 // FIXME : Same here !
7091 public override bool IsDefined (Type t, bool b)
7096 public override EventAttributes Attributes {
7102 public override string Name {
7108 public override Type DeclaringType {
7110 return declaring_type;
7114 public override Type ReflectedType {
7116 return reflected_type;
7120 public Type EventType {
7126 public void SetUsed ()
7128 if (my_event != null) {
7129 // my_event.SetAssigned ();
7130 my_event.SetMemberIsUsed ();
7136 /// For case when event is declared like property (with add and remove accessors).
7138 public class EventProperty: Event {
7139 abstract class AEventPropertyAccessor : AEventAccessor
7141 readonly ArrayList anonymous_methods;
7143 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7144 base (method, accessor, prefix)
7146 this.anonymous_methods = accessor.AnonymousMethods;
7149 public override MethodBuilder Define (DeclSpace ds)
7151 CheckAbstractAndExtern (block != null);
7152 return base.Define (ds);
7155 public override string GetSignatureForError ()
7157 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7160 public override bool ResolveMembers ()
7162 if (anonymous_methods == null)
7165 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7166 if (!ame.CreateAnonymousHelpers ())
7175 sealed class AddDelegateMethod: AEventPropertyAccessor
7177 public AddDelegateMethod (Event method, Accessor accessor):
7178 base (method, accessor, "add_")
7182 protected override MethodInfo DelegateMethodInfo {
7184 return TypeManager.delegate_combine_delegate_delegate;
7189 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7191 public RemoveDelegateMethod (Event method, Accessor accessor):
7192 base (method, accessor, "remove_")
7196 protected override MethodInfo DelegateMethodInfo {
7198 return TypeManager.delegate_remove_delegate_delegate;
7204 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7206 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
7207 bool is_iface, MemberName name,
7208 Attributes attrs, Accessor add, Accessor remove)
7209 : base (parent, type, mod_flags, is_iface, name, attrs)
7211 Add = new AddDelegateMethod (this, add);
7212 Remove = new RemoveDelegateMethod (this, remove);
7215 public override bool Define()
7217 if (!base.Define ())
7226 public override string[] ValidAttributeTargets {
7228 return attribute_targets;
7234 /// Event is declared like field.
7236 public class EventField : Event {
7237 abstract class EventFieldAccessor : AEventAccessor
7239 protected EventFieldAccessor (Event method, string prefix)
7240 : base (method, prefix)
7244 protected override void EmitMethod(DeclSpace parent)
7246 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7249 MethodBuilder mb = method_data.MethodBuilder;
7250 ILGenerator ig = mb.GetILGenerator ();
7252 // TODO: because we cannot use generics yet
7253 FieldInfo field_info = ((EventField)method).FieldBuilder;
7255 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7256 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7257 ig.Emit (OpCodes.Ldsfld, field_info);
7258 ig.Emit (OpCodes.Ldarg_0);
7259 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7260 ig.Emit (OpCodes.Castclass, method.MemberType);
7261 ig.Emit (OpCodes.Stsfld, field_info);
7263 ig.Emit (OpCodes.Ldarg_0);
7264 ig.Emit (OpCodes.Ldarg_0);
7265 ig.Emit (OpCodes.Ldfld, field_info);
7266 ig.Emit (OpCodes.Ldarg_1);
7267 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7268 ig.Emit (OpCodes.Castclass, method.MemberType);
7269 ig.Emit (OpCodes.Stfld, field_info);
7271 ig.Emit (OpCodes.Ret);
7275 sealed class AddDelegateMethod: EventFieldAccessor
7277 public AddDelegateMethod (Event method):
7278 base (method, "add_")
7282 protected override MethodInfo DelegateMethodInfo {
7284 return TypeManager.delegate_combine_delegate_delegate;
7289 sealed class RemoveDelegateMethod: EventFieldAccessor
7291 public RemoveDelegateMethod (Event method):
7292 base (method, "remove_")
7296 protected override MethodInfo DelegateMethodInfo {
7298 return TypeManager.delegate_remove_delegate_delegate;
7304 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7305 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7307 public FieldBuilder FieldBuilder;
7308 public Expression Initializer;
7310 public EventField (DeclSpace parent, Expression type, int mod_flags,
7311 bool is_iface, MemberName name,
7313 : base (parent, type, mod_flags, is_iface, name, attrs)
7315 Add = new AddDelegateMethod (this);
7316 Remove = new RemoveDelegateMethod (this);
7319 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7321 if (a.Target == AttributeTargets.Field) {
7322 FieldBuilder.SetCustomAttribute (cb);
7326 if (a.Target == AttributeTargets.Method) {
7327 int errors = Report.Errors;
7328 Add.ApplyAttributeBuilder (a, cb);
7329 if (errors == Report.Errors)
7330 Remove.ApplyAttributeBuilder (a, cb);
7334 base.ApplyAttributeBuilder (a, cb);
7337 public override bool Define()
7339 if (!base.Define ())
7345 // FIXME: We are unable to detect whether generic event is used because
7346 // we are using FieldExpr instead of EventExpr for event access in that
7347 // case. When this issue will be fixed this hack can be removed.
7348 if (TypeManager.IsGenericType (MemberType))
7351 FieldBuilder = Parent.TypeBuilder.DefineField (
7353 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7354 TypeManager.RegisterEventField (EventBuilder, this);
7356 if (Initializer != null) {
7357 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7358 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7359 GetSignatureForError ());
7363 Parent.PartialContainer.RegisterFieldForInitialization (this,
7364 new FieldInitializer (FieldBuilder, Initializer, Parent));
7370 public override string[] ValidAttributeTargets
7373 return IsInterface ? attribute_targets_interface : attribute_targets;
7378 public abstract class Event : PropertyBasedMember {
7379 public abstract class AEventAccessor : AbstractPropertyEventMethod
7381 protected readonly Event method;
7382 ImplicitParameter param_attr;
7384 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7386 protected AEventAccessor (Event method, string prefix)
7387 : base (method, prefix)
7389 this.method = method;
7390 this.ModFlags = method.ModFlags;
7393 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7394 : base (method, accessor, prefix)
7396 this.method = method;
7397 this.ModFlags = method.ModFlags;
7400 public override Iterator Iterator {
7401 get { return null; }
7404 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7406 if (a.IsInternalMethodImplAttribute) {
7407 method.is_external_implementation = true;
7410 base.ApplyAttributeBuilder (a, cb);
7413 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7415 if (a.Target == AttributeTargets.Parameter) {
7416 if (param_attr == null)
7417 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7419 param_attr.ApplyAttributeBuilder (a, cb);
7423 base.ApplyAttributeBuilder (a, cb);
7426 public override AttributeTargets AttributeTargets {
7428 return AttributeTargets.Method;
7432 public override bool IsClsComplianceRequired ()
7434 return method.IsClsComplianceRequired ();
7437 public virtual MethodBuilder Define (DeclSpace parent)
7439 method_data = new MethodData (method, method.ModFlags,
7440 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7442 if (!method_data.Define (parent))
7445 MethodBuilder mb = method_data.MethodBuilder;
7446 ParameterInfo.ApplyAttributes (mb);
7450 protected abstract MethodInfo DelegateMethodInfo { get; }
7452 public override Type ReturnType {
7454 return TypeManager.void_type;
7458 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7460 return new EmitContext (
7461 ds, method.Parent, Location, ig, ReturnType,
7462 method.ModFlags, false);
7465 public override ObsoleteAttribute GetObsoleteAttribute ()
7467 return method.GetObsoleteAttribute ();
7470 public override string[] ValidAttributeTargets {
7472 return attribute_targets;
7476 public override Parameters ParameterInfo {
7478 return method.parameters;
7484 const int AllowedModifiers =
7487 Modifiers.PROTECTED |
7488 Modifiers.INTERNAL |
7493 Modifiers.OVERRIDE |
7495 Modifiers.ABSTRACT |
7498 const int AllowedInterfaceModifiers =
7501 public AEventAccessor Add, Remove;
7502 public MyEventBuilder EventBuilder;
7503 public MethodBuilder AddBuilder, RemoveBuilder;
7505 Parameters parameters;
7507 protected Event (DeclSpace parent, Expression type, int mod_flags,
7508 bool is_iface, MemberName name, Attributes attrs)
7509 : base (parent, null, type, mod_flags,
7510 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7515 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7517 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7518 a.Error_InvalidSecurityParent ();
7522 EventBuilder.SetCustomAttribute (cb);
7525 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7527 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7530 public override AttributeTargets AttributeTargets {
7532 return AttributeTargets.Event;
7536 public override bool Define ()
7538 if (!DoDefineBase ())
7544 if (!TypeManager.IsDelegateType (MemberType)) {
7545 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7549 parameters = Parameters.CreateFullyResolved (
7550 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7556 // Now define the accessors
7559 AddBuilder = Add.Define (Parent);
7560 if (AddBuilder == null)
7563 RemoveBuilder = Remove.Define (Parent);
7564 if (RemoveBuilder == null)
7567 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7568 EventBuilder.SetAddOnMethod (AddBuilder);
7569 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7573 public override void Emit ()
7575 if (OptAttributes != null) {
7576 OptAttributes.Emit ();
7580 Remove.Emit (Parent);
7585 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7587 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7588 Parent.TypeBuilder, Name);
7593 ParameterData pd = TypeManager.GetParameterData (mi);
7594 base_ret_type = pd.ParameterType (0);
7599 // Represents header string for documentation comment.
7601 public override string DocCommentHeader {
7602 get { return "E:"; }
7607 public class Indexer : PropertyBase {
7609 class GetIndexerMethod : GetMethod
7611 public GetIndexerMethod (PropertyBase method):
7616 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7617 base (method, accessor)
7621 public override Parameters ParameterInfo {
7623 return ((Indexer)method).parameters;
7628 class SetIndexerMethod: SetMethod
7630 public SetIndexerMethod (PropertyBase method):
7635 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7636 base (method, accessor)
7640 protected override void DefineParameters ()
7642 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7643 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7647 const int AllowedModifiers =
7650 Modifiers.PROTECTED |
7651 Modifiers.INTERNAL |
7655 Modifiers.OVERRIDE |
7660 const int AllowedInterfaceModifiers =
7663 public readonly Parameters parameters;
7665 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7666 bool is_iface, Parameters parameters, Attributes attrs,
7667 Accessor get_block, Accessor set_block, bool define_set_first)
7668 : base (parent, type, mod,
7669 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7670 is_iface, name, attrs, define_set_first)
7672 if (type == TypeManager.system_void_expr)
7673 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7675 this.parameters = parameters;
7677 if (get_block == null)
7678 Get = new GetIndexerMethod (this);
7680 Get = new GetIndexerMethod (this, get_block);
7682 if (set_block == null)
7683 Set = new SetIndexerMethod (this);
7685 Set = new SetIndexerMethod (this, set_block);
7688 protected override bool CheckForDuplications ()
7690 ArrayList ar = Parent.PartialContainer.Indexers;
7692 int arLen = ar.Count;
7694 for (int i = 0; i < arLen; i++) {
7695 Indexer m = (Indexer) ar [i];
7696 if (IsDuplicateImplementation (m))
7704 bool IsDuplicateImplementation (Indexer indexer)
7706 if (this == indexer)
7709 if (!MemberName.Equals (indexer.MemberName))
7712 Type[] param_types = indexer.parameters.Types;
7714 // When it is not yet defined
7715 if (param_types == null)
7718 if (param_types.Length != parameters.Count)
7721 for (int i = 0; i < param_types.Length; i++)
7722 if (param_types [i] != parameters.Types [i])
7725 Report.SymbolRelatedToPreviousError (indexer);
7726 Report.Error (111, Location, TypeContainer.Error111, indexer.GetSignatureForError ());
7731 public override bool Define ()
7733 if (!DoDefineBase ())
7736 if (!base.Define ())
7739 if (!DefineParameters (parameters))
7742 if (OptAttributes != null) {
7743 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7744 if (indexer_attr != null) {
7745 // Remove the attribute from the list because it is not emitted
7746 OptAttributes.Attrs.Remove (indexer_attr);
7748 string name = indexer_attr.GetIndexerAttributeValue ();
7754 if (IsExplicitImpl) {
7755 Report.Error (415, indexer_attr.Location,
7756 "The `IndexerName' attribute is valid only on an " +
7757 "indexer that is not an explicit interface member declaration");
7761 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7762 Report.Error (609, indexer_attr.Location,
7763 "Cannot set the `IndexerName' attribute on an indexer marked override");
7769 if (InterfaceType != null) {
7770 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7771 if (base_IndexerName != Name)
7772 ShortName = base_IndexerName;
7775 if (!Parent.PartialContainer.AddMember (this) ||
7776 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7782 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7784 if (!DefineAccessors ())
7788 // Setup iterator if we are one
7789 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7790 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7791 if (iterator == null)
7797 // Now name the parameters
7799 Parameter [] p = parameters.FixedParameters;
7801 // TODO: should be done in parser and it needs to do cycle
7802 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7803 CSharpParser.Error_ParameterModifierNotValid (Location);
7808 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7809 Name, PropertyAttributes.None, MemberType, parameters.Types);
7812 PropertyBuilder.SetGetMethod (GetBuilder);
7815 PropertyBuilder.SetSetMethod (SetBuilder);
7817 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7822 public override string GetDocCommentName (DeclSpace ds)
7824 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7827 public override string GetSignatureForError ()
7829 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7830 if (MemberName.Left != null) {
7832 sb.Append (MemberName.Left);
7835 sb.Append (".this");
7836 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7837 return sb.ToString ();
7840 public override bool MarkForDuplicationCheck ()
7842 caching_flags |= Flags.TestMethodDuplication;
7846 protected override PropertyInfo ResolveBaseProperty ()
7848 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7849 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7852 protected override bool VerifyClsCompliance ()
7854 if (!base.VerifyClsCompliance ())
7857 parameters.VerifyClsCompliance ();
7862 public class Operator : MethodOrOperator, IAnonymousHost {
7864 const int AllowedModifiers =
7870 public enum OpType : byte {
7880 // Unary and Binary operators
7903 // Implicit and Explicit
7907 // Just because of enum
7911 public readonly OpType OperatorType;
7913 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7914 int mod_flags, Parameters parameters,
7915 ToplevelBlock block, Attributes attrs, Location loc)
7916 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7917 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7919 OperatorType = type;
7923 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7925 if (a.Type == TypeManager.conditional_attribute_type) {
7926 Error_ConditionalAttributeIsNotValid ();
7930 base.ApplyAttributeBuilder (a, cb);
7933 protected override bool CheckForDuplications ()
7935 ArrayList ar = Parent.PartialContainer.Operators;
7937 int arLen = ar.Count;
7939 for (int i = 0; i < arLen; i++) {
7940 Operator o = (Operator) ar [i];
7941 if (IsDuplicateImplementation (o))
7946 ar = Parent.PartialContainer.Methods;
7948 int arLen = ar.Count;
7950 for (int i = 0; i < arLen; i++) {
7951 Method m = (Method) ar [i];
7952 if (IsDuplicateImplementation (m))
7960 public override bool Define ()
7962 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7963 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7964 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7968 // imlicit and explicit operator of same types are not allowed
7969 if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
7970 MarkForDuplicationCheck ();
7972 if (!base.Define ())
7975 if (MemberType == TypeManager.void_type) {
7976 Report.Error (590, Location, "User-defined operators cannot return void");
7980 Type declaring_type = MethodData.DeclaringType;
7981 Type return_type = MemberType;
7982 Type first_arg_type = ParameterTypes [0];
7984 // Rules for conversion operators
7986 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7987 if (first_arg_type == return_type && first_arg_type == declaring_type){
7988 Report.Error (555, Location,
7989 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7993 if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
7994 !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
7995 !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
7998 "User-defined conversion must convert to or from the " +
8003 if (first_arg_type.IsInterface || return_type.IsInterface){
8004 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8005 GetSignatureForError ());
8009 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
8010 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
8011 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
8012 GetSignatureForError ());
8015 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
8016 GetSignatureForError ());
8019 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8020 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8021 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");
8024 } else if (Parameters.Count == 1) {
8025 // Checks for Unary operators
8027 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8028 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8029 Report.Error (448, Location,
8030 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8033 if (first_arg_type != declaring_type) {
8035 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8040 if (first_arg_type != declaring_type){
8043 "The parameter of a unary operator must be the " +
8048 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8049 if (return_type != TypeManager.bool_type){
8052 "The return type of operator True or False " +
8059 // Checks for Binary operators
8061 if (first_arg_type != declaring_type &&
8062 ParameterTypes [1] != declaring_type){
8065 "One of the parameters of a binary operator must " +
8066 "be the containing type");
8074 protected override bool DoDefine ()
8076 if (!base.DoDefine ())
8079 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8083 public override void Emit ()
8087 Parameters.ApplyAttributes (MethodBuilder);
8090 // abstract or extern methods have no bodies
8092 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8096 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8097 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8099 ec = CreateEmitContext (Parent, null);
8101 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8102 ec.EmitTopBlock (this, Block);
8105 source.CloseMethod ();
8110 // Operator cannot be override
8111 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8116 public static string GetName (OpType ot)
8119 case OpType.LogicalNot:
8121 case OpType.OnesComplement:
8123 case OpType.Increment:
8125 case OpType.Decrement:
8131 case OpType.Addition:
8133 case OpType.Subtraction:
8135 case OpType.UnaryPlus:
8137 case OpType.UnaryNegation:
8139 case OpType.Multiply:
8141 case OpType.Division:
8143 case OpType.Modulus:
8145 case OpType.BitwiseAnd:
8147 case OpType.BitwiseOr:
8149 case OpType.ExclusiveOr:
8151 case OpType.LeftShift:
8153 case OpType.RightShift:
8155 case OpType.Equality:
8157 case OpType.Inequality:
8159 case OpType.GreaterThan:
8161 case OpType.LessThan:
8163 case OpType.GreaterThanOrEqual:
8165 case OpType.LessThanOrEqual:
8167 case OpType.Implicit:
8169 case OpType.Explicit:
8175 public static OpType GetOperatorType (string name)
8177 if (name.StartsWith ("op_")){
8178 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8179 if (Unary.oper_names [i] == name)
8183 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8184 if (Binary.oper_names [i] == name)
8191 public override string GetSignatureForError ()
8193 StringBuilder sb = new StringBuilder ();
8194 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8195 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8198 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8201 sb.Append (Parameters.GetSignatureForError ());
8202 return sb.ToString ();
8207 // This is used to compare method signatures
8209 struct MethodSignature {
8211 public Type RetType;
8212 public Type [] Parameters;
8215 /// This delegate is used to extract methods which have the
8216 /// same signature as the argument
8218 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8220 public MethodSignature (string name, Type ret_type, Type [] parameters)
8225 if (parameters == null)
8226 Parameters = Type.EmptyTypes;
8228 Parameters = parameters;
8231 public override string ToString ()
8234 if (Parameters.Length != 0){
8235 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8236 for (int i = 0; i < Parameters.Length; i++){
8237 sb.Append (Parameters [i]);
8238 if (i+1 < Parameters.Length)
8241 pars = sb.ToString ();
8244 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8247 public override int GetHashCode ()
8249 return Name.GetHashCode ();
8252 public override bool Equals (Object o)
8254 MethodSignature other = (MethodSignature) o;
8256 if (other.Name != Name)
8259 if (other.RetType != RetType)
8262 if (Parameters == null){
8263 if (other.Parameters == null)
8268 if (other.Parameters == null)
8271 int c = Parameters.Length;
8272 if (other.Parameters.Length != c)
8275 for (int i = 0; i < c; i++)
8276 if (other.Parameters [i] != Parameters [i])
8282 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8284 MethodSignature sig = (MethodSignature) filter_criteria;
8286 if (m.Name != sig.Name)
8290 MethodInfo mi = m as MethodInfo;
8291 PropertyInfo pi = m as PropertyInfo;
8294 ReturnType = mi.ReturnType;
8295 else if (pi != null)
8296 ReturnType = pi.PropertyType;
8301 // we use sig.RetType == null to mean `do not check the
8302 // method return value.
8304 if (sig.RetType != null)
8305 if (ReturnType != sig.RetType)
8310 args = TypeManager.GetParameterData (mi).Types;
8312 args = TypeManager.GetArgumentTypes (pi);
8313 Type [] sigp = sig.Parameters;
8315 if (args.Length != sigp.Length)
8318 for (int i = args.Length; i > 0; ){
8320 if (args [i] != sigp [i])