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 bool 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 ());
610 public void AddProperty (Property prop)
612 if (!AddMember (prop) ||
613 !AddMember (prop.Get) || !AddMember (prop.Set))
616 if (properties == null)
617 properties = new MemberCoreArrayList ();
619 if (prop.MemberName.Left != null)
620 AddMemberToList (prop, properties, true);
622 AddMemberToList (prop, properties, false);
625 public void AddEvent (Event e)
630 if (e is EventProperty) {
631 if (!AddMember (e.Add))
634 if (!AddMember (e.Remove))
639 events = new MemberCoreArrayList ();
645 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
647 public void AddIndexer (Indexer i)
649 if (indexers == null)
650 indexers = new ArrayList ();
652 if (i.IsExplicitImpl)
653 AddMemberToList (i, indexers, true);
655 AddMemberToList (i, indexers, false);
658 public void AddOperator (Operator op)
663 if (operators == null)
664 operators = new OperatorArrayList (this);
669 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
671 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
673 if (compiler_generated == null)
674 compiler_generated = new ArrayList ();
676 compiler_generated.Add (c);
679 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
681 if (a.Type == TypeManager.default_member_type) {
682 if (Indexers != null) {
683 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
688 base.ApplyAttributeBuilder (a, cb);
691 public override AttributeTargets AttributeTargets {
693 throw new NotSupportedException ();
697 public ArrayList Types {
703 public MemberCoreArrayList Methods {
709 public ArrayList Constants {
715 public ArrayList CompilerGenerated {
717 return compiler_generated;
721 protected Type BaseType {
723 return TypeBuilder.BaseType;
727 public ArrayList Bases {
737 public ArrayList Fields {
743 public ArrayList InstanceConstructors {
745 return instance_constructors;
749 public ArrayList Properties {
755 public ArrayList Events {
761 public ArrayList Indexers {
767 public ArrayList Operators {
773 public ArrayList Delegates {
779 protected override TypeAttributes TypeAttr {
781 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
785 public string IndexerName {
787 return indexers == null ? DefaultIndexerName : indexer_name;
791 public bool IsComImport {
793 if (OptAttributes == null)
796 return OptAttributes.Contains (TypeManager.comimport_attr_type);
800 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
802 if ((field.ModFlags & Modifiers.STATIC) != 0){
803 if (initialized_static_fields == null)
804 initialized_static_fields = new ArrayList (4);
806 initialized_static_fields.Add (expression);
808 if (initialized_fields == null)
809 initialized_fields = new ArrayList (4);
811 initialized_fields.Add (expression);
816 // Emits the instance field initializers
818 public bool EmitFieldInitializers (EmitContext ec)
823 fields = initialized_static_fields;
825 fields = initialized_fields;
831 foreach (FieldInitializer f in fields) {
832 f.EmitStatement (ec);
837 public override string DocComment {
849 public PendingImplementation PendingImplementations {
850 get { return pending; }
853 public override bool GetClsCompliantAttributeValue ()
855 if (PartialContainer != this)
856 return PartialContainer.GetClsCompliantAttributeValue ();
858 return base.GetClsCompliantAttributeValue ();
861 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
863 // FIXME: get rid of partial_parts and store lists of bases of each part here
864 // assumed, not verified: 'part' is in 'partial_parts'
865 ((TypeContainer) part).Bases = bases;
868 TypeExpr[] GetNormalBases (out TypeExpr base_class)
874 int count = Bases.Count;
877 if (Kind == Kind.Class){
878 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
884 if (!name.IsInterface) {
885 // base_class could be a class, struct, enum, delegate.
886 // This is validated in GetClassBases.
892 TypeExpr [] ifaces = new TypeExpr [count-start];
894 for (i = start, j = 0; i < count; i++, j++){
895 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
896 if (resolved == null) {
900 ifaces [j] = resolved;
903 return ifaces.Length == 0 ? null : ifaces;
907 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
909 ArrayList ifaces = new ArrayList (0);
910 if (iface_exprs != null)
911 ifaces.AddRange (iface_exprs);
913 foreach (TypeContainer part in partial_parts) {
914 TypeExpr new_base_class;
915 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
916 if (new_base_class != TypeManager.system_object_expr) {
917 if (base_class == TypeManager.system_object_expr)
918 base_class = new_base_class;
920 if (new_base_class != null && !new_base_class.Equals (base_class)) {
921 Report.SymbolRelatedToPreviousError (base_class.Location, "");
922 Report.Error (263, part.Location,
923 "Partial declarations of `{0}' must not specify different base classes",
924 part.GetSignatureForError ());
931 if (new_ifaces == null)
934 foreach (TypeExpr iface in new_ifaces) {
935 if (ifaces.Contains (iface))
942 if (ifaces.Count == 0)
945 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
949 /// This function computes the Base class and also the
950 /// list of interfaces that the class or struct @c implements.
952 /// The return value is an array (might be null) of
953 /// interfaces implemented (as Types).
955 /// The @base_class argument is set to the base object or null
956 /// if this is `System.Object'.
958 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
960 TypeExpr[] ifaces = GetNormalBases (out base_class);
965 int count = ifaces.Length;
967 for (int i = 0; i < count; i++) {
968 TypeExpr iface = (TypeExpr) ifaces [i];
970 if (!iface.IsInterface) {
971 if (Kind != Kind.Class) {
972 // TODO: location of symbol related ....
973 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
975 else if (base_class != null)
976 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
977 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
979 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
980 GetSignatureForError (), iface.GetSignatureForError ());
985 for (int x = 0; x < i; x++) {
986 if (iface.Equals (ifaces [x])) {
987 Report.Error (528, Location,
988 "`{0}' is already listed in " +
989 "interface list", iface.GetSignatureForError ());
994 if ((Kind == Kind.Interface) &&
995 !iface.AsAccessible (Parent, ModFlags)) {
996 Report.Error (61, Location,
997 "Inconsistent accessibility: base " +
998 "interface `{0}' is less accessible " +
999 "than interface `{1}'", iface.Name,
1007 bool CheckGenericInterfaces (Type[] ifaces)
1010 ArrayList already_checked = new ArrayList ();
1012 for (int i = 0; i < ifaces.Length; i++) {
1013 Type iface = ifaces [i];
1014 foreach (Type t in already_checked) {
1018 Type[] inferred = new Type [CountTypeParameters];
1019 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
1022 Report.Error (695, Location,
1023 "`{0}' cannot implement both `{1}' and `{2}' " +
1024 "because they may unify for some type parameter substitutions",
1025 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1026 TypeManager.CSharpName (t));
1030 already_checked.Add (iface);
1039 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1041 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1044 bool CreateTypeBuilder ()
1047 Type default_parent = null;
1048 if (Kind == Kind.Struct)
1049 default_parent = TypeManager.value_type;
1050 else if (Kind == Kind.Enum)
1051 default_parent = TypeManager.enum_type;
1054 if (TypeManager.NamespaceClash (Name, Location)) {
1058 ModuleBuilder builder = CodeGen.Module.Builder;
1059 TypeBuilder = builder.DefineType (
1060 Name, TypeAttr, default_parent, null);
1062 TypeBuilder builder = Parent.TypeBuilder;
1064 TypeBuilder = builder.DefineNestedType (
1065 Basename, TypeAttr, default_parent, null);
1067 } catch (ArgumentException) {
1068 Report.RuntimeMissingSupport (Location, "static classes");
1072 TypeManager.AddUserType (this);
1076 string[] param_names = new string [TypeParameters.Length];
1077 for (int i = 0; i < TypeParameters.Length; i++)
1078 param_names [i] = TypeParameters [i].Name;
1080 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1082 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1083 for (int i = offset; i < gen_params.Length; i++)
1084 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1091 bool DefineBaseTypes ()
1093 iface_exprs = GetClassBases (out base_type);
1094 if (partial_parts != null) {
1095 iface_exprs = GetNormalPartialBases (ref base_type);
1099 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1100 // which in turn should have called DefineType()s on base types if necessary.
1102 // None of the code below should trigger DefineType()s on classes that we depend on.
1103 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1105 // Let's do it as soon as possible, since code below can call DefineType() on classes
1106 // that depend on us to be populated before they are.
1108 if (!(this is CompilerGeneratedClass))
1109 RootContext.RegisterOrder (this);
1111 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1112 Report.Error (698, base_type.Location,
1113 "A generic type cannot derive from `{0}' because it is an attribute class",
1118 if (!CheckRecursiveDefinition (this))
1121 if (base_type != null && base_type.Type != null) {
1122 TypeBuilder.SetParent (base_type.Type);
1124 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1125 if (obsolete_attr != null && !IsInObsoleteScope)
1126 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1129 // add interfaces that were not added at type creation
1130 if (iface_exprs != null) {
1131 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1135 foreach (Type itype in ifaces)
1136 TypeBuilder.AddInterfaceImplementation (itype);
1138 foreach (TypeExpr ie in iface_exprs) {
1139 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1140 if ((oa != null) && !IsInObsoleteScope)
1141 AttributeTester.Report_ObsoleteMessage (
1142 oa, ie.GetSignatureForError (), Location);
1145 if (!CheckGenericInterfaces (ifaces))
1148 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1155 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1157 public TypeBuilder CreateType ()
1159 if (TypeBuilder != null)
1165 if (!CreateTypeBuilder ()) {
1170 if (partial_parts != null) {
1171 foreach (TypeContainer part in partial_parts)
1172 part.TypeBuilder = TypeBuilder;
1175 if (Types != null) {
1176 foreach (TypeContainer tc in Types) {
1177 if (tc.CreateType () == null) {
1189 public override TypeBuilder DefineType ()
1196 type_defined = true;
1198 if (CreateType () == null) {
1203 if (!DefineBaseTypes ()) {
1208 if (!(this is CompilerGeneratedClass)) {
1209 if (!ResolveMembers ()) {
1215 if (!DefineNestedTypes ()) {
1223 public bool ResolveMembers ()
1225 if (members_resolved)
1226 return members_resolved_ok;
1228 members_resolved_ok = DoResolveMembers ();
1229 members_resolved = true;
1231 return members_resolved_ok;
1234 protected virtual bool DoResolveMembers ()
1236 if (methods != null) {
1237 foreach (Method method in methods) {
1238 if (!method.ResolveMembers ())
1243 if (instance_constructors != null) {
1244 foreach (Constructor c in instance_constructors) {
1245 if (!c.ResolveMembers ())
1250 if (default_static_constructor != null) {
1251 if (!default_static_constructor.ResolveMembers ())
1255 if (operators != null) {
1256 foreach (Operator o in operators) {
1257 if (!o.ResolveMembers ())
1262 if (properties != null) {
1263 foreach (PropertyBase p in properties) {
1264 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1266 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1271 if (indexers != null) {
1272 foreach (PropertyBase p in indexers) {
1273 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1275 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1280 if (events != null) {
1281 foreach (Event e in events) {
1282 if (!e.Add.ResolveMembers ())
1284 if (!e.Remove.ResolveMembers ())
1289 if (compiler_generated != null) {
1290 foreach (CompilerGeneratedClass c in compiler_generated) {
1291 if (c.DefineType () == null)
1299 Constraints [] constraints;
1300 public override void SetParameterInfo (ArrayList constraints_list)
1302 if (PartialContainer == this) {
1303 base.SetParameterInfo (constraints_list);
1307 if (constraints_list == null)
1310 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1312 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1313 for (int i = 0; i < constraints.Length; i++) {
1314 foreach (Constraints constraint in constraints_list) {
1315 if (constraint.TypeParameter == current_params [i].Name) {
1316 constraints [i] = constraint;
1323 bool UpdateTypeParameterConstraints ()
1325 if (constraints == null)
1328 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1329 for (int i = 0; i < current_params.Length; i++) {
1330 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1331 Report.SymbolRelatedToPreviousError (Location, "");
1332 Report.Error (265, PartialContainer.Location,
1333 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1334 PartialContainer.GetSignatureForError (), current_params [i].Name);
1342 public bool ResolveType ()
1344 if (!DoResolveType ())
1347 if (compiler_generated != null) {
1348 foreach (CompilerGeneratedClass c in compiler_generated)
1349 if (!c.ResolveType ())
1356 protected virtual bool DoResolveType ()
1358 if ((base_type != null) &&
1359 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1367 if (PartialContainer != this)
1368 throw new InternalErrorException ();
1370 TypeExpr current_type = null;
1372 foreach (TypeParameter type_param in CurrentTypeParameters) {
1373 if (!type_param.Resolve (this)) {
1379 if (partial_parts != null) {
1380 foreach (TypeContainer part in partial_parts) {
1381 if (!part.UpdateTypeParameterConstraints ()) {
1388 foreach (TypeParameter type_param in TypeParameters) {
1389 if (!type_param.DefineType (this)) {
1395 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1397 foreach (TypeParameter type_param in TypeParameters)
1398 if (!type_param.CheckDependencies ()) {
1403 if (current_type != null) {
1404 current_type = current_type.ResolveAsTypeTerminal (this, false);
1405 if (current_type == null) {
1410 CurrentType = current_type.Type;
1416 protected virtual bool DefineNestedTypes ()
1418 if (Types != null) {
1419 foreach (TypeContainer tc in Types)
1420 if (tc.DefineType () == null)
1424 if (Delegates != null) {
1425 foreach (Delegate d in Delegates)
1426 if (d.DefineType () == null)
1433 TypeContainer InTransit;
1435 protected bool CheckRecursiveDefinition (TypeContainer tc)
1437 if (InTransit != null) {
1438 Report.SymbolRelatedToPreviousError (this);
1439 if (this is Interface)
1441 529, tc.Location, "Inherited interface `{0}' causes a " +
1442 "cycle in the interface hierarchy of `{1}'",
1443 GetSignatureForError (), tc.GetSignatureForError ());
1446 146, tc.Location, "Circular base class dependency " +
1447 "involving `{0}' and `{1}'",
1448 tc.GetSignatureForError (), GetSignatureForError ());
1454 if (base_type != null && base_type.Type != null) {
1455 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1456 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1457 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1461 if (iface_exprs != null) {
1462 foreach (TypeExpr iface in iface_exprs) {
1463 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1464 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1465 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1470 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1477 public static void Error_KeywordNotAllowed (Location loc)
1479 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1483 /// Populates our TypeBuilder with fields and methods
1485 public override bool DefineMembers ()
1487 if (members_defined)
1488 return members_defined_ok;
1490 if (!base.DefineMembers ())
1493 members_defined_ok = DoDefineMembers ();
1494 members_defined = true;
1496 return members_defined_ok;
1499 protected virtual bool DoDefineMembers ()
1501 if (iface_exprs != null) {
1502 foreach (TypeExpr iface in iface_exprs) {
1503 ConstructedType ct = iface as ConstructedType;
1504 if ((ct != null) && !ct.CheckConstraints (this))
1509 if (base_type != null) {
1510 ConstructedType ct = base_type as ConstructedType;
1511 if ((ct != null) && !ct.CheckConstraints (this))
1516 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1517 if (conflict_symbol == null) {
1518 if ((ModFlags & Modifiers.NEW) != 0)
1519 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1521 if ((ModFlags & Modifiers.NEW) == 0) {
1522 Report.SymbolRelatedToPreviousError (conflict_symbol);
1523 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1524 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1529 DefineContainerMembers (constants);
1530 DefineContainerMembers (fields);
1532 if (Kind == Kind.Struct || Kind == Kind.Class) {
1533 pending = PendingImplementation.GetPendingImplementations (this);
1537 // Constructors are not in the defined_names array
1539 DefineContainerMembers (instance_constructors);
1541 DefineContainerMembers (events);
1542 DefineContainerMembers (ordered_explicit_member_list);
1543 DefineContainerMembers (ordered_member_list);
1545 DefineContainerMembers (operators);
1546 DefineContainerMembers (delegates);
1548 ComputeIndexerName();
1549 CheckEqualsAndGetHashCode();
1551 if (CurrentType != null) {
1552 GenericType = CurrentType;
1556 member_cache = new MemberCache (this);
1557 if (partial_parts != null) {
1558 foreach (TypeContainer part in partial_parts)
1559 part.member_cache = member_cache;
1566 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1569 mcal.DefineContainerMembers ();
1572 protected virtual void ComputeIndexerName ()
1574 if (indexers == null)
1577 string class_indexer_name = null;
1580 // If there's both an explicit and an implicit interface implementation, the
1581 // explicit one actually implements the interface while the other one is just
1582 // a normal indexer. See bug #37714.
1585 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1586 foreach (Indexer i in indexers) {
1587 if (i.InterfaceType != null) {
1588 if (seen_normal_indexers)
1589 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1593 seen_normal_indexers = true;
1595 if (class_indexer_name == null) {
1596 class_indexer_name = i.ShortName;
1600 if (i.ShortName != class_indexer_name)
1601 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");
1604 if (class_indexer_name != null)
1605 indexer_name = class_indexer_name;
1608 protected virtual void EmitIndexerName ()
1610 if (!seen_normal_indexers)
1613 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1614 TypeBuilder.SetCustomAttribute (cb);
1617 protected virtual void CheckEqualsAndGetHashCode ()
1619 if (methods == null)
1622 if (HasEquals && !HasGetHashCode) {
1623 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1627 public override bool Define ()
1629 if (compiler_generated != null) {
1630 foreach (CompilerGeneratedClass c in compiler_generated) {
1639 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1641 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1645 /// This function is based by a delegate to the FindMembers routine
1647 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1653 /// This filter is used by FindMembers, and we just keep
1654 /// a global for the filter to `AlwaysAccept'
1656 static MemberFilter accepting_filter;
1659 static TypeContainer ()
1661 accepting_filter = new MemberFilter (AlwaysAccept);
1664 public MethodInfo[] GetMethods ()
1666 ArrayList members = new ArrayList ();
1670 if (methods != null) {
1671 int len = methods.Count;
1672 for (int i = 0; i < len; i++) {
1673 Method m = (Method) methods [i];
1675 members.Add (m.MethodBuilder);
1679 if (operators != null) {
1680 int len = operators.Count;
1681 for (int i = 0; i < len; i++) {
1682 Operator o = (Operator) operators [i];
1684 members.Add (o.MethodBuilder);
1688 if (properties != null) {
1689 int len = properties.Count;
1690 for (int i = 0; i < len; i++) {
1691 Property p = (Property) properties [i];
1693 if (p.GetBuilder != null)
1694 members.Add (p.GetBuilder);
1695 if (p.SetBuilder != null)
1696 members.Add (p.SetBuilder);
1700 if (indexers != null) {
1701 int len = indexers.Count;
1702 for (int i = 0; i < len; i++) {
1703 Indexer ix = (Indexer) indexers [i];
1705 if (ix.GetBuilder != null)
1706 members.Add (ix.GetBuilder);
1707 if (ix.SetBuilder != null)
1708 members.Add (ix.SetBuilder);
1712 if (events != null) {
1713 int len = events.Count;
1714 for (int i = 0; i < len; i++) {
1715 Event e = (Event) events [i];
1717 if (e.AddBuilder != null)
1718 members.Add (e.AddBuilder);
1719 if (e.RemoveBuilder != null)
1720 members.Add (e.RemoveBuilder);
1724 MethodInfo[] retMethods = new MethodInfo [members.Count];
1725 members.CopyTo (retMethods, 0);
1729 // Indicated whether container has StructLayout attribute set Explicit
1730 public bool HasExplicitLayout {
1731 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1732 set { caching_flags |= Flags.HasExplicitLayout; }
1736 // Return the nested type with name @name. Ensures that the nested type
1737 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1739 public Type FindNestedType (string name)
1741 if (PartialContainer != this)
1742 throw new InternalErrorException ("should not happen");
1744 ArrayList [] lists = { types, delegates };
1746 for (int j = 0; j < lists.Length; ++j) {
1747 ArrayList list = lists [j];
1751 int len = list.Count;
1752 for (int i = 0; i < len; ++i) {
1753 DeclSpace ds = (DeclSpace) list [i];
1754 if (ds.Basename == name) {
1755 return ds.DefineType ();
1763 private void FindMembers_NestedTypes (int modflags,
1764 BindingFlags bf, MemberFilter filter, object criteria,
1765 ref ArrayList members)
1767 ArrayList [] lists = { types, delegates };
1769 for (int j = 0; j < lists.Length; ++j) {
1770 ArrayList list = lists [j];
1774 int len = list.Count;
1775 for (int i = 0; i < len; i++) {
1776 DeclSpace ds = (DeclSpace) list [i];
1778 if ((ds.ModFlags & modflags) == 0)
1781 TypeBuilder tb = ds.TypeBuilder;
1783 if (!(criteria is string) || ds.Basename.Equals (criteria))
1784 tb = ds.DefineType ();
1787 if (tb != null && (filter (tb, criteria) == true)) {
1788 if (members == null)
1789 members = new ArrayList ();
1798 /// This method returns the members of this type just like Type.FindMembers would
1799 /// Only, we need to use this for types which are _being_ defined because MS'
1800 /// implementation can't take care of that.
1803 // FIXME: return an empty static array instead of null, that cleans up
1804 // some code and is consistent with some coding conventions I just found
1808 // Notice that in various cases we check if our field is non-null,
1809 // something that would normally mean that there was a bug elsewhere.
1811 // The problem happens while we are defining p-invoke methods, as those
1812 // will trigger a FindMembers, but this happens before things are defined
1814 // Since the whole process is a no-op, it is fine to check for null here.
1816 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1817 MemberFilter filter, object criteria)
1819 ArrayList members = null;
1822 if ((bf & BindingFlags.Public) != 0)
1823 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1825 if ((bf & BindingFlags.NonPublic) != 0)
1826 modflags |= Modifiers.PRIVATE;
1828 int static_mask = 0, static_flags = 0;
1829 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1830 case BindingFlags.Static:
1831 static_mask = static_flags = Modifiers.STATIC;
1834 case BindingFlags.Instance:
1835 static_mask = Modifiers.STATIC;
1840 static_mask = static_flags = 0;
1844 Timer.StartTimer (TimerType.TcFindMembers);
1847 filter = accepting_filter;
1849 if ((mt & MemberTypes.Field) != 0) {
1850 if (fields != null) {
1851 int len = fields.Count;
1852 for (int i = 0; i < len; i++) {
1853 FieldBase f = (FieldBase) fields [i];
1855 if ((f.ModFlags & modflags) == 0)
1857 if ((f.ModFlags & static_mask) != static_flags)
1860 FieldBuilder fb = f.FieldBuilder;
1861 if (fb != null && filter (fb, criteria) == true) {
1862 if (members == null)
1863 members = new ArrayList ();
1870 if (constants != null) {
1871 int len = constants.Count;
1872 for (int i = 0; i < len; i++) {
1873 Const con = (Const) constants [i];
1875 if ((con.ModFlags & modflags) == 0)
1877 if ((con.ModFlags & static_mask) != static_flags)
1880 FieldBuilder fb = con.FieldBuilder;
1883 fb = con.FieldBuilder;
1885 if (fb != null && filter (fb, criteria) == true) {
1886 if (members == null)
1887 members = new ArrayList ();
1895 if ((mt & MemberTypes.Method) != 0) {
1896 if (methods != null) {
1897 int len = methods.Count;
1898 for (int i = 0; i < len; i++) {
1899 Method m = (Method) methods [i];
1901 if ((m.ModFlags & modflags) == 0)
1903 if ((m.ModFlags & static_mask) != static_flags)
1906 MethodBuilder mb = m.MethodBuilder;
1908 if (mb != null && filter (mb, criteria) == true) {
1909 if (members == null)
1910 members = new ArrayList ();
1917 if (operators != null) {
1918 int len = operators.Count;
1919 for (int i = 0; i < len; i++) {
1920 Operator o = (Operator) operators [i];
1922 if ((o.ModFlags & modflags) == 0)
1924 if ((o.ModFlags & static_mask) != static_flags)
1927 MethodBuilder ob = o.MethodBuilder;
1928 if (ob != null && filter (ob, criteria) == true) {
1929 if (members == null)
1930 members = new ArrayList ();
1937 if (events != null) {
1938 foreach (Event e in events) {
1939 if ((e.ModFlags & modflags) == 0)
1941 if ((e.ModFlags & static_mask) != static_flags)
1944 MethodBuilder b = e.AddBuilder;
1945 if (b != null && filter (b, criteria)) {
1946 if (members == null)
1947 members = new ArrayList (4);
1952 b = e.RemoveBuilder;
1953 if (b != null && filter (b, criteria)) {
1954 if (members == null)
1955 members = new ArrayList (4);
1962 if (properties != null) {
1963 int len = properties.Count;
1964 for (int i = 0; i < len; i++) {
1965 Property p = (Property) properties [i];
1967 if ((p.ModFlags & modflags) == 0)
1969 if ((p.ModFlags & static_mask) != static_flags)
1975 if (b != null && filter (b, criteria) == true) {
1976 if (members == null)
1977 members = new ArrayList ();
1983 if (b != null && filter (b, criteria) == true) {
1984 if (members == null)
1985 members = new ArrayList ();
1992 if (indexers != null) {
1993 int len = indexers.Count;
1994 for (int i = 0; i < len; i++) {
1995 Indexer ix = (Indexer) indexers [i];
1997 if ((ix.ModFlags & modflags) == 0)
1999 if ((ix.ModFlags & static_mask) != static_flags)
2005 if (b != null && filter (b, criteria) == true) {
2006 if (members == null)
2007 members = new ArrayList ();
2013 if (b != null && filter (b, criteria) == true) {
2014 if (members == null)
2015 members = new ArrayList ();
2023 if ((mt & MemberTypes.Event) != 0) {
2024 if (events != null) {
2025 int len = events.Count;
2026 for (int i = 0; i < len; i++) {
2027 Event e = (Event) events [i];
2029 if ((e.ModFlags & modflags) == 0)
2031 if ((e.ModFlags & static_mask) != static_flags)
2034 MemberInfo eb = e.EventBuilder;
2035 if (eb != null && filter (eb, criteria) == true) {
2036 if (members == null)
2037 members = new ArrayList ();
2039 members.Add (e.EventBuilder);
2045 if ((mt & MemberTypes.Property) != 0){
2046 if (properties != null) {
2047 int len = properties.Count;
2048 for (int i = 0; i < len; i++) {
2049 Property p = (Property) properties [i];
2051 if ((p.ModFlags & modflags) == 0)
2053 if ((p.ModFlags & static_mask) != static_flags)
2056 MemberInfo pb = p.PropertyBuilder;
2057 if (pb != null && filter (pb, criteria) == true) {
2058 if (members == null)
2059 members = new ArrayList ();
2061 members.Add (p.PropertyBuilder);
2066 if (indexers != null) {
2067 int len = indexers.Count;
2068 for (int i = 0; i < len; i++) {
2069 Indexer ix = (Indexer) indexers [i];
2071 if ((ix.ModFlags & modflags) == 0)
2073 if ((ix.ModFlags & static_mask) != static_flags)
2076 MemberInfo ib = ix.PropertyBuilder;
2077 if (ib != null && filter (ib, criteria) == true) {
2078 if (members == null)
2079 members = new ArrayList ();
2081 members.Add (ix.PropertyBuilder);
2087 if ((mt & MemberTypes.NestedType) != 0)
2088 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2090 if ((mt & MemberTypes.Constructor) != 0){
2091 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2092 int len = instance_constructors.Count;
2093 for (int i = 0; i < len; i++) {
2094 Constructor c = (Constructor) instance_constructors [i];
2096 ConstructorBuilder cb = c.ConstructorBuilder;
2097 if (cb != null && filter (cb, criteria) == true) {
2098 if (members == null)
2099 members = new ArrayList ();
2106 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2107 ConstructorBuilder cb =
2108 default_static_constructor.ConstructorBuilder;
2110 if (cb != null && filter (cb, criteria) == true) {
2111 if (members == null)
2112 members = new ArrayList ();
2120 // Lookup members in base if requested.
2122 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2123 if (TypeBuilder.BaseType != null) {
2124 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2125 if (list.Count > 0) {
2126 if (members == null)
2127 members = new ArrayList ();
2129 members.AddRange (list);
2134 Timer.StopTimer (TimerType.TcFindMembers);
2136 if (members == null)
2137 return MemberList.Empty;
2139 return new MemberList (members);
2142 public override MemberCache MemberCache {
2144 return member_cache;
2148 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2149 MemberFilter filter, object criteria)
2151 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2154 return ds.FindMembers (mt, bf, filter, criteria);
2156 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2160 /// Emits the values for the constants
2162 public void EmitConstants ()
2164 if (constants != null)
2165 foreach (Const con in constants)
2170 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2175 foreach (MemberCore mc in al) {
2176 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2180 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2185 public virtual void VerifyMembers ()
2188 // Check for internal or private fields that were never assigned
2190 if (Report.WarningLevel >= 3) {
2191 CheckMemberUsage (properties, "property");
2192 CheckMemberUsage (methods, "method");
2193 CheckMemberUsage (constants, "constant");
2195 if (fields != null){
2196 foreach (FieldBase f in fields) {
2197 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2201 if ((f.caching_flags & Flags.IsAssigned) == 0)
2202 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2205 const int error_code = 414;
2207 const int error_code = 169;
2209 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2210 f.GetSignatureForError ());
2216 // Only report 649 on level 4
2218 if (Report.WarningLevel < 4)
2221 if ((f.caching_flags & Flags.IsAssigned) != 0)
2224 Constant c = New.Constantify (f.Type.Type);
2225 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2226 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2232 // TODO: move to ClassOrStruct
2233 void EmitConstructors ()
2235 if (instance_constructors == null)
2238 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2239 bool has_compliant_args = false;
2241 foreach (Constructor c in instance_constructors) {
2245 catch (Exception e) {
2246 throw new InternalErrorException (c, e);
2249 if (has_compliant_args)
2252 has_compliant_args = c.HasCompliantArgs;
2254 if (!has_compliant_args)
2255 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2257 foreach (Constructor c in instance_constructors) {
2261 catch (Exception e) {
2262 throw new InternalErrorException (c, e);
2269 /// Emits the code, this step is performed after all
2270 /// the types, enumerations, constructors
2272 public virtual void EmitType ()
2274 if (OptAttributes != null)
2275 OptAttributes.Emit ();
2279 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2280 for (int i = offset; i < gen_params.Length; i++)
2281 CurrentTypeParameters [i - offset].EmitAttributes ();
2286 // Structs with no fields need to have at least one byte.
2287 // The right thing would be to set the PackingSize in a DefineType
2288 // but there are no functions that allow interfaces *and* the size to
2292 if (Kind == Kind.Struct && first_nonstatic_field == null){
2293 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2294 FieldAttributes.Private);
2296 if (HasExplicitLayout){
2297 object [] ctor_args = new object [1];
2300 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2301 TypeManager.field_offset_attribute_ctor, ctor_args);
2302 fb.SetCustomAttribute (cba);
2308 EmitConstructors ();
2310 // Can not continue if constants are broken
2312 if (Report.Errors > 0)
2315 if (default_static_constructor != null)
2316 default_static_constructor.Emit ();
2318 if (methods != null){
2319 for (int i = 0; i < methods.Count; ++i)
2320 ((Method)methods[i]).Emit ();
2323 if (operators != null)
2324 foreach (Operator o in operators)
2327 if (properties != null)
2328 foreach (Property p in properties)
2331 if (indexers != null) {
2332 foreach (Indexer indx in indexers)
2338 foreach (FieldBase f in fields)
2341 if (events != null){
2342 foreach (Event e in Events)
2346 if (delegates != null) {
2347 foreach (Delegate d in Delegates) {
2352 if (pending != null)
2353 if (pending.VerifyPendingMethods ())
2356 if (Report.Errors > 0)
2359 if (compiler_generated != null) {
2360 foreach (CompilerGeneratedClass c in compiler_generated) {
2361 if (!c.DefineMembers ())
2362 throw new InternalErrorException ();
2364 foreach (CompilerGeneratedClass c in compiler_generated)
2369 public override void CloseType ()
2371 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2375 caching_flags |= Flags.CloseTypeCreated;
2376 TypeBuilder.CreateType ();
2377 } catch (TypeLoadException){
2379 // This is fine, the code still created the type
2381 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2382 // Console.WriteLine (e.Message);
2383 } catch (Exception e) {
2384 throw new InternalErrorException (this, e);
2388 foreach (TypeContainer tc in Types)
2389 if (tc.Kind == Kind.Struct)
2392 foreach (TypeContainer tc in Types)
2393 if (tc.Kind != Kind.Struct)
2397 if (Delegates != null)
2398 foreach (Delegate d in Delegates)
2401 if (CompilerGenerated != null)
2402 foreach (CompilerGeneratedClass c in CompilerGenerated)
2409 initialized_fields = null;
2410 initialized_static_fields = null;
2412 ordered_explicit_member_list = null;
2413 ordered_member_list = null;
2418 compiler_generated = null;
2419 default_constructor = null;
2420 default_static_constructor = null;
2422 OptAttributes = null;
2425 member_cache = null;
2429 // Performs the validation on a Method's modifiers (properties have
2430 // the same properties).
2432 public bool MethodModifiersValid (MemberCore mc)
2434 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2435 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2436 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2438 int flags = mc.ModFlags;
2441 // At most one of static, virtual or override
2443 if ((flags & Modifiers.STATIC) != 0){
2444 if ((flags & vao) != 0){
2445 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2446 mc.GetSignatureForError ());
2451 if (Kind == Kind.Struct){
2452 if ((flags & va) != 0){
2453 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2458 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2459 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2460 mc.GetSignatureForError ());
2465 // If the declaration includes the abstract modifier, then the
2466 // declaration does not include static, virtual or extern
2468 if ((flags & Modifiers.ABSTRACT) != 0){
2469 if ((flags & Modifiers.EXTERN) != 0){
2471 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2475 if ((flags & Modifiers.SEALED) != 0) {
2476 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2480 if ((flags & Modifiers.VIRTUAL) != 0){
2481 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2485 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2486 Report.SymbolRelatedToPreviousError (this);
2487 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2488 mc.GetSignatureForError (), GetSignatureForError ());
2493 if ((flags & Modifiers.PRIVATE) != 0){
2494 if ((flags & vao) != 0){
2495 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2500 if ((flags & Modifiers.SEALED) != 0){
2501 if ((flags & Modifiers.OVERRIDE) == 0){
2502 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2510 public Constructor DefaultStaticConstructor {
2511 get { return default_static_constructor; }
2514 protected override bool VerifyClsCompliance ()
2516 if (!base.VerifyClsCompliance ())
2521 Type base_type = TypeBuilder.BaseType;
2522 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2523 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2530 /// Checks whether container name is CLS Compliant
2532 void VerifyClsName ()
2534 Hashtable base_members = base_cache == null ?
2536 base_cache.GetPublicMembers ();
2537 Hashtable this_members = new Hashtable ();
2539 foreach (DictionaryEntry entry in defined_names) {
2540 MemberCore mc = (MemberCore)entry.Value;
2541 if (!mc.IsClsComplianceRequired ())
2544 string name = (string) entry.Key;
2545 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2547 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2548 object found = base_members [lcase];
2549 if (found == null) {
2550 found = this_members [lcase];
2551 if (found == null) {
2552 this_members.Add (lcase, mc);
2557 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2560 if (found is MemberInfo) {
2561 if (basename == ((MemberInfo) found).Name)
2563 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2565 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2568 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2570 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2577 /// Performs checks for an explicit interface implementation. First it
2578 /// checks whether the `interface_type' is a base inteface implementation.
2579 /// Then it checks whether `name' exists in the interface type.
2581 public virtual bool VerifyImplements (InterfaceMemberBase mb)
2583 if (ifaces != null) {
2584 foreach (Type t in ifaces){
2585 if (t == mb.InterfaceType)
2590 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2591 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2592 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2596 public override Type LookupAnyGeneric (string typeName)
2598 if (types != null) {
2599 foreach (TypeContainer tc in types) {
2603 int pos = tc.Basename.LastIndexOf ('`');
2604 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2605 return tc.TypeBuilder;
2609 return base.LookupAnyGeneric (typeName);
2612 public void Mark_HasEquals ()
2614 cached_method |= CachedMethods.Equals;
2617 public void Mark_HasGetHashCode ()
2619 cached_method |= CachedMethods.GetHashCode;
2623 /// Method container contains Equals method
2625 public bool HasEquals {
2627 return (cached_method & CachedMethods.Equals) != 0;
2632 /// Method container contains GetHashCode method
2634 public bool HasGetHashCode {
2636 return (cached_method & CachedMethods.GetHashCode) != 0;
2644 string IMemberContainer.Name {
2650 Type IMemberContainer.Type {
2656 MemberCache IMemberContainer.MemberCache {
2658 return member_cache;
2662 bool IMemberContainer.IsInterface {
2664 return Kind == Kind.Interface;
2668 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2670 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2672 if (GenericType != null)
2673 return TypeManager.FindMembers (GenericType, mt, new_bf,
2676 return FindMembers (mt, new_bf, null, null);
2680 // Generates xml doc comments (if any), and if required,
2681 // handle warning report.
2683 internal override void GenerateDocComment (DeclSpace ds)
2685 DocUtil.GenerateTypeDocComment (this, ds);
2688 public override string DocCommentHeader {
2689 get { return "T:"; }
2692 public virtual MemberCache BaseCache {
2694 if (base_cache != null)
2696 if (TypeBuilder.BaseType != null)
2697 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2698 if (TypeBuilder.IsInterface)
2699 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2705 public abstract class ClassOrStruct : TypeContainer {
2706 ListDictionary declarative_security;
2708 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2709 MemberName name, Attributes attrs, Kind kind)
2710 : base (ns, parent, name, attrs, kind)
2714 protected override bool AddToContainer (MemberCore symbol, string name)
2716 if (name == MemberName.Name) {
2717 if (symbol is TypeParameter) {
2718 Report.Error (694, symbol.Location,
2719 "Type parameter `{0}' has same name as " +
2720 "containing type, or method", name);
2724 Report.SymbolRelatedToPreviousError (this);
2725 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2726 symbol.GetSignatureForError ());
2730 return base.AddToContainer (symbol, name);
2733 public override void VerifyMembers ()
2735 base.VerifyMembers ();
2737 if ((events != null) && Report.WarningLevel >= 3) {
2738 foreach (Event e in events){
2739 if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2742 if ((e.caching_flags & Flags.IsUsed) == 0)
2743 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2748 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2750 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2751 if (declarative_security == null)
2752 declarative_security = new ListDictionary ();
2754 a.ExtractSecurityPermissionSet (declarative_security);
2758 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2759 HasExplicitLayout = true;
2762 base.ApplyAttributeBuilder (a, cb);
2766 /// Defines the default constructors
2768 protected void DefineDefaultConstructor (bool is_static)
2770 // The default instance constructor is public
2771 // If the class is abstract, the default constructor is protected
2772 // The default static constructor is private
2776 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2778 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2781 Constructor c = new Constructor (this, MemberName.Name, mods,
2782 Parameters.EmptyReadOnlyParameters,
2783 new GeneratedBaseInitializer (Location),
2787 c.Block = new ToplevelBlock (null, Location);
2790 void DefineFieldInitializers ()
2792 if (initialized_fields != null) {
2793 for (int i = 0; i < initialized_fields.Count; ++i) {
2794 FieldInitializer fi = (FieldInitializer)initialized_fields[i];
2796 EmitContext ec = new EmitContext (fi.TypeContainer, fi.TypeContainer,
2797 Location, null, TypeManager.void_type, ModFlags);
2798 ec.IsFieldInitializer = true;
2800 fi.ResolveStatement (ec);
2801 if (fi.IsDefaultInitializer && RootContext.Optimize) {
2802 // Field is re-initialized to its default value => removed
2803 initialized_fields.RemoveAt (i);
2809 if (initialized_static_fields != null) {
2810 bool has_complex_initializer = false;
2812 foreach (FieldInitializer fi in initialized_static_fields) {
2813 EmitContext ec = new EmitContext (fi.TypeContainer, fi.TypeContainer,
2814 Location, null, TypeManager.void_type, ModFlags);
2816 ec.IsFieldInitializer = true;
2818 fi.ResolveStatement (ec);
2819 if (!fi.IsComplexInitializer)
2822 has_complex_initializer = true;
2825 // Need special check to not optimize code like this
2826 // static int a = b = 5;
2827 // static int b = 0;
2828 if (!has_complex_initializer && RootContext.Optimize) {
2829 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2830 FieldInitializer fi = (FieldInitializer)initialized_static_fields[i];
2831 if (fi.IsDefaultInitializer) {
2832 initialized_static_fields.RemoveAt (i);
2838 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2839 DefineDefaultConstructor (true);
2845 public override bool Define ()
2847 DefineFieldInitializers ();
2849 if (default_static_constructor != null)
2850 default_static_constructor.Define ();
2852 return base.Define ();
2855 public override void Emit ()
2859 if (declarative_security != null) {
2860 foreach (DictionaryEntry de in declarative_security) {
2861 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2866 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
2868 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name);
2871 protected override TypeAttributes TypeAttr {
2873 if (default_static_constructor == null)
2874 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2876 return base.TypeAttr;
2882 // TODO: should be sealed
2883 public class Class : ClassOrStruct {
2884 const int AllowedModifiers =
2887 Modifiers.PROTECTED |
2888 Modifiers.INTERNAL |
2890 Modifiers.ABSTRACT |
2895 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2897 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2899 : base (ns, parent, name, attrs, Kind.Class)
2901 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2902 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2904 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2905 Report.FeatureIsNotISO1 (Location, "static classes");
2909 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2911 if (part.Name == "System.Object")
2912 Report.Error (537, part.Location,
2913 "The class System.Object cannot have a base class or implement an interface.");
2914 base.AddBasesForPart (part, bases);
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 ()
4545 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4546 MethodData.Emit (Parent);
4549 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4550 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4555 Console.WriteLine ("Interna compiler error at {0}: exception caught while emitting {1}",
4556 Location, MethodBuilder);
4561 public static void Error1599 (Location loc, Type t)
4563 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4566 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4568 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4569 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4574 if (mi.IsSpecialName)
4577 base_ret_type = mi.ReturnType;
4581 protected override bool VerifyClsCompliance ()
4583 if (!base.VerifyClsCompliance ())
4586 if (ParameterInfo.Count > 0) {
4587 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4589 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4596 public abstract class ConstructorInitializer {
4597 readonly ArrayList argument_list;
4598 MethodGroupExpr base_constructor_group;
4599 readonly Location loc;
4601 public ConstructorInitializer (ArrayList argument_list, Location loc)
4603 this.argument_list = argument_list;
4607 public ArrayList Arguments {
4609 return argument_list;
4613 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4617 ec.CurrentBlock = block;
4619 if (argument_list != null){
4620 foreach (Argument a in argument_list){
4621 if (!a.Resolve (ec, loc))
4625 ec.CurrentBlock = null;
4627 if (this is ConstructorBaseInitializer) {
4628 if (ec.ContainerType.BaseType == null)
4631 t = ec.ContainerType.BaseType;
4632 if (ec.ContainerType.IsValueType) {
4633 Report.Error (522, loc,
4634 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4639 // It is legal to have "this" initializers that take no arguments
4640 // in structs, they are just no-ops.
4642 // struct D { public D (int a) : this () {}
4644 if (ec.ContainerType.IsValueType && argument_list == null)
4647 t = ec.ContainerType;
4650 base_constructor_group = Expression.MemberLookup (
4651 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4652 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4653 loc) as MethodGroupExpr;
4655 bool error_non_public = false;
4656 if (base_constructor_group == null) {
4657 error_non_public = true;
4658 base_constructor_group = Expression.MemberLookup (
4659 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4660 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4661 loc) as MethodGroupExpr;
4663 // TODO: because of MemberLookup is so broken. It does not return private members
4664 // even if you ask for them.
4665 if (base_constructor_group == null) {
4666 Expression.MemberLookupFailed (ec.ContainerType, t, t, ".ctor", null, true, loc);
4671 base_constructor_group = base_constructor_group.OverloadResolve (
4672 ec, argument_list, false, loc);
4674 if (base_constructor_group == null)
4677 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4679 if (base_ctor == caller_builder){
4680 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4683 if (error_non_public) {
4684 Report.SymbolRelatedToPreviousError (base_ctor);
4685 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_ctor));
4691 public void Emit (EmitContext ec)
4693 // It can be null for static initializers
4694 if (base_constructor_group == null)
4697 ec.Mark (loc, false);
4699 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4701 base_constructor_group.EmitCall (ec, argument_list);
4705 public class ConstructorBaseInitializer : ConstructorInitializer {
4706 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4707 base (argument_list, l)
4712 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4713 public GeneratedBaseInitializer (Location loc):
4719 public class ConstructorThisInitializer : ConstructorInitializer {
4720 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4721 base (argument_list, l)
4726 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4727 public ConstructorBuilder ConstructorBuilder;
4728 public ConstructorInitializer Initializer;
4729 ListDictionary declarative_security;
4730 ArrayList anonymous_methods;
4733 // Modifiers allowed for a constructor.
4735 public const int AllowedModifiers =
4737 Modifiers.PROTECTED |
4738 Modifiers.INTERNAL |
4744 static string[] attribute_targets = new string [] { "method" };
4746 public Iterator Iterator {
4747 get { return null; }
4750 bool has_compliant_args = false;
4752 // The spec claims that static is not permitted, but
4753 // my very own code has static constructors.
4755 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4756 ConstructorInitializer init, Location loc)
4757 : base (parent, null, null, mod, AllowedModifiers, false,
4758 new MemberName (name, loc), null, args)
4763 public bool HasCompliantArgs {
4764 get { return has_compliant_args; }
4767 public override AttributeTargets AttributeTargets {
4768 get { return AttributeTargets.Constructor; }
4773 // Returns true if this is a default constructor
4775 public bool IsDefault ()
4777 if ((ModFlags & Modifiers.STATIC) != 0)
4778 return Parameters.Empty;
4780 return Parameters.Empty &&
4781 (Initializer is ConstructorBaseInitializer) &&
4782 (Initializer.Arguments == null);
4785 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4787 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4788 if (declarative_security == null) {
4789 declarative_security = new ListDictionary ();
4791 a.ExtractSecurityPermissionSet (declarative_security);
4795 if (a.IsInternalMethodImplAttribute) {
4796 is_external_implementation = true;
4799 ConstructorBuilder.SetCustomAttribute (cb);
4802 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4804 if (anonymous_methods == null)
4805 anonymous_methods = new ArrayList ();
4806 anonymous_methods.Add (anonymous);
4809 public bool ResolveMembers ()
4811 if (anonymous_methods != null) {
4812 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4813 if (!ame.CreateAnonymousHelpers ())
4821 protected override bool CheckForDuplications ()
4823 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4825 int arLen = ar.Count;
4827 for (int i = 0; i < arLen; i++) {
4828 Constructor m = (Constructor) ar [i];
4829 if (IsDuplicateImplementation (m))
4836 protected override bool CheckBase ()
4838 if ((ModFlags & Modifiers.STATIC) != 0) {
4839 if (!Parameters.Empty) {
4840 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4841 GetSignatureForError ());
4845 // the rest can be ignored
4849 // Check whether arguments were correct.
4850 if (!DefineParameters (Parameters))
4853 if (!CheckForDuplications ())
4856 if (Parent.PartialContainer.Kind == Kind.Struct) {
4857 if (ParameterTypes.Length == 0) {
4858 Report.Error (568, Location,
4859 "Structs cannot contain explicit parameterless constructors");
4863 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4864 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4869 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0) {
4870 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4877 // Creates the ConstructorBuilder
4879 public override bool Define ()
4881 if (ConstructorBuilder != null)
4884 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4885 MethodAttributes.SpecialName);
4887 if ((ModFlags & Modifiers.STATIC) != 0) {
4888 ca |= MethodAttributes.Static | MethodAttributes.Private;
4890 ca |= MethodAttributes.HideBySig;
4892 if ((ModFlags & Modifiers.PUBLIC) != 0)
4893 ca |= MethodAttributes.Public;
4894 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4895 if ((ModFlags & Modifiers.INTERNAL) != 0)
4896 ca |= MethodAttributes.FamORAssem;
4898 ca |= MethodAttributes.Family;
4899 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4900 ca |= MethodAttributes.Assembly;
4902 ca |= MethodAttributes.Private;
4905 if (!CheckAbstractAndExtern (block != null))
4908 // Check if arguments were correct.
4912 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4913 ca, CallingConventions,
4916 if ((ModFlags & Modifiers.UNSAFE) != 0)
4917 ConstructorBuilder.InitLocals = false;
4919 if (Parent.PartialContainer.IsComImport) {
4920 if (!IsDefault ()) {
4921 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4922 Parent.GetSignatureForError ());
4925 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4928 TypeManager.AddMethod (ConstructorBuilder, this);
4936 public override void Emit ()
4938 if (OptAttributes != null)
4939 OptAttributes.Emit ();
4941 EmitContext ec = CreateEmitContext (null, null);
4943 if (block != null) {
4944 // If this is a non-static `struct' constructor and doesn't have any
4945 // initializer, it must initialize all of the struct's fields.
4946 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4947 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4948 block.AddThisVariable (Parent, Location);
4950 if (!block.ResolveMeta (ec, ParameterInfo))
4954 if ((ModFlags & Modifiers.STATIC) == 0){
4955 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4956 Initializer = new GeneratedBaseInitializer (Location);
4960 // Spec mandates that Initializers will not have
4964 if ((Initializer != null) &&
4965 !Initializer.Resolve (ConstructorBuilder, block, ec))
4967 ec.IsStatic = false;
4970 Parameters.ApplyAttributes (ConstructorBuilder);
4972 SourceMethod source = SourceMethod.Create (
4973 Parent, ConstructorBuilder, block);
4976 // Classes can have base initializers and instance field initializers.
4978 if (Parent.PartialContainer.Kind == Kind.Class){
4979 if ((ModFlags & Modifiers.STATIC) == 0){
4982 // If we use a "this (...)" constructor initializer, then
4983 // do not emit field initializers, they are initialized in the other constructor
4985 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4986 Parent.PartialContainer.EmitFieldInitializers (ec);
4990 bool unreachable = false;
4991 if (block != null) {
4992 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4994 ec.EmitMeta (block);
4996 if (block.ScopeInfo != null) {
4997 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4998 init.EmitStatement (ec);
5002 if (Initializer != null) {
5003 Initializer.Emit (ec);
5006 if ((ModFlags & Modifiers.STATIC) != 0)
5007 Parent.PartialContainer.EmitFieldInitializers (ec);
5010 ec.EmitResolvedTopBlock (block, unreachable);
5013 source.CloseMethod ();
5017 if (declarative_security != null) {
5018 foreach (DictionaryEntry de in declarative_security) {
5019 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5026 // Is never override
5027 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5032 public override string GetSignatureForError()
5034 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
5037 public override string[] ValidAttributeTargets {
5039 return attribute_targets;
5043 protected override bool VerifyClsCompliance ()
5045 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
5049 if (ParameterInfo.Count > 0) {
5050 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
5052 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
5054 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
5055 foreach (Type param in ParameterTypes) {
5056 if (param.IsArray) {
5062 has_compliant_args = true;
5066 #region IMethodData Members
5068 public System.Reflection.CallingConventions CallingConventions {
5070 CallingConventions cc = Parameters.CallingConvention;
5072 if (Parent.PartialContainer.Kind == Kind.Class)
5073 if ((ModFlags & Modifiers.STATIC) == 0)
5074 cc |= CallingConventions.HasThis;
5076 // FIXME: How is `ExplicitThis' used in C#?
5082 public new Location Location {
5084 return base.Location;
5088 public MemberName MethodName {
5094 public Type ReturnType {
5100 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5102 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5103 return new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5106 public bool IsExcluded()
5111 GenericMethod IMethodData.GenericMethod {
5121 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5123 public interface IMethodData
5125 CallingConventions CallingConventions { get; }
5126 Location Location { get; }
5127 MemberName MethodName { get; }
5128 Type ReturnType { get; }
5129 GenericMethod GenericMethod { get; }
5130 Parameters ParameterInfo { get; }
5132 Iterator Iterator { get; }
5134 Attributes OptAttributes { get; }
5135 ToplevelBlock Block { get; set; }
5137 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5138 ObsoleteAttribute GetObsoleteAttribute ();
5139 string GetSignatureForError ();
5141 bool IsClsComplianceRequired ();
5142 void SetMemberIsUsed ();
5146 // Encapsulates most of the Method's state
5148 public class MethodData {
5150 readonly IMethodData method;
5152 public readonly GenericMethod GenericMethod;
5155 // Are we implementing an interface ?
5157 public MethodInfo implementing;
5162 protected InterfaceMemberBase member;
5163 protected int modifiers;
5164 protected MethodAttributes flags;
5165 protected Type declaring_type;
5166 protected MethodInfo parent_method;
5168 MethodBuilder builder = null;
5169 public MethodBuilder MethodBuilder {
5175 public Type DeclaringType {
5177 return declaring_type;
5181 public MethodData (InterfaceMemberBase member,
5182 int modifiers, MethodAttributes flags, IMethodData method)
5184 this.member = member;
5185 this.modifiers = modifiers;
5188 this.method = method;
5191 public MethodData (InterfaceMemberBase member,
5192 int modifiers, MethodAttributes flags,
5193 IMethodData method, MethodBuilder builder,
5194 GenericMethod generic, MethodInfo parent_method)
5195 : this (member, modifiers, flags, method)
5197 this.builder = builder;
5198 this.GenericMethod = generic;
5199 this.parent_method = parent_method;
5202 public bool Define (DeclSpace parent)
5204 string name = method.MethodName.Basename;
5205 string method_name = method.MethodName.FullName;
5207 TypeContainer container = parent.PartialContainer;
5209 PendingImplementation pending = container.PendingImplementations;
5210 if (pending != null){
5211 if (member is Indexer) // TODO: test it, but it should work without this IF
5212 implementing = pending.IsInterfaceIndexer (
5213 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5215 implementing = pending.IsInterfaceMethod (
5216 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5218 if (member.InterfaceType != null){
5219 if (implementing == null){
5220 if (member is PropertyBase) {
5221 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5222 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5223 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5226 Report.Error (539, method.Location,
5227 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5228 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5232 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5233 Report.SymbolRelatedToPreviousError (implementing);
5234 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5235 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5239 method_name = member.InterfaceType.FullName +
5242 if (implementing != null) {
5243 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5244 if (prop_method == null) {
5245 if (implementing.IsSpecialName) {
5246 Report.SymbolRelatedToPreviousError (implementing);
5247 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5248 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5249 implementing.Name.StartsWith ("get_") ? "get" : "set");
5252 } else if (implementing.DeclaringType.IsInterface) {
5253 if (!implementing.IsSpecialName) {
5254 Report.SymbolRelatedToPreviousError (implementing);
5255 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5256 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5259 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5260 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5261 Report.SymbolRelatedToPreviousError (implementing);
5262 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5263 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5272 // For implicit implementations, make sure we are public, for
5273 // explicit implementations, make sure we are private.
5275 if (implementing != null){
5277 // Setting null inside this block will trigger a more
5278 // verbose error reporting for missing interface implementations
5280 // The "candidate" function has been flagged already
5281 // but it wont get cleared
5283 if (member.IsExplicitImpl){
5284 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5285 Report.SymbolRelatedToPreviousError (implementing);
5286 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5287 method.GetSignatureForError ());
5291 if (implementing.DeclaringType.IsInterface) {
5293 // If this is an interface method implementation,
5294 // check for public accessibility
5296 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5298 implementing = null;
5300 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5301 // We may never be private.
5302 implementing = null;
5304 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5306 // We may be protected if we're overriding something.
5308 implementing = null;
5313 // Static is not allowed
5315 if ((modifiers & Modifiers.STATIC) != 0){
5316 implementing = null;
5321 // If implementing is still valid, set flags
5323 if (implementing != null){
5325 // When implementing interface methods, set NewSlot
5326 // unless, we are overwriting a method.
5328 if (implementing.DeclaringType.IsInterface){
5329 if ((modifiers & Modifiers.OVERRIDE) == 0)
5330 flags |= MethodAttributes.NewSlot;
5333 MethodAttributes.Virtual |
5334 MethodAttributes.HideBySig;
5336 // Set Final unless we're virtual, abstract or already overriding a method.
5337 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5338 flags |= MethodAttributes.Final;
5341 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
5343 if (builder == null)
5346 if (container.CurrentType != null)
5347 declaring_type = container.CurrentType;
5349 declaring_type = container.TypeBuilder;
5351 if ((modifiers & Modifiers.UNSAFE) != 0)
5352 builder.InitLocals = false;
5355 if (implementing != null){
5357 // clear the pending implemntation flag
5359 if (member is Indexer) {
5360 pending.ImplementIndexer (
5361 member.InterfaceType, builder, method.ReturnType,
5362 method.ParameterInfo, member.IsExplicitImpl);
5364 pending.ImplementMethod (
5365 member.InterfaceType, name, method.ReturnType,
5366 method.ParameterInfo, member.IsExplicitImpl);
5368 if (member.IsExplicitImpl)
5369 container.TypeBuilder.DefineMethodOverride (
5370 builder, implementing);
5373 TypeManager.AddMethod (builder, method);
5375 if (GenericMethod != null) {
5376 bool is_override = member.IsExplicitImpl |
5377 ((modifiers & Modifiers.OVERRIDE) != 0);
5379 if (implementing != null)
5380 parent_method = implementing;
5382 EmitContext ec = method.CreateEmitContext (container, null);
5383 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5392 /// Create the MethodBuilder for the method
5394 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5396 if (builder == null) {
5397 builder = container.TypeBuilder.DefineMethod (
5398 method_name, flags, method.CallingConventions,
5399 method.ReturnType, ParameterTypes);
5403 #if GMCS_SOURCE && !MS_COMPATIBLE
5404 builder.SetGenericMethodSignature (
5405 flags, method.CallingConventions,
5406 method.ReturnType, ParameterTypes);
5413 public void Emit (DeclSpace parent)
5415 ToplevelBlock block = method.Block;
5419 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5421 ec = method.CreateEmitContext (parent, null);
5423 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5425 if (GenericMethod != null)
5426 GenericMethod.EmitAttributes ();
5428 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5431 // Handle destructors specially
5433 // FIXME: This code generates buggy code
5435 if (member is Destructor)
5436 EmitDestructor (ec, block);
5438 ec.EmitTopBlock (method, block);
5441 source.CloseMethod ();
5444 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5446 ILGenerator ig = ec.ig;
5448 Label finish = ig.DefineLabel ();
5450 block.SetDestructor ();
5452 ig.BeginExceptionBlock ();
5453 ec.ReturnLabel = finish;
5454 ec.HasReturnLabel = true;
5455 ec.EmitTopBlock (method, block);
5457 // ig.MarkLabel (finish);
5458 ig.BeginFinallyBlock ();
5460 if (ec.ContainerType.BaseType != null) {
5461 Expression member_lookup = Expression.MemberLookup (
5462 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5463 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5465 if (member_lookup != null){
5466 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5468 ig.Emit (OpCodes.Ldarg_0);
5469 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5473 ig.EndExceptionBlock ();
5474 //ig.MarkLabel (ec.ReturnLabel);
5475 ig.Emit (OpCodes.Ret);
5479 // TODO: Should derive from MethodCore
5480 public class Destructor : Method {
5482 static string[] attribute_targets = new string [] { "method" };
5484 public Destructor (DeclSpace parent, Expression return_type, int mod,
5485 string name, Parameters parameters, Attributes attrs,
5487 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5491 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5493 if (a.Type == TypeManager.conditional_attribute_type) {
5494 Error_ConditionalAttributeIsNotValid ();
5498 base.ApplyAttributeBuilder (a, cb);
5501 public override string GetSignatureForError ()
5503 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5506 public override string[] ValidAttributeTargets {
5508 return attribute_targets;
5513 abstract public class MemberBase : MemberCore {
5514 public Expression Type;
5515 public readonly DeclSpace ds;
5516 public readonly GenericMethod GenericMethod;
5519 // The type of this property / indexer / event
5521 protected Type member_type;
5522 public Type MemberType {
5524 if (member_type == null && Type != null) {
5525 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5526 Type = Type.ResolveAsTypeTerminal (rc, false);
5528 member_type = Type.Type;
5536 // The constructor is only exposed to our children
5538 protected MemberBase (DeclSpace parent, GenericMethod generic,
5539 Expression type, int mod, int allowed_mod, int def_mod,
5540 MemberName name, Attributes attrs)
5541 : base (parent, name, attrs)
5543 this.ds = generic != null ? generic : (DeclSpace) parent;
5545 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5546 GenericMethod = generic;
5547 if (GenericMethod != null)
5548 GenericMethod.ModFlags = ModFlags;
5551 protected virtual bool CheckBase ()
5553 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5554 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5558 if (Report.WarningLevel >= 4 &&
5559 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5560 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5561 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5562 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5567 protected virtual bool DoDefine ()
5569 if (MemberType == null)
5572 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5573 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5574 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5575 GetSignatureForError (), Parent.GetSignatureForError ());
5579 // verify accessibility
5580 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5581 Report.SymbolRelatedToPreviousError (MemberType);
5582 if (this is Property)
5583 Report.Error (53, Location,
5584 "Inconsistent accessibility: property type `" +
5585 TypeManager.CSharpName (MemberType) + "' is less " +
5586 "accessible than property `" + GetSignatureForError () + "'");
5587 else if (this is Indexer)
5588 Report.Error (54, Location,
5589 "Inconsistent accessibility: indexer return type `" +
5590 TypeManager.CSharpName (MemberType) + "' is less " +
5591 "accessible than indexer `" + GetSignatureForError () + "'");
5592 else if (this is MethodCore) {
5593 if (this is Operator)
5594 Report.Error (56, Location,
5595 "Inconsistent accessibility: return type `" +
5596 TypeManager.CSharpName (MemberType) + "' is less " +
5597 "accessible than operator `" + GetSignatureForError () + "'");
5599 Report.Error (50, Location,
5600 "Inconsistent accessibility: return type `" +
5601 TypeManager.CSharpName (MemberType) + "' is less " +
5602 "accessible than method `" + GetSignatureForError () + "'");
5604 Report.Error (52, Location,
5605 "Inconsistent accessibility: field type `" +
5606 TypeManager.CSharpName (MemberType) + "' is less " +
5607 "accessible than field `" + GetSignatureForError () + "'");
5615 protected bool IsTypePermitted ()
5617 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5618 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5626 // Abstract class for all fields
5628 abstract public class FieldBase : MemberBase {
5629 public FieldBuilder FieldBuilder;
5630 public Status status;
5631 protected Expression initializer;
5634 public enum Status : byte {
5635 HAS_OFFSET = 4 // Used by FieldMember.
5638 static readonly string[] attribute_targets = new string [] { "field" };
5640 protected FieldBase (DeclSpace parent, Expression type, int mod,
5641 int allowed_mod, MemberName name, Attributes attrs)
5642 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5645 if ((mod & Modifiers.ABSTRACT) != 0)
5646 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5649 public override AttributeTargets AttributeTargets {
5651 return AttributeTargets.Field;
5655 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5657 if (a.Type == TypeManager.field_offset_attribute_type) {
5658 status |= Status.HAS_OFFSET;
5660 if (!Parent.PartialContainer.HasExplicitLayout) {
5661 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5665 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5666 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5672 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5673 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5678 if (a.Type == TypeManager.marshal_as_attr_type) {
5679 UnmanagedMarshal marshal = a.GetMarshal (this);
5680 if (marshal != null) {
5681 FieldBuilder.SetMarshal (marshal);
5686 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5687 a.Error_InvalidSecurityParent ();
5691 FieldBuilder.SetCustomAttribute (cb);
5694 protected override bool CheckBase ()
5696 if (!base.CheckBase ())
5699 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5700 if (conflict_symbol == null) {
5701 if ((ModFlags & Modifiers.NEW) != 0) {
5702 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5707 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5708 Report.SymbolRelatedToPreviousError (conflict_symbol);
5709 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5710 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5716 public override bool Define()
5718 if (MemberType == null || Type == null)
5721 if (TypeManager.IsGenericParameter (MemberType))
5724 if (MemberType == TypeManager.void_type) {
5725 // TODO: wrong location
5726 Expression.Error_VoidInvalidInTheContext (Location);
5730 if (MemberType.IsSealed && MemberType.IsAbstract) {
5731 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5738 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5739 Report.Error (52, Location,
5740 "Inconsistent accessibility: field type `" +
5741 TypeManager.CSharpName (MemberType) + "' is less " +
5742 "accessible than field `" + GetSignatureForError () + "'");
5746 if (!IsTypePermitted ())
5753 // Represents header string for documentation comment.
5755 public override string DocCommentHeader {
5756 get { return "F:"; }
5759 public override void Emit ()
5762 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5763 FieldBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
5767 if (OptAttributes != null) {
5768 OptAttributes.Emit ();
5771 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5772 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5778 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5780 Report.SymbolRelatedToPreviousError (static_class);
5781 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5785 public Expression Initializer {
5787 if (value != null) {
5788 this.initializer = value;
5793 protected virtual bool IsFieldClsCompliant {
5795 if (FieldBuilder == null)
5798 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5802 public override string[] ValidAttributeTargets
5805 return attribute_targets;
5809 protected override bool VerifyClsCompliance ()
5811 if (!base.VerifyClsCompliance ())
5814 if (!IsFieldClsCompliant) {
5815 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5820 public void SetAssigned ()
5822 caching_flags |= Flags.IsAssigned;
5826 interface IFixedBuffer
5828 FieldInfo Element { get; }
5829 Type ElementType { get; }
5832 public class FixedFieldExternal: IFixedBuffer
5834 FieldInfo element_field;
5836 public FixedFieldExternal (FieldInfo fi)
5838 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5841 #region IFixedField Members
5843 public FieldInfo Element {
5845 return element_field;
5849 public Type ElementType {
5851 return element_field.FieldType;
5859 /// Fixed buffer implementation
5861 public class FixedField : FieldBase, IFixedBuffer
5863 public const string FixedElementName = "FixedElementField";
5864 static int GlobalCounter = 0;
5865 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5866 static FieldInfo[] fi;
5868 TypeBuilder fixed_buffer_type;
5869 FieldBuilder element;
5870 Expression size_expr;
5873 const int AllowedModifiers =
5876 Modifiers.PROTECTED |
5877 Modifiers.INTERNAL |
5880 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5881 Expression size_expr, Attributes attrs, Location loc):
5882 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5884 if (RootContext.Version == LanguageVersion.ISO_1)
5885 Report.FeatureIsNotISO1 (loc, "fixed size buffers");
5887 if ((mod & Modifiers.VOLATILE) != 0)
5888 Modifiers.Error_InvalidModifier (loc, Modifiers.Name (Modifiers.VOLATILE));
5890 this.size_expr = size_expr;
5893 public override bool Define()
5896 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5897 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5900 if (Parent.PartialContainer.Kind != Kind.Struct) {
5901 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5902 GetSignatureForError ());
5905 if (!Parent.IsInUnsafeScope)
5906 Expression.UnsafeError (Location);
5908 if (!base.Define ())
5911 if (!TypeManager.IsPrimitiveType (MemberType)) {
5912 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",
5913 GetSignatureForError ());
5917 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5918 Constant c = size_expr.ResolveAsConstant (ec, this);
5922 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5923 if (buffer_size_const == null)
5926 buffer_size = buffer_size_const.Value;
5928 if (buffer_size <= 0) {
5929 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5933 int type_size = Expression.GetTypeSize (MemberType);
5935 if (buffer_size > int.MaxValue / type_size) {
5936 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5937 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5941 buffer_size *= type_size;
5944 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5946 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5947 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5948 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5949 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5951 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5952 TypeManager.RegisterFieldBase (FieldBuilder, this);
5957 public override void Emit()
5960 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5962 object[] fi_val = new object[1];
5963 fi_val [0] = buffer_size;
5965 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5966 ctor_args, fi, fi_val);
5967 fixed_buffer_type.SetCustomAttribute (cab);
5970 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5971 FieldBuilder.SetCustomAttribute (cab);
5976 protected override bool IsFieldClsCompliant {
5982 #region IFixedField Members
5984 public FieldInfo Element {
5990 public Type ElementType {
6000 // The Field class is used to represents class/struct fields during parsing.
6002 public class Field : FieldBase {
6004 // Modifiers allowed in a class declaration
6006 const int AllowedModifiers =
6009 Modifiers.PROTECTED |
6010 Modifiers.INTERNAL |
6013 Modifiers.VOLATILE |
6017 public Field (DeclSpace parent, Expression type, int mod, string name,
6018 Attributes attrs, Location loc)
6019 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6024 public override bool Define ()
6026 if (!base.Define ())
6029 if ((ModFlags & Modifiers.VOLATILE) != 0){
6030 if (!MemberType.IsClass){
6031 Type vt = MemberType;
6033 if (TypeManager.IsEnumType (vt))
6034 vt = TypeManager.EnumToUnderlying (MemberType);
6036 if (!((vt == TypeManager.bool_type) ||
6037 (vt == TypeManager.sbyte_type) ||
6038 (vt == TypeManager.byte_type) ||
6039 (vt == TypeManager.short_type) ||
6040 (vt == TypeManager.ushort_type) ||
6041 (vt == TypeManager.int32_type) ||
6042 (vt == TypeManager.uint32_type) ||
6043 (vt == TypeManager.char_type) ||
6044 (vt == TypeManager.float_type) ||
6045 (!vt.IsValueType))){
6046 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6047 GetSignatureForError (), TypeManager.CSharpName (vt));
6052 if ((ModFlags & Modifiers.READONLY) != 0){
6053 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6054 GetSignatureForError ());
6059 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6061 if (Parent.PartialContainer.Kind == Kind.Struct &&
6062 ((fa & FieldAttributes.Static) == 0) &&
6063 MemberType == Parent.TypeBuilder &&
6064 !TypeManager.IsBuiltinType (MemberType)){
6065 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6066 "' causes a cycle in the structure layout");
6071 FieldBuilder = Parent.TypeBuilder.DefineField (
6072 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6074 TypeManager.RegisterFieldBase (FieldBuilder, this);
6076 catch (ArgumentException) {
6077 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6081 if (initializer != null)
6082 Parent.PartialContainer.RegisterFieldForInitialization (this,
6083 new FieldInitializer (FieldBuilder, initializer, Parent));
6088 protected override bool VerifyClsCompliance ()
6090 if (!base.VerifyClsCompliance ())
6093 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6094 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6102 // `set' and `get' accessors are represented with an Accessor.
6104 public class Accessor : IAnonymousHost {
6106 // Null if the accessor is empty, or a Block if not
6108 public const int AllowedModifiers =
6110 Modifiers.PROTECTED |
6111 Modifiers.INTERNAL |
6114 public ToplevelBlock Block;
6115 public Attributes Attributes;
6116 public Location Location;
6117 public int ModFlags;
6119 public ArrayList AnonymousMethods;
6121 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6126 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6129 public void SetYields ()
6134 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6136 if (AnonymousMethods == null)
6137 AnonymousMethods = new ArrayList ();
6138 AnonymousMethods.Add (ame);
6142 // Ooouh Martin, templates are missing here.
6143 // When it will be possible move here a lot of child code and template method type.
6144 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6145 protected MethodData method_data;
6146 protected ToplevelBlock block;
6147 protected ListDictionary declarative_security;
6149 // The accessor are created event if they are not wanted.
6150 // But we need them because their names are reserved.
6151 // Field says whether accessor will be emited or not
6152 public readonly bool IsDummy;
6154 protected readonly string prefix;
6156 ReturnParameter return_attributes;
6158 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6159 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6161 this.prefix = prefix;
6165 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6167 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6168 accessor.Attributes)
6170 this.prefix = prefix;
6171 this.block = accessor.Block;
6174 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6176 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6179 public void UpdateName (InterfaceMemberBase member)
6181 SetMemberName (SetupName (prefix, member, Location));
6184 #region IMethodData Members
6186 public abstract Iterator Iterator {
6190 public ToplevelBlock Block {
6200 public CallingConventions CallingConventions {
6202 return CallingConventions.Standard;
6206 public bool IsExcluded ()
6211 GenericMethod IMethodData.GenericMethod {
6217 public MemberName MethodName {
6223 public Type[] ParameterTypes {
6225 return ParameterInfo.Types;
6229 public abstract Parameters ParameterInfo { get ; }
6230 public abstract Type ReturnType { get; }
6231 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6235 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6237 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6238 a.Type == TypeManager.conditional_attribute_type) {
6239 Report.Error (1667, a.Location,
6240 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6241 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6245 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6246 if (declarative_security == null)
6247 declarative_security = new ListDictionary ();
6248 a.ExtractSecurityPermissionSet (declarative_security);
6252 if (a.Target == AttributeTargets.Method) {
6253 method_data.MethodBuilder.SetCustomAttribute (cb);
6257 if (a.Target == AttributeTargets.ReturnValue) {
6258 if (return_attributes == null)
6259 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6261 return_attributes.ApplyAttributeBuilder (a, cb);
6265 ApplyToExtraTarget (a, cb);
6268 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6270 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6273 // It is not supported for the accessors
6274 public sealed override bool Define()
6276 throw new NotSupportedException ();
6279 public void Emit (DeclSpace parent)
6281 EmitMethod (parent);
6284 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6285 method_data.MethodBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
6287 if (OptAttributes != null)
6288 OptAttributes.Emit ();
6290 if (declarative_security != null) {
6291 foreach (DictionaryEntry de in declarative_security) {
6292 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6299 protected virtual void EmitMethod (DeclSpace parent)
6301 method_data.Emit (parent);
6304 public override bool IsClsComplianceRequired()
6309 public bool IsDuplicateImplementation (MethodCore method)
6311 if (!MemberName.Equals (method.MemberName))
6314 Type[] param_types = method.ParameterTypes;
6316 if (param_types == null || param_types.Length != ParameterTypes.Length)
6319 for (int i = 0; i < param_types.Length; i++)
6320 if (param_types [i] != ParameterTypes [i])
6323 Report.SymbolRelatedToPreviousError (method);
6324 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6328 public override bool IsUsed
6338 public new Location Location {
6340 return base.Location;
6344 public virtual bool ResolveMembers ()
6350 // Represents header string for documentation comment.
6352 public override string DocCommentHeader {
6353 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6359 // Properties and Indexers both generate PropertyBuilders, we use this to share
6360 // their common bits.
6362 abstract public class PropertyBase : PropertyBasedMember {
6364 public class GetMethod : PropertyMethod
6366 static string[] attribute_targets = new string [] { "method", "return" };
6368 public GetMethod (PropertyBase method):
6369 base (method, "get_")
6373 public GetMethod (PropertyBase method, Accessor accessor):
6374 base (method, accessor, "get_")
6378 public override MethodBuilder Define (DeclSpace parent)
6380 if (!CheckForDuplications ())
6386 base.Define (parent);
6388 method_data = new MethodData (method, ModFlags, flags, this);
6390 if (!method_data.Define (parent))
6393 return method_data.MethodBuilder;
6396 public override Type ReturnType {
6398 return method.MemberType;
6402 public override Parameters ParameterInfo {
6404 return Parameters.EmptyReadOnlyParameters;
6408 public override string[] ValidAttributeTargets {
6410 return attribute_targets;
6415 public class SetMethod : PropertyMethod {
6417 static string[] attribute_targets = new string [] { "method", "param", "return" };
6418 ImplicitParameter param_attr;
6419 protected Parameters parameters;
6421 public SetMethod (PropertyBase method):
6422 base (method, "set_")
6426 public SetMethod (PropertyBase method, Accessor accessor):
6427 base (method, accessor, "set_")
6431 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6433 if (a.Target == AttributeTargets.Parameter) {
6434 if (param_attr == null)
6435 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6437 param_attr.ApplyAttributeBuilder (a, cb);
6441 base.ApplyAttributeBuilder (a, cb);
6444 public override Parameters ParameterInfo {
6446 if (parameters == null)
6447 DefineParameters ();
6452 protected virtual void DefineParameters ()
6454 parameters = Parameters.CreateFullyResolved (
6455 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6458 public override MethodBuilder Define (DeclSpace parent)
6460 if (!CheckForDuplications ())
6466 base.Define (parent);
6468 method_data = new MethodData (method, ModFlags, flags, this);
6470 if (!method_data.Define (parent))
6473 return method_data.MethodBuilder;
6476 public override Type ReturnType {
6478 return TypeManager.void_type;
6482 public override string[] ValidAttributeTargets {
6484 return attribute_targets;
6489 static string[] attribute_targets = new string [] { "property" };
6491 public abstract class PropertyMethod : AbstractPropertyEventMethod
6493 protected readonly PropertyBase method;
6494 protected MethodAttributes flags;
6496 ArrayList anonymous_methods;
6499 public PropertyMethod (PropertyBase method, string prefix)
6500 : base (method, prefix)
6502 this.method = method;
6505 public PropertyMethod (PropertyBase method, Accessor accessor,
6507 : base (method, accessor, prefix)
6509 this.method = method;
6510 this.ModFlags = accessor.ModFlags;
6511 yields = accessor.Yields;
6512 anonymous_methods = accessor.AnonymousMethods;
6514 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6515 Report.FeatureIsNotISO1 (Location, "access modifiers on properties");
6519 public override Iterator Iterator {
6520 get { return iterator; }
6523 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6525 if (a.IsInternalMethodImplAttribute) {
6526 method.is_external_implementation = true;
6529 base.ApplyAttributeBuilder (a, cb);
6532 public override AttributeTargets AttributeTargets {
6534 return AttributeTargets.Method;
6538 public override bool IsClsComplianceRequired ()
6540 return method.IsClsComplianceRequired ();
6543 public override bool ResolveMembers ()
6546 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6547 if (iterator == null)
6551 if (anonymous_methods != null) {
6552 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6553 if (!ame.CreateAnonymousHelpers ())
6561 public virtual MethodBuilder Define (DeclSpace parent)
6563 TypeContainer container = parent.PartialContainer;
6566 // Check for custom access modifier
6568 if ((ModFlags & Modifiers.Accessibility) == 0) {
6569 ModFlags |= method.ModFlags;
6570 flags = method.flags;
6572 if (container.Kind == Kind.Interface)
6573 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6574 GetSignatureForError ());
6576 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6577 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6580 CheckModifiers (ModFlags);
6581 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6582 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6583 flags = Modifiers.MethodAttr (ModFlags);
6584 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6587 CheckAbstractAndExtern (block != null);
6591 public bool HasCustomAccessModifier
6594 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6598 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6600 return new EmitContext (method,
6601 ds, method.ds, method.Location, ig, ReturnType,
6602 method.ModFlags, false);
6605 public override ObsoleteAttribute GetObsoleteAttribute ()
6607 return method.GetObsoleteAttribute ();
6610 public override string GetSignatureForError()
6612 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6615 void CheckModifiers (int modflags)
6617 modflags &= Modifiers.Accessibility;
6619 int mflags = method.ModFlags & Modifiers.Accessibility;
6621 if ((mflags & Modifiers.PUBLIC) != 0) {
6622 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6624 else if ((mflags & Modifiers.PROTECTED) != 0) {
6625 if ((mflags & Modifiers.INTERNAL) != 0)
6626 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6628 flags |= Modifiers.PRIVATE;
6630 else if ((mflags & Modifiers.INTERNAL) != 0)
6631 flags |= Modifiers.PRIVATE;
6633 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6634 Report.Error (273, Location,
6635 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6636 GetSignatureForError (), method.GetSignatureForError ());
6640 public override bool MarkForDuplicationCheck ()
6642 caching_flags |= Flags.TestMethodDuplication;
6646 protected bool CheckForDuplications ()
6648 if ((caching_flags & Flags.TestMethodDuplication) == 0)
6651 ArrayList ar = Parent.PartialContainer.Methods;
6653 int arLen = ar.Count;
6655 for (int i = 0; i < arLen; i++) {
6656 Method m = (Method) ar [i];
6657 if (IsDuplicateImplementation (m))
6666 public PropertyMethod Get, Set;
6667 public PropertyBuilder PropertyBuilder;
6668 public MethodBuilder GetBuilder, SetBuilder;
6670 protected bool define_set_first = false;
6672 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6673 int allowed_mod, bool is_iface, MemberName name,
6674 Attributes attrs, bool define_set_first)
6675 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6677 this.define_set_first = define_set_first;
6680 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6682 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6683 a.Error_InvalidSecurityParent ();
6687 PropertyBuilder.SetCustomAttribute (cb);
6690 public override AttributeTargets AttributeTargets {
6692 return AttributeTargets.Property;
6696 public override bool Define ()
6701 if (!IsTypePermitted ())
6707 protected override bool DoDefine ()
6709 if (!base.DoDefine ())
6713 // Accessors modifiers check
6715 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6716 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6717 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6718 GetSignatureForError ());
6722 if ((Get.IsDummy || Set.IsDummy)
6723 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6724 Report.Error (276, Location,
6725 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6726 GetSignatureForError ());
6731 if (MemberType.IsGenericParameter)
6735 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6736 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6745 GetBuilder = Get.Define (Parent);
6746 return (Get.IsDummy) ? true : GetBuilder != null;
6749 bool DefineSet (bool define)
6754 SetBuilder = Set.Define (Parent);
6755 return (Set.IsDummy) ? true : SetBuilder != null;
6758 protected bool DefineAccessors ()
6760 return DefineSet (define_set_first) &&
6762 DefineSet (!define_set_first);
6765 protected abstract PropertyInfo ResolveBaseProperty ();
6767 // TODO: rename to Resolve......
6768 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6770 PropertyInfo base_property = ResolveBaseProperty ();
6771 if (base_property == null)
6774 base_ret_type = base_property.PropertyType;
6775 MethodInfo get_accessor = base_property.GetGetMethod (true);
6776 MethodInfo set_accessor = base_property.GetSetMethod (true);
6777 MethodAttributes get_accessor_access, set_accessor_access;
6779 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6780 if (Get != null && !Get.IsDummy && get_accessor == null) {
6781 Report.SymbolRelatedToPreviousError (base_property);
6782 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6785 if (Set != null && !Set.IsDummy && set_accessor == null) {
6786 Report.SymbolRelatedToPreviousError (base_property);
6787 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6792 // Check base class accessors access
6795 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6796 get_accessor_access = set_accessor_access = 0;
6797 if ((ModFlags & Modifiers.NEW) == 0) {
6798 if (get_accessor != null) {
6799 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6800 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6802 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6803 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6806 if (set_accessor != null) {
6807 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6808 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6810 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6811 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6815 // When one accessor does not exist and property hides base one
6816 // we need to propagate this upwards
6817 if (set_accessor == null)
6818 set_accessor = get_accessor;
6821 // Get the less restrictive access
6823 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6826 public override void Emit ()
6829 // The PropertyBuilder can be null for explicit implementations, in that
6830 // case, we do not actually emit the ".property", so there is nowhere to
6831 // put the attribute
6833 if (PropertyBuilder != null && OptAttributes != null)
6834 OptAttributes.Emit ();
6846 /// Tests whether accessors are not in collision with some method (CS0111)
6848 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6850 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6853 public override bool IsUsed
6859 return Get.IsUsed | Set.IsUsed;
6863 protected override void SetMemberName (MemberName new_name)
6865 base.SetMemberName (new_name);
6867 Get.UpdateName (this);
6868 Set.UpdateName (this);
6871 public override string[] ValidAttributeTargets {
6873 return attribute_targets;
6878 // Represents header string for documentation comment.
6880 public override string DocCommentHeader {
6881 get { return "P:"; }
6885 public class Property : PropertyBase {
6886 const int AllowedModifiers =
6889 Modifiers.PROTECTED |
6890 Modifiers.INTERNAL |
6894 Modifiers.OVERRIDE |
6895 Modifiers.ABSTRACT |
6898 Modifiers.METHOD_YIELDS |
6901 const int AllowedInterfaceModifiers =
6904 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6907 Field field = new Field (
6909 Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & Modifiers.STATIC),
6910 CompilerGeneratedClass.MakeName (null, "CompilerGeneratedField"),
6912 ((TypeContainer)Parent).AddField (field);
6915 get_block.Block = new ToplevelBlock (block, null, Location);
6916 Return r = new Return (new SimpleName(field.Name, Location), Location);
6917 get_block.Block.AddStatement (r);
6918 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6921 Parameters parameters = new Parameters (new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location));
6922 set_block.Block = new ToplevelBlock (block, parameters, Location);
6923 Assign a = new Assign (new SimpleName(field.Name, Location), new SimpleName ("value", Location));
6924 set_block.Block.AddStatement (new StatementExpression(a));
6925 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6928 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6929 MemberName name, Attributes attrs, Accessor get_block,
6930 Accessor set_block, bool define_set_first)
6931 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6932 define_set_first, null)
6936 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6937 MemberName name, Attributes attrs, Accessor get_block,
6938 Accessor set_block, bool define_set_first, Block current_block)
6939 : base (parent, type, mod,
6940 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6941 is_iface, name, attrs, define_set_first)
6943 if (RootContext.Version >= LanguageVersion.LINQ &&
6945 (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6946 get_block != null && get_block.Block == null &&
6947 set_block != null && set_block.Block == null)
6948 CreateAutomaticProperty (current_block, get_block, set_block);
6950 if (get_block == null)
6951 Get = new GetMethod (this);
6953 Get = new GetMethod (this, get_block);
6955 if (set_block == null)
6956 Set = new SetMethod (this);
6958 Set = new SetMethod (this, set_block);
6961 public override bool Define ()
6963 if (!DoDefineBase ())
6966 if (!base.Define ())
6972 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6974 if (!DefineAccessors ())
6977 // FIXME - PropertyAttributes.HasDefault ?
6979 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6980 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6983 PropertyBuilder.SetGetMethod (GetBuilder);
6986 PropertyBuilder.SetSetMethod (SetBuilder);
6988 TypeManager.RegisterProperty (PropertyBuilder, this);
6992 protected override PropertyInfo ResolveBaseProperty ()
6994 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6995 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
7000 /// Gigantic workaround for lameness in SRE follows :
7001 /// This class derives from EventInfo and attempts to basically
7002 /// wrap around the EventBuilder so that FindMembers can quickly
7003 /// return this in it search for members
7005 public class MyEventBuilder : EventInfo {
7008 // We use this to "point" to our Builder which is
7009 // not really a MemberInfo
7011 EventBuilder MyBuilder;
7014 // We "catch" and wrap these methods
7016 MethodInfo raise, remove, add;
7018 EventAttributes attributes;
7019 Type declaring_type, reflected_type, event_type;
7024 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7026 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7028 // And now store the values in our own fields.
7030 declaring_type = type_builder;
7032 reflected_type = type_builder;
7034 attributes = event_attr;
7037 this.event_type = event_type;
7041 // Methods that you have to override. Note that you only need
7042 // to "implement" the variants that take the argument (those are
7043 // the "abstract" methods, the others (GetAddMethod()) are
7046 public override MethodInfo GetAddMethod (bool nonPublic)
7051 public override MethodInfo GetRemoveMethod (bool nonPublic)
7056 public override MethodInfo GetRaiseMethod (bool nonPublic)
7062 // These methods make "MyEventInfo" look like a Builder
7064 public void SetRaiseMethod (MethodBuilder raiseMethod)
7066 raise = raiseMethod;
7067 MyBuilder.SetRaiseMethod (raiseMethod);
7070 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7072 remove = removeMethod;
7073 MyBuilder.SetRemoveOnMethod (removeMethod);
7076 public void SetAddOnMethod (MethodBuilder addMethod)
7079 MyBuilder.SetAddOnMethod (addMethod);
7082 public void SetCustomAttribute (CustomAttributeBuilder cb)
7084 MyBuilder.SetCustomAttribute (cb);
7087 public override object [] GetCustomAttributes (bool inherit)
7089 // FIXME : There's nothing which can be seemingly done here because
7090 // we have no way of getting at the custom attribute objects of the
7095 public override object [] GetCustomAttributes (Type t, bool inherit)
7097 // FIXME : Same here !
7101 public override bool IsDefined (Type t, bool b)
7106 public override EventAttributes Attributes {
7112 public override string Name {
7118 public override Type DeclaringType {
7120 return declaring_type;
7124 public override Type ReflectedType {
7126 return reflected_type;
7130 public Type EventType {
7136 public void SetUsed ()
7138 if (my_event != null) {
7139 // my_event.SetAssigned ();
7140 my_event.SetMemberIsUsed ();
7146 /// For case when event is declared like property (with add and remove accessors).
7148 public class EventProperty: Event {
7149 abstract class AEventPropertyAccessor : AEventAccessor
7151 readonly ArrayList anonymous_methods;
7153 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7154 base (method, accessor, prefix)
7156 this.anonymous_methods = accessor.AnonymousMethods;
7159 public override MethodBuilder Define (DeclSpace ds)
7161 CheckAbstractAndExtern (block != null);
7162 return base.Define (ds);
7165 public override string GetSignatureForError ()
7167 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7170 public override bool ResolveMembers ()
7172 if (anonymous_methods == null)
7175 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7176 if (!ame.CreateAnonymousHelpers ())
7185 sealed class AddDelegateMethod: AEventPropertyAccessor
7187 public AddDelegateMethod (Event method, Accessor accessor):
7188 base (method, accessor, "add_")
7192 protected override MethodInfo DelegateMethodInfo {
7194 return TypeManager.delegate_combine_delegate_delegate;
7199 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7201 public RemoveDelegateMethod (Event method, Accessor accessor):
7202 base (method, accessor, "remove_")
7206 protected override MethodInfo DelegateMethodInfo {
7208 return TypeManager.delegate_remove_delegate_delegate;
7214 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7216 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
7217 bool is_iface, MemberName name,
7218 Attributes attrs, Accessor add, Accessor remove)
7219 : base (parent, type, mod_flags, is_iface, name, attrs)
7221 Add = new AddDelegateMethod (this, add);
7222 Remove = new RemoveDelegateMethod (this, remove);
7225 public override bool Define()
7227 if (!base.Define ())
7236 public override string[] ValidAttributeTargets {
7238 return attribute_targets;
7244 /// Event is declared like field.
7246 public class EventField : Event {
7247 abstract class EventFieldAccessor : AEventAccessor
7249 protected EventFieldAccessor (Event method, string prefix)
7250 : base (method, prefix)
7254 protected override void EmitMethod(DeclSpace parent)
7256 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7259 MethodBuilder mb = method_data.MethodBuilder;
7260 ILGenerator ig = mb.GetILGenerator ();
7262 // TODO: because we cannot use generics yet
7263 FieldInfo field_info = ((EventField)method).FieldBuilder;
7265 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7266 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7267 ig.Emit (OpCodes.Ldsfld, field_info);
7268 ig.Emit (OpCodes.Ldarg_0);
7269 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7270 ig.Emit (OpCodes.Castclass, method.MemberType);
7271 ig.Emit (OpCodes.Stsfld, field_info);
7273 ig.Emit (OpCodes.Ldarg_0);
7274 ig.Emit (OpCodes.Ldarg_0);
7275 ig.Emit (OpCodes.Ldfld, field_info);
7276 ig.Emit (OpCodes.Ldarg_1);
7277 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7278 ig.Emit (OpCodes.Castclass, method.MemberType);
7279 ig.Emit (OpCodes.Stfld, field_info);
7281 ig.Emit (OpCodes.Ret);
7285 sealed class AddDelegateMethod: EventFieldAccessor
7287 public AddDelegateMethod (Event method):
7288 base (method, "add_")
7292 protected override MethodInfo DelegateMethodInfo {
7294 return TypeManager.delegate_combine_delegate_delegate;
7299 sealed class RemoveDelegateMethod: EventFieldAccessor
7301 public RemoveDelegateMethod (Event method):
7302 base (method, "remove_")
7306 protected override MethodInfo DelegateMethodInfo {
7308 return TypeManager.delegate_remove_delegate_delegate;
7314 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7315 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7317 public FieldBuilder FieldBuilder;
7318 public Expression Initializer;
7320 public EventField (DeclSpace parent, Expression type, int mod_flags,
7321 bool is_iface, MemberName name,
7323 : base (parent, type, mod_flags, is_iface, name, attrs)
7325 Add = new AddDelegateMethod (this);
7326 Remove = new RemoveDelegateMethod (this);
7329 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7331 if (a.Target == AttributeTargets.Field) {
7332 FieldBuilder.SetCustomAttribute (cb);
7336 if (a.Target == AttributeTargets.Method) {
7337 int errors = Report.Errors;
7338 Add.ApplyAttributeBuilder (a, cb);
7339 if (errors == Report.Errors)
7340 Remove.ApplyAttributeBuilder (a, cb);
7344 base.ApplyAttributeBuilder (a, cb);
7347 public override bool Define()
7349 if (!base.Define ())
7355 // FIXME: We are unable to detect whether generic event is used because
7356 // we are using FieldExpr instead of EventExpr for event access in that
7357 // case. When this issue will be fixed this hack can be removed.
7358 if (TypeManager.IsGenericType (MemberType))
7361 FieldBuilder = Parent.TypeBuilder.DefineField (
7363 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7364 TypeManager.RegisterEventField (EventBuilder, this);
7366 if (Initializer != null) {
7367 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7368 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7369 GetSignatureForError ());
7373 Parent.PartialContainer.RegisterFieldForInitialization (this,
7374 new FieldInitializer (FieldBuilder, Initializer, Parent));
7380 public override string[] ValidAttributeTargets
7383 return IsInterface ? attribute_targets_interface : attribute_targets;
7388 public abstract class Event : PropertyBasedMember {
7389 public abstract class AEventAccessor : AbstractPropertyEventMethod
7391 protected readonly Event method;
7392 ImplicitParameter param_attr;
7394 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7396 protected AEventAccessor (Event method, string prefix)
7397 : base (method, prefix)
7399 this.method = method;
7400 this.ModFlags = method.ModFlags;
7403 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7404 : base (method, accessor, prefix)
7406 this.method = method;
7407 this.ModFlags = method.ModFlags;
7410 public override Iterator Iterator {
7411 get { return null; }
7414 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7416 if (a.IsInternalMethodImplAttribute) {
7417 method.is_external_implementation = true;
7420 base.ApplyAttributeBuilder (a, cb);
7423 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7425 if (a.Target == AttributeTargets.Parameter) {
7426 if (param_attr == null)
7427 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7429 param_attr.ApplyAttributeBuilder (a, cb);
7433 base.ApplyAttributeBuilder (a, cb);
7436 public override AttributeTargets AttributeTargets {
7438 return AttributeTargets.Method;
7442 public override bool IsClsComplianceRequired ()
7444 return method.IsClsComplianceRequired ();
7447 public virtual MethodBuilder Define (DeclSpace parent)
7449 method_data = new MethodData (method, method.ModFlags,
7450 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7452 if (!method_data.Define (parent))
7455 MethodBuilder mb = method_data.MethodBuilder;
7456 ParameterInfo.ApplyAttributes (mb);
7460 protected abstract MethodInfo DelegateMethodInfo { get; }
7462 public override Type ReturnType {
7464 return TypeManager.void_type;
7468 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7470 return new EmitContext (
7471 ds, method.Parent, Location, ig, ReturnType,
7472 method.ModFlags, false);
7475 public override ObsoleteAttribute GetObsoleteAttribute ()
7477 return method.GetObsoleteAttribute ();
7480 public override string[] ValidAttributeTargets {
7482 return attribute_targets;
7486 public override Parameters ParameterInfo {
7488 return method.parameters;
7494 const int AllowedModifiers =
7497 Modifiers.PROTECTED |
7498 Modifiers.INTERNAL |
7503 Modifiers.OVERRIDE |
7505 Modifiers.ABSTRACT |
7508 const int AllowedInterfaceModifiers =
7511 public AEventAccessor Add, Remove;
7512 public MyEventBuilder EventBuilder;
7513 public MethodBuilder AddBuilder, RemoveBuilder;
7515 Parameters parameters;
7517 protected Event (DeclSpace parent, Expression type, int mod_flags,
7518 bool is_iface, MemberName name, Attributes attrs)
7519 : base (parent, null, type, mod_flags,
7520 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7525 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7527 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7528 a.Error_InvalidSecurityParent ();
7532 EventBuilder.SetCustomAttribute (cb);
7535 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7537 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7540 public override AttributeTargets AttributeTargets {
7542 return AttributeTargets.Event;
7546 public override bool Define ()
7548 if (!DoDefineBase ())
7554 if (!TypeManager.IsDelegateType (MemberType)) {
7555 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7559 parameters = Parameters.CreateFullyResolved (
7560 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7566 // Now define the accessors
7569 AddBuilder = Add.Define (Parent);
7570 if (AddBuilder == null)
7573 RemoveBuilder = Remove.Define (Parent);
7574 if (RemoveBuilder == null)
7577 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7578 EventBuilder.SetAddOnMethod (AddBuilder);
7579 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7583 public override void Emit ()
7585 if (OptAttributes != null) {
7586 OptAttributes.Emit ();
7590 Remove.Emit (Parent);
7595 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7597 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7598 Parent.TypeBuilder, Name);
7603 ParameterData pd = TypeManager.GetParameterData (mi);
7604 base_ret_type = pd.ParameterType (0);
7609 // Represents header string for documentation comment.
7611 public override string DocCommentHeader {
7612 get { return "E:"; }
7617 public class Indexer : PropertyBase {
7619 class GetIndexerMethod : GetMethod
7621 public GetIndexerMethod (PropertyBase method):
7626 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7627 base (method, accessor)
7631 public override Parameters ParameterInfo {
7633 return ((Indexer)method).parameters;
7638 class SetIndexerMethod: SetMethod
7640 public SetIndexerMethod (PropertyBase method):
7645 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7646 base (method, accessor)
7650 protected override void DefineParameters ()
7652 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7653 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7657 const int AllowedModifiers =
7660 Modifiers.PROTECTED |
7661 Modifiers.INTERNAL |
7665 Modifiers.OVERRIDE |
7670 const int AllowedInterfaceModifiers =
7673 public readonly Parameters parameters;
7675 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7676 bool is_iface, Parameters parameters, Attributes attrs,
7677 Accessor get_block, Accessor set_block, bool define_set_first)
7678 : base (parent, type, mod,
7679 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7680 is_iface, name, attrs, define_set_first)
7682 if (type == TypeManager.system_void_expr)
7683 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7685 this.parameters = parameters;
7687 if (get_block == null)
7688 Get = new GetIndexerMethod (this);
7690 Get = new GetIndexerMethod (this, get_block);
7692 if (set_block == null)
7693 Set = new SetIndexerMethod (this);
7695 Set = new SetIndexerMethod (this, set_block);
7698 protected override bool CheckForDuplications ()
7700 ArrayList ar = Parent.PartialContainer.Indexers;
7702 int arLen = ar.Count;
7704 for (int i = 0; i < arLen; i++) {
7705 Indexer m = (Indexer) ar [i];
7706 if (IsDuplicateImplementation (m))
7714 bool IsDuplicateImplementation (Indexer indexer)
7716 if (this == indexer)
7719 if (!MemberName.Equals (indexer.MemberName))
7722 Type[] param_types = indexer.parameters.Types;
7724 // When it is not yet defined
7725 if (param_types == null)
7728 if (param_types.Length != parameters.Count)
7731 for (int i = 0; i < param_types.Length; i++)
7732 if (param_types [i] != parameters.Types [i])
7735 Report.SymbolRelatedToPreviousError (indexer);
7736 Report.Error (111, Location, TypeContainer.Error111, indexer.GetSignatureForError ());
7741 public override bool Define ()
7743 if (!DoDefineBase ())
7746 if (!base.Define ())
7749 if (!DefineParameters (parameters))
7752 if (OptAttributes != null) {
7753 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7754 if (indexer_attr != null) {
7755 // Remove the attribute from the list because it is not emitted
7756 OptAttributes.Attrs.Remove (indexer_attr);
7758 string name = indexer_attr.GetIndexerAttributeValue ();
7764 if (IsExplicitImpl) {
7765 Report.Error (415, indexer_attr.Location,
7766 "The `IndexerName' attribute is valid only on an " +
7767 "indexer that is not an explicit interface member declaration");
7771 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7772 Report.Error (609, indexer_attr.Location,
7773 "Cannot set the `IndexerName' attribute on an indexer marked override");
7779 if (InterfaceType != null) {
7780 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7781 if (base_IndexerName != Name)
7782 ShortName = base_IndexerName;
7785 if (!Parent.PartialContainer.AddMember (this) ||
7786 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7792 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7794 if (!DefineAccessors ())
7798 // Setup iterator if we are one
7799 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7800 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7801 if (iterator == null)
7807 // Now name the parameters
7809 Parameter [] p = parameters.FixedParameters;
7811 // TODO: should be done in parser and it needs to do cycle
7812 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7813 CSharpParser.Error_ParameterModifierNotValid (Location);
7818 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7819 Name, PropertyAttributes.None, MemberType, parameters.Types);
7822 PropertyBuilder.SetGetMethod (GetBuilder);
7825 PropertyBuilder.SetSetMethod (SetBuilder);
7827 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7832 public override string GetDocCommentName (DeclSpace ds)
7834 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7837 public override string GetSignatureForError ()
7839 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7840 if (MemberName.Left != null) {
7842 sb.Append (MemberName.Left);
7845 sb.Append (".this");
7846 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7847 return sb.ToString ();
7850 public override bool MarkForDuplicationCheck ()
7852 caching_flags |= Flags.TestMethodDuplication;
7856 protected override PropertyInfo ResolveBaseProperty ()
7858 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7859 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7862 protected override bool VerifyClsCompliance ()
7864 if (!base.VerifyClsCompliance ())
7867 parameters.VerifyClsCompliance ();
7872 public class Operator : MethodOrOperator, IAnonymousHost {
7874 const int AllowedModifiers =
7880 public enum OpType : byte {
7890 // Unary and Binary operators
7913 // Implicit and Explicit
7917 // Just because of enum
7921 public readonly OpType OperatorType;
7923 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7924 int mod_flags, Parameters parameters,
7925 ToplevelBlock block, Attributes attrs, Location loc)
7926 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7927 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7929 OperatorType = type;
7933 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7935 if (a.Type == TypeManager.conditional_attribute_type) {
7936 Error_ConditionalAttributeIsNotValid ();
7940 base.ApplyAttributeBuilder (a, cb);
7943 protected override bool CheckForDuplications ()
7945 ArrayList ar = Parent.PartialContainer.Operators;
7947 int arLen = ar.Count;
7949 for (int i = 0; i < arLen; i++) {
7950 Operator o = (Operator) ar [i];
7951 if (IsDuplicateImplementation (o))
7956 ar = Parent.PartialContainer.Methods;
7958 int arLen = ar.Count;
7960 for (int i = 0; i < arLen; i++) {
7961 Method m = (Method) ar [i];
7962 if (IsDuplicateImplementation (m))
7970 public override bool Define ()
7972 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7973 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7974 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7978 // imlicit and explicit operator of same types are not allowed
7979 if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
7980 MarkForDuplicationCheck ();
7982 if (!base.Define ())
7985 if (MemberType == TypeManager.void_type) {
7986 Report.Error (590, Location, "User-defined operators cannot return void");
7990 Type declaring_type = MethodData.DeclaringType;
7991 Type return_type = MemberType;
7992 Type first_arg_type = ParameterTypes [0];
7994 // Rules for conversion operators
7996 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7997 if (first_arg_type == return_type && first_arg_type == declaring_type){
7998 Report.Error (555, Location,
7999 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
8003 if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
8004 !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
8005 !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
8008 "User-defined conversion must convert to or from the " +
8013 if (first_arg_type.IsInterface || return_type.IsInterface){
8014 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8015 GetSignatureForError ());
8019 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
8020 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
8021 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
8022 GetSignatureForError ());
8025 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
8026 GetSignatureForError ());
8029 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8030 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8031 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");
8034 } else if (Parameters.Count == 1) {
8035 // Checks for Unary operators
8037 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8038 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8039 Report.Error (448, Location,
8040 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8043 if (first_arg_type != declaring_type) {
8045 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8050 if (first_arg_type != declaring_type){
8053 "The parameter of a unary operator must be the " +
8058 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8059 if (return_type != TypeManager.bool_type){
8062 "The return type of operator True or False " +
8069 // Checks for Binary operators
8071 if (first_arg_type != declaring_type &&
8072 ParameterTypes [1] != declaring_type){
8075 "One of the parameters of a binary operator must " +
8076 "be the containing type");
8084 protected override bool DoDefine ()
8086 if (!base.DoDefine ())
8089 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8093 public override void Emit ()
8097 Parameters.ApplyAttributes (MethodBuilder);
8100 // abstract or extern methods have no bodies
8102 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8106 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8107 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8109 ec = CreateEmitContext (Parent, null);
8111 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8112 ec.EmitTopBlock (this, Block);
8115 source.CloseMethod ();
8120 // Operator cannot be override
8121 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8126 public static string GetName (OpType ot)
8129 case OpType.LogicalNot:
8131 case OpType.OnesComplement:
8133 case OpType.Increment:
8135 case OpType.Decrement:
8141 case OpType.Addition:
8143 case OpType.Subtraction:
8145 case OpType.UnaryPlus:
8147 case OpType.UnaryNegation:
8149 case OpType.Multiply:
8151 case OpType.Division:
8153 case OpType.Modulus:
8155 case OpType.BitwiseAnd:
8157 case OpType.BitwiseOr:
8159 case OpType.ExclusiveOr:
8161 case OpType.LeftShift:
8163 case OpType.RightShift:
8165 case OpType.Equality:
8167 case OpType.Inequality:
8169 case OpType.GreaterThan:
8171 case OpType.LessThan:
8173 case OpType.GreaterThanOrEqual:
8175 case OpType.LessThanOrEqual:
8177 case OpType.Implicit:
8179 case OpType.Explicit:
8185 public static OpType GetOperatorType (string name)
8187 if (name.StartsWith ("op_")){
8188 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8189 if (Unary.oper_names [i] == name)
8193 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8194 if (Binary.oper_names [i] == name)
8201 public override string GetSignatureForError ()
8203 StringBuilder sb = new StringBuilder ();
8204 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8205 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8208 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8211 sb.Append (Parameters.GetSignatureForError ());
8212 return sb.ToString ();
8217 // This is used to compare method signatures
8219 struct MethodSignature {
8221 public Type RetType;
8222 public Type [] Parameters;
8225 /// This delegate is used to extract methods which have the
8226 /// same signature as the argument
8228 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8230 public MethodSignature (string name, Type ret_type, Type [] parameters)
8235 if (parameters == null)
8236 Parameters = Type.EmptyTypes;
8238 Parameters = parameters;
8241 public override string ToString ()
8244 if (Parameters.Length != 0){
8245 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8246 for (int i = 0; i < Parameters.Length; i++){
8247 sb.Append (Parameters [i]);
8248 if (i+1 < Parameters.Length)
8251 pars = sb.ToString ();
8254 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8257 public override int GetHashCode ()
8259 return Name.GetHashCode ();
8262 public override bool Equals (Object o)
8264 MethodSignature other = (MethodSignature) o;
8266 if (other.Name != Name)
8269 if (other.RetType != RetType)
8272 if (Parameters == null){
8273 if (other.Parameters == null)
8278 if (other.Parameters == null)
8281 int c = Parameters.Length;
8282 if (other.Parameters.Length != c)
8285 for (int i = 0; i < c; i++)
8286 if (other.Parameters [i] != Parameters [i])
8292 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8294 MethodSignature sig = (MethodSignature) filter_criteria;
8296 if (m.Name != sig.Name)
8300 MethodInfo mi = m as MethodInfo;
8301 PropertyInfo pi = m as PropertyInfo;
8304 ReturnType = mi.ReturnType;
8305 else if (pi != null)
8306 ReturnType = pi.PropertyType;
8311 // we use sig.RetType == null to mean `do not check the
8312 // method return value.
8314 if (sig.RetType != null)
8315 if (ReturnType != sig.RetType)
8320 args = TypeManager.GetParameterData (mi).Types;
8322 args = TypeManager.GetArgumentTypes (pi);
8323 Type [] sigp = sig.Parameters;
8325 if (args.Length != sigp.Length)
8328 for (int i = args.Length; i > 0; ){
8330 if (args [i] != sigp [i])