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 ();
270 GetHashCode = 1 << 1,
271 HasStaticFieldInitializer = 1 << 2
275 // Whether this is a struct, class or interface
276 public readonly Kind Kind;
278 // Holds a list of classes and structures
279 protected ArrayList types;
281 MemberCoreArrayList ordered_explicit_member_list;
282 MemberCoreArrayList ordered_member_list;
284 // Holds the list of properties
285 MemberCoreArrayList properties;
287 // Holds the list of delegates
288 MemberCoreArrayList delegates;
290 // Holds the list of constructors
291 protected MemberCoreArrayList instance_constructors;
293 // Holds the list of fields
294 MemberCoreArrayList fields;
296 // Holds a list of fields that have initializers
297 protected ArrayList initialized_fields;
299 // Holds a list of static fields that have initializers
300 protected ArrayList initialized_static_fields;
302 // Holds the list of constants
303 MemberCoreArrayList constants;
305 // Holds the methods.
306 MemberCoreArrayList methods;
309 protected MemberCoreArrayList events;
311 // Holds the indexers
314 // Holds the operators
315 MemberCoreArrayList operators;
317 // Holds the compiler generated classes
318 ArrayList compiler_generated;
321 // Pointers to the default constructor and the default static constructor
323 protected Constructor default_constructor;
324 protected Constructor default_static_constructor;
327 // Points to the first non-static field added to the container.
329 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
330 // and the first one's as good as any.
332 FieldBase first_nonstatic_field = null;
335 // This one is computed after we can distinguish interfaces
336 // from classes from the arraylist `type_bases'
339 TypeExpr[] iface_exprs;
342 ArrayList type_bases;
344 bool members_resolved;
345 bool members_resolved_ok;
346 bool members_defined;
347 bool members_defined_ok;
349 // The interfaces we implement.
350 protected Type[] ifaces;
352 // The base member cache and our member cache
353 MemberCache base_cache;
354 MemberCache member_cache;
356 public const string DefaultIndexerName = "Item";
358 private bool seen_normal_indexers = false;
359 private string indexer_name = DefaultIndexerName;
361 private CachedMethods cached_method;
364 GenericTypeParameterBuilder[] gen_params;
367 ArrayList partial_parts;
370 /// The pending methods that need to be implemented
371 // (interfaces or abstract methods)
373 PendingImplementation pending;
375 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
376 Attributes attrs, Kind kind)
377 : base (ns, parent, name, attrs)
379 if (parent != null && parent.NamespaceEntry != ns)
380 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
383 this.PartialContainer = this;
386 public bool AddMember (MemberCore symbol)
388 return AddToContainer (symbol, symbol.MemberName.MethodName);
391 protected virtual bool AddMemberType (DeclSpace ds)
393 return AddToContainer (ds, ds.Basename);
396 public void AddConstant (Const constant)
398 if (!AddMember (constant))
401 if (constants == null)
402 constants = new MemberCoreArrayList ();
404 constants.Add (constant);
407 public TypeContainer AddTypeContainer (TypeContainer tc)
409 if (!AddMemberType (tc))
413 types = new MemberCoreArrayList ();
419 public virtual TypeContainer AddPartial (TypeContainer next_part)
421 return AddPartial (next_part, next_part.Basename);
424 protected TypeContainer AddPartial (TypeContainer next_part, string name)
426 next_part.ModFlags |= Modifiers.PARTIAL;
427 TypeContainer tc = defined_names [name] as TypeContainer;
430 return AddTypeContainer (next_part);
432 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
433 Report.SymbolRelatedToPreviousError (tc);
434 Error_MissingPartialModifier (next_part);
437 if (tc.Kind != next_part.Kind) {
438 Report.SymbolRelatedToPreviousError (tc);
439 Report.Error (261, next_part.Location,
440 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
441 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 ());
453 if (tc.MemberName.IsGeneric) {
454 TypeParameter[] tc_names = tc.TypeParameters;
455 TypeParameterName[] part_names = next_part.MemberName.TypeArguments.GetDeclarations ();
457 for (int i = 0; i < tc_names.Length; ++i) {
458 if (tc_names[i].Name == part_names[i].Name)
461 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
462 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
463 tc.GetSignatureForError ());
467 if (tc.partial_parts == null)
468 tc.partial_parts = new ArrayList (1);
470 if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
471 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
472 } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
473 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
474 tc.ModFlags |= next_part.ModFlags;
476 tc.ModFlags |= next_part.ModFlags;
479 if (next_part.attributes != null) {
480 if (tc.attributes == null)
481 tc.attributes = next_part.attributes;
483 tc.attributes.AddAttributes (next_part.attributes.Attrs);
486 next_part.PartialContainer = tc;
487 tc.partial_parts.Add (next_part);
491 public void AddDelegate (Delegate d)
493 if (!AddMemberType (d))
496 if (delegates == null)
497 delegates = new MemberCoreArrayList ();
502 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
504 if (ordered_explicit_member_list == null) {
505 ordered_explicit_member_list = new MemberCoreArrayList ();
506 ordered_member_list = new MemberCoreArrayList ();
510 ordered_explicit_member_list.Add (mc);
511 alist.Insert (0, mc);
514 ordered_member_list.Add (mc);
520 public void AddMethod (Method method)
522 if (!AddMember (method))
526 methods = new MemberCoreArrayList ();
528 if (method.MemberName.Left != null)
529 AddMemberToList (method, methods, true);
531 AddMemberToList (method, methods, false);
535 // Do not use this method: use AddMethod.
537 // This is only used by iterators.
539 public void AppendMethod (Method method)
541 if (!AddMember (method))
545 methods = new MemberCoreArrayList ();
547 AddMemberToList (method, methods, false);
550 public void AddConstructor (Constructor c)
552 if (c.Name != MemberName.Name) {
553 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
556 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
559 if (default_static_constructor != null) {
560 Report.SymbolRelatedToPreviousError (default_static_constructor);
561 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
565 default_static_constructor = c;
567 if (c.Parameters.Empty){
568 if (default_constructor != null) {
569 Report.SymbolRelatedToPreviousError (default_constructor);
570 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
573 default_constructor = c;
576 if (instance_constructors == null)
577 instance_constructors = new MemberCoreArrayList ();
579 instance_constructors.Add (c);
583 internal static string Error111 {
585 return "`{0}' is already defined. Rename this member or use different parameter types";
589 public bool AddField (FieldBase field)
591 if (!AddMember (field))
595 fields = new MemberCoreArrayList ();
599 if ((field.ModFlags & Modifiers.STATIC) != 0)
602 if (first_nonstatic_field == null) {
603 first_nonstatic_field = field;
607 if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
608 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
609 Report.Warning (282, 3, field.Location,
610 "struct instance field `{0}' found in different declaration from instance field `{1}'",
611 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
616 public void AddProperty (Property prop)
618 if (!AddMember (prop) ||
619 !AddMember (prop.Get) || !AddMember (prop.Set))
622 if (properties == null)
623 properties = new MemberCoreArrayList ();
625 if (prop.MemberName.Left != null)
626 AddMemberToList (prop, properties, true);
628 AddMemberToList (prop, properties, false);
631 public void AddEvent (Event e)
636 if (e is EventProperty) {
637 if (!AddMember (e.Add))
640 if (!AddMember (e.Remove))
645 events = new MemberCoreArrayList ();
651 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
653 public void AddIndexer (Indexer i)
655 if (indexers == null)
656 indexers = new ArrayList ();
658 if (i.IsExplicitImpl)
659 AddMemberToList (i, indexers, true);
661 AddMemberToList (i, indexers, false);
664 public void AddOperator (Operator op)
669 if (operators == null)
670 operators = new OperatorArrayList (this);
675 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
677 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
679 if (compiler_generated == null)
680 compiler_generated = new ArrayList ();
682 compiler_generated.Add (c);
685 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
687 if (a.Type == TypeManager.default_member_type) {
688 if (Indexers != null) {
689 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
694 base.ApplyAttributeBuilder (a, cb);
697 public override AttributeTargets AttributeTargets {
699 throw new NotSupportedException ();
703 public ArrayList Types {
709 public MemberCoreArrayList Methods {
715 public ArrayList Constants {
721 public ArrayList CompilerGenerated {
723 return compiler_generated;
727 protected Type BaseType {
729 return TypeBuilder.BaseType;
733 public ArrayList Bases {
743 public ArrayList Fields {
749 public ArrayList InstanceConstructors {
751 return instance_constructors;
755 public ArrayList Properties {
761 public ArrayList Events {
767 public ArrayList Indexers {
773 public ArrayList Operators {
779 public ArrayList Delegates {
785 protected override TypeAttributes TypeAttr {
787 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
791 public string IndexerName {
793 return indexers == null ? DefaultIndexerName : indexer_name;
797 public bool IsComImport {
799 if (OptAttributes == null)
802 return OptAttributes.Contains (TypeManager.comimport_attr_type);
806 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
808 if ((field.ModFlags & Modifiers.STATIC) != 0){
809 if (initialized_static_fields == null) {
810 PartialContainer.HasStaticFieldInitializer = true;
811 initialized_static_fields = new ArrayList (4);
814 initialized_static_fields.Add (expression);
816 if (initialized_fields == null)
817 initialized_fields = new ArrayList (4);
819 initialized_fields.Add (expression);
823 public void ResolveFieldInitializers (EmitContext ec)
825 // Field initializers are tricky for partial classes. They have to
826 // share same costructor (block) but they have they own resolve scope.
827 DeclSpace orig = ec.DeclContainer;
829 if (partial_parts != null) {
830 foreach (TypeContainer part in partial_parts) {
831 ec.DeclContainer = part;
832 part.DoResolveFieldInitializers (ec);
835 ec.DeclContainer = PartialContainer;
836 DoResolveFieldInitializers (ec);
837 ec.DeclContainer = orig;
840 void DoResolveFieldInitializers (EmitContext ec)
843 if (initialized_static_fields == null)
846 bool has_complex_initializer = false;
847 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
848 foreach (FieldInitializer fi in initialized_static_fields) {
849 fi.ResolveStatement (ec);
850 if (!fi.IsComplexInitializer)
853 has_complex_initializer = true;
856 // Need special check to not optimize code like this
857 // static int a = b = 5;
859 if (!has_complex_initializer && RootContext.Optimize) {
860 for (int i = 0; i < initialized_static_fields.Count; ++i) {
861 FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
862 if (fi.IsDefaultInitializer) {
863 initialized_static_fields.RemoveAt (i);
873 if (initialized_fields == null)
876 using (ec.Set (EmitContext.Flags.InFieldInitializer)) {
877 for (int i = 0; i < initialized_fields.Count; ++i) {
878 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
879 fi.ResolveStatement (ec);
880 if (fi.IsDefaultInitializer && RootContext.Optimize) {
881 // Field is re-initialized to its default value => removed
882 initialized_fields.RemoveAt (i);
890 // Emits the instance field initializers
892 public bool EmitFieldInitializers (EmitContext ec)
894 if (partial_parts != null) {
895 foreach (TypeContainer part in partial_parts)
896 part.EmitFieldInitializers (ec);
902 fields = initialized_static_fields;
904 fields = initialized_fields;
910 foreach (FieldInitializer f in fields) {
911 f.EmitStatement (ec);
916 public override string DocComment {
928 public PendingImplementation PendingImplementations {
929 get { return pending; }
932 public override bool GetClsCompliantAttributeValue ()
934 if (PartialContainer != this)
935 return PartialContainer.GetClsCompliantAttributeValue ();
937 return base.GetClsCompliantAttributeValue ();
940 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
942 // FIXME: get rid of partial_parts and store lists of bases of each part here
943 // assumed, not verified: 'part' is in 'partial_parts'
944 ((TypeContainer) part).Bases = bases;
947 TypeExpr[] GetNormalBases (out TypeExpr base_class)
953 int count = Bases.Count;
956 if (Kind == Kind.Class){
957 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
963 if (!name.IsInterface) {
964 // base_class could be a class, struct, enum, delegate.
965 // This is validated in GetClassBases.
971 TypeExpr [] ifaces = new TypeExpr [count-start];
973 for (i = start, j = 0; i < count; i++, j++){
974 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
975 if (resolved == null) {
979 ifaces [j] = resolved;
982 return ifaces.Length == 0 ? null : ifaces;
986 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
988 ArrayList ifaces = new ArrayList (0);
989 if (iface_exprs != null)
990 ifaces.AddRange (iface_exprs);
992 foreach (TypeContainer part in partial_parts) {
993 TypeExpr new_base_class;
994 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
995 if (new_base_class != TypeManager.system_object_expr) {
996 if (base_class == TypeManager.system_object_expr)
997 base_class = new_base_class;
999 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1000 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1001 Report.Error (263, part.Location,
1002 "Partial declarations of `{0}' must not specify different base classes",
1003 part.GetSignatureForError ());
1010 if (new_ifaces == null)
1013 foreach (TypeExpr iface in new_ifaces) {
1014 if (ifaces.Contains (iface))
1021 if (ifaces.Count == 0)
1024 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1028 /// This function computes the Base class and also the
1029 /// list of interfaces that the class or struct @c implements.
1031 /// The return value is an array (might be null) of
1032 /// interfaces implemented (as Types).
1034 /// The @base_class argument is set to the base object or null
1035 /// if this is `System.Object'.
1037 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1039 TypeExpr[] ifaces = GetNormalBases (out base_class);
1044 int count = ifaces.Length;
1046 for (int i = 0; i < count; i++) {
1047 TypeExpr iface = (TypeExpr) ifaces [i];
1049 if (!iface.IsInterface) {
1050 if (Kind != Kind.Class) {
1051 // TODO: location of symbol related ....
1052 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
1054 else if (base_class != null)
1055 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1056 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1058 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1059 GetSignatureForError (), iface.GetSignatureForError ());
1064 for (int x = 0; x < i; x++) {
1065 if (iface.Equals (ifaces [x])) {
1066 Report.Error (528, Location,
1067 "`{0}' is already listed in " +
1068 "interface list", iface.GetSignatureForError ());
1073 if ((Kind == Kind.Interface) &&
1074 !iface.AsAccessible (Parent, ModFlags)) {
1075 Report.Error (61, Location,
1076 "Inconsistent accessibility: base " +
1077 "interface `{0}' is less accessible " +
1078 "than interface `{1}'", iface.Name,
1086 bool CheckGenericInterfaces (Type[] ifaces)
1089 ArrayList already_checked = new ArrayList ();
1091 for (int i = 0; i < ifaces.Length; i++) {
1092 Type iface = ifaces [i];
1093 foreach (Type t in already_checked) {
1097 Type[] inferred = new Type [CountTypeParameters];
1098 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
1101 Report.Error (695, Location,
1102 "`{0}' cannot implement both `{1}' and `{2}' " +
1103 "because they may unify for some type parameter substitutions",
1104 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1105 TypeManager.CSharpName (t));
1109 already_checked.Add (iface);
1118 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1120 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1123 bool CreateTypeBuilder ()
1126 Type default_parent = null;
1127 if (Kind == Kind.Struct)
1128 default_parent = TypeManager.value_type;
1129 else if (Kind == Kind.Enum)
1130 default_parent = TypeManager.enum_type;
1133 if (TypeManager.NamespaceClash (Name, Location)) {
1137 ModuleBuilder builder = CodeGen.Module.Builder;
1138 TypeBuilder = builder.DefineType (
1139 Name, TypeAttr, default_parent, null);
1141 TypeBuilder builder = Parent.TypeBuilder;
1143 TypeBuilder = builder.DefineNestedType (
1144 Basename, TypeAttr, default_parent, null);
1146 } catch (ArgumentException) {
1147 Report.RuntimeMissingSupport (Location, "static classes");
1151 TypeManager.AddUserType (this);
1155 string[] param_names = new string [TypeParameters.Length];
1156 for (int i = 0; i < TypeParameters.Length; i++)
1157 param_names [i] = TypeParameters [i].Name;
1159 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1161 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1162 for (int i = offset; i < gen_params.Length; i++)
1163 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1170 bool DefineBaseTypes ()
1172 iface_exprs = GetClassBases (out base_type);
1173 if (partial_parts != null) {
1174 iface_exprs = GetNormalPartialBases (ref base_type);
1178 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1179 // which in turn should have called DefineType()s on base types if necessary.
1181 // None of the code below should trigger DefineType()s on classes that we depend on.
1182 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1184 // Let's do it as soon as possible, since code below can call DefineType() on classes
1185 // that depend on us to be populated before they are.
1187 if (!(this is CompilerGeneratedClass))
1188 RootContext.RegisterOrder (this);
1190 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1191 Report.Error (698, base_type.Location,
1192 "A generic type cannot derive from `{0}' because it is an attribute class",
1197 if (!CheckRecursiveDefinition (this))
1200 if (base_type != null && base_type.Type != null) {
1201 TypeBuilder.SetParent (base_type.Type);
1203 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1204 if (obsolete_attr != null && !IsInObsoleteScope)
1205 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1208 // add interfaces that were not added at type creation
1209 if (iface_exprs != null) {
1210 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1214 foreach (Type itype in ifaces)
1215 TypeBuilder.AddInterfaceImplementation (itype);
1217 foreach (TypeExpr ie in iface_exprs) {
1218 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1219 if ((oa != null) && !IsInObsoleteScope)
1220 AttributeTester.Report_ObsoleteMessage (
1221 oa, ie.GetSignatureForError (), Location);
1224 if (!CheckGenericInterfaces (ifaces))
1227 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1234 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1236 public TypeBuilder CreateType ()
1238 if (TypeBuilder != null)
1244 if (!CreateTypeBuilder ()) {
1249 if (partial_parts != null) {
1250 foreach (TypeContainer part in partial_parts)
1251 part.TypeBuilder = TypeBuilder;
1254 if (Types != null) {
1255 foreach (TypeContainer tc in Types) {
1256 if (tc.CreateType () == null) {
1268 public override TypeBuilder DefineType ()
1275 type_defined = true;
1277 if (CreateType () == null) {
1282 if (!DefineBaseTypes ()) {
1287 if (!(this is CompilerGeneratedClass)) {
1288 if (!ResolveMembers ()) {
1294 if (!DefineNestedTypes ()) {
1302 public bool ResolveMembers ()
1304 if (members_resolved)
1305 return members_resolved_ok;
1307 members_resolved_ok = DoResolveMembers ();
1308 members_resolved = true;
1310 return members_resolved_ok;
1313 protected virtual bool DoResolveMembers ()
1315 if (methods != null) {
1316 foreach (Method method in methods) {
1317 if (!method.ResolveMembers ())
1322 if (instance_constructors != null) {
1323 foreach (Constructor c in instance_constructors) {
1324 if (!c.ResolveMembers ())
1329 if (default_static_constructor != null) {
1330 if (!default_static_constructor.ResolveMembers ())
1334 if (operators != null) {
1335 foreach (Operator o in operators) {
1336 if (!o.ResolveMembers ())
1341 if (properties != null) {
1342 foreach (PropertyBase p in properties) {
1343 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1345 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1350 if (indexers != null) {
1351 foreach (PropertyBase p in indexers) {
1352 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1354 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1359 if (events != null) {
1360 foreach (Event e in events) {
1361 if (!e.Add.ResolveMembers ())
1363 if (!e.Remove.ResolveMembers ())
1368 if (compiler_generated != null) {
1369 foreach (CompilerGeneratedClass c in compiler_generated) {
1370 if (c.DefineType () == null)
1378 Constraints [] constraints;
1379 public override void SetParameterInfo (ArrayList constraints_list)
1381 if (PartialContainer == this) {
1382 base.SetParameterInfo (constraints_list);
1386 if (constraints_list == null)
1389 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1391 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1392 for (int i = 0; i < constraints.Length; i++) {
1393 foreach (Constraints constraint in constraints_list) {
1394 if (constraint.TypeParameter == current_params [i].Name) {
1395 constraints [i] = constraint;
1402 bool UpdateTypeParameterConstraints ()
1404 if (constraints == null)
1407 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1408 for (int i = 0; i < current_params.Length; i++) {
1409 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1410 Report.SymbolRelatedToPreviousError (Location, "");
1411 Report.Error (265, PartialContainer.Location,
1412 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1413 PartialContainer.GetSignatureForError (), current_params [i].Name);
1421 public bool ResolveType ()
1423 if (!DoResolveType ())
1426 if (compiler_generated != null) {
1427 foreach (CompilerGeneratedClass c in compiler_generated)
1428 if (!c.ResolveType ())
1435 protected virtual bool DoResolveType ()
1437 if ((base_type != null) &&
1438 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1446 if (PartialContainer != this)
1447 throw new InternalErrorException ();
1449 TypeExpr current_type = null;
1451 foreach (TypeParameter type_param in CurrentTypeParameters) {
1452 if (!type_param.Resolve (this)) {
1458 if (partial_parts != null) {
1459 foreach (TypeContainer part in partial_parts) {
1460 if (!part.UpdateTypeParameterConstraints ()) {
1467 foreach (TypeParameter type_param in TypeParameters) {
1468 if (!type_param.DefineType (this)) {
1474 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1476 foreach (TypeParameter type_param in TypeParameters)
1477 if (!type_param.CheckDependencies ()) {
1482 if (current_type != null) {
1483 current_type = current_type.ResolveAsTypeTerminal (this, false);
1484 if (current_type == null) {
1489 CurrentType = current_type.Type;
1495 protected virtual bool DefineNestedTypes ()
1497 if (Types != null) {
1498 foreach (TypeContainer tc in Types)
1499 if (tc.DefineType () == null)
1503 if (Delegates != null) {
1504 foreach (Delegate d in Delegates)
1505 if (d.DefineType () == null)
1512 TypeContainer InTransit;
1514 protected bool CheckRecursiveDefinition (TypeContainer tc)
1516 if (InTransit != null) {
1517 Report.SymbolRelatedToPreviousError (this);
1518 if (this is Interface)
1520 529, tc.Location, "Inherited interface `{0}' causes a " +
1521 "cycle in the interface hierarchy of `{1}'",
1522 GetSignatureForError (), tc.GetSignatureForError ());
1525 146, tc.Location, "Circular base class dependency " +
1526 "involving `{0}' and `{1}'",
1527 tc.GetSignatureForError (), GetSignatureForError ());
1533 if (base_type != null && base_type.Type != null) {
1534 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1535 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1536 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1540 if (iface_exprs != null) {
1541 foreach (TypeExpr iface in iface_exprs) {
1542 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1543 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1544 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1549 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1556 public static void Error_KeywordNotAllowed (Location loc)
1558 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1562 /// Populates our TypeBuilder with fields and methods
1564 public override bool DefineMembers ()
1566 if (members_defined)
1567 return members_defined_ok;
1569 if (!base.DefineMembers ())
1572 members_defined_ok = DoDefineMembers ();
1573 members_defined = true;
1575 return members_defined_ok;
1578 protected virtual bool DoDefineMembers ()
1580 if (iface_exprs != null) {
1581 foreach (TypeExpr iface in iface_exprs) {
1582 ConstructedType ct = iface as ConstructedType;
1583 if ((ct != null) && !ct.CheckConstraints (this))
1588 if (base_type != null) {
1589 ConstructedType ct = base_type as ConstructedType;
1590 if ((ct != null) && !ct.CheckConstraints (this))
1595 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1596 if (conflict_symbol == null) {
1597 if ((ModFlags & Modifiers.NEW) != 0)
1598 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1600 if ((ModFlags & Modifiers.NEW) == 0) {
1601 Report.SymbolRelatedToPreviousError (conflict_symbol);
1602 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1603 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1608 DefineContainerMembers (constants);
1609 DefineContainerMembers (fields);
1611 if (Kind == Kind.Struct || Kind == Kind.Class) {
1612 pending = PendingImplementation.GetPendingImplementations (this);
1616 // Constructors are not in the defined_names array
1618 DefineContainerMembers (instance_constructors);
1620 DefineContainerMembers (events);
1621 DefineContainerMembers (ordered_explicit_member_list);
1622 DefineContainerMembers (ordered_member_list);
1624 DefineContainerMembers (operators);
1625 DefineContainerMembers (delegates);
1627 ComputeIndexerName();
1628 CheckEqualsAndGetHashCode();
1630 if (CurrentType != null) {
1631 GenericType = CurrentType;
1635 member_cache = new MemberCache (this);
1636 if (partial_parts != null) {
1637 foreach (TypeContainer part in partial_parts)
1638 part.member_cache = member_cache;
1645 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1648 mcal.DefineContainerMembers ();
1651 protected virtual void ComputeIndexerName ()
1653 if (indexers == null)
1656 string class_indexer_name = null;
1659 // If there's both an explicit and an implicit interface implementation, the
1660 // explicit one actually implements the interface while the other one is just
1661 // a normal indexer. See bug #37714.
1664 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1665 foreach (Indexer i in indexers) {
1666 if (i.InterfaceType != null) {
1667 if (seen_normal_indexers)
1668 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1672 seen_normal_indexers = true;
1674 if (class_indexer_name == null) {
1675 class_indexer_name = i.ShortName;
1679 if (i.ShortName != class_indexer_name)
1680 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");
1683 if (class_indexer_name != null)
1684 indexer_name = class_indexer_name;
1687 protected virtual void EmitIndexerName ()
1689 if (!seen_normal_indexers)
1692 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1693 TypeBuilder.SetCustomAttribute (cb);
1696 protected virtual void CheckEqualsAndGetHashCode ()
1698 if (methods == null)
1701 if (HasEquals && !HasGetHashCode) {
1702 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1706 public override bool Define ()
1708 if (compiler_generated != null) {
1709 foreach (CompilerGeneratedClass c in compiler_generated) {
1718 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1720 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1724 /// This function is based by a delegate to the FindMembers routine
1726 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1732 /// This filter is used by FindMembers, and we just keep
1733 /// a global for the filter to `AlwaysAccept'
1735 static MemberFilter accepting_filter;
1738 static TypeContainer ()
1740 accepting_filter = new MemberFilter (AlwaysAccept);
1743 public MethodInfo[] GetMethods ()
1745 ArrayList members = new ArrayList ();
1749 if (methods != null) {
1750 int len = methods.Count;
1751 for (int i = 0; i < len; i++) {
1752 Method m = (Method) methods [i];
1754 members.Add (m.MethodBuilder);
1758 if (operators != null) {
1759 int len = operators.Count;
1760 for (int i = 0; i < len; i++) {
1761 Operator o = (Operator) operators [i];
1763 members.Add (o.MethodBuilder);
1767 if (properties != null) {
1768 int len = properties.Count;
1769 for (int i = 0; i < len; i++) {
1770 Property p = (Property) properties [i];
1772 if (p.GetBuilder != null)
1773 members.Add (p.GetBuilder);
1774 if (p.SetBuilder != null)
1775 members.Add (p.SetBuilder);
1779 if (indexers != null) {
1780 int len = indexers.Count;
1781 for (int i = 0; i < len; i++) {
1782 Indexer ix = (Indexer) indexers [i];
1784 if (ix.GetBuilder != null)
1785 members.Add (ix.GetBuilder);
1786 if (ix.SetBuilder != null)
1787 members.Add (ix.SetBuilder);
1791 if (events != null) {
1792 int len = events.Count;
1793 for (int i = 0; i < len; i++) {
1794 Event e = (Event) events [i];
1796 if (e.AddBuilder != null)
1797 members.Add (e.AddBuilder);
1798 if (e.RemoveBuilder != null)
1799 members.Add (e.RemoveBuilder);
1803 MethodInfo[] retMethods = new MethodInfo [members.Count];
1804 members.CopyTo (retMethods, 0);
1808 // Indicated whether container has StructLayout attribute set Explicit
1809 public bool HasExplicitLayout {
1810 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1811 set { caching_flags |= Flags.HasExplicitLayout; }
1815 // Return the nested type with name @name. Ensures that the nested type
1816 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1818 public Type FindNestedType (string name)
1820 if (PartialContainer != this)
1821 throw new InternalErrorException ("should not happen");
1823 ArrayList [] lists = { types, delegates };
1825 for (int j = 0; j < lists.Length; ++j) {
1826 ArrayList list = lists [j];
1830 int len = list.Count;
1831 for (int i = 0; i < len; ++i) {
1832 DeclSpace ds = (DeclSpace) list [i];
1833 if (ds.Basename == name) {
1834 return ds.DefineType ();
1842 private void FindMembers_NestedTypes (int modflags,
1843 BindingFlags bf, MemberFilter filter, object criteria,
1844 ref ArrayList members)
1846 ArrayList [] lists = { types, delegates };
1848 for (int j = 0; j < lists.Length; ++j) {
1849 ArrayList list = lists [j];
1853 int len = list.Count;
1854 for (int i = 0; i < len; i++) {
1855 DeclSpace ds = (DeclSpace) list [i];
1857 if ((ds.ModFlags & modflags) == 0)
1860 TypeBuilder tb = ds.TypeBuilder;
1862 if (!(criteria is string) || ds.Basename.Equals (criteria))
1863 tb = ds.DefineType ();
1866 if (tb != null && (filter (tb, criteria) == true)) {
1867 if (members == null)
1868 members = new ArrayList ();
1877 /// This method returns the members of this type just like Type.FindMembers would
1878 /// Only, we need to use this for types which are _being_ defined because MS'
1879 /// implementation can't take care of that.
1882 // FIXME: return an empty static array instead of null, that cleans up
1883 // some code and is consistent with some coding conventions I just found
1887 // Notice that in various cases we check if our field is non-null,
1888 // something that would normally mean that there was a bug elsewhere.
1890 // The problem happens while we are defining p-invoke methods, as those
1891 // will trigger a FindMembers, but this happens before things are defined
1893 // Since the whole process is a no-op, it is fine to check for null here.
1895 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1896 MemberFilter filter, object criteria)
1898 ArrayList members = null;
1901 if ((bf & BindingFlags.Public) != 0)
1902 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1904 if ((bf & BindingFlags.NonPublic) != 0)
1905 modflags |= Modifiers.PRIVATE;
1907 int static_mask = 0, static_flags = 0;
1908 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1909 case BindingFlags.Static:
1910 static_mask = static_flags = Modifiers.STATIC;
1913 case BindingFlags.Instance:
1914 static_mask = Modifiers.STATIC;
1919 static_mask = static_flags = 0;
1923 Timer.StartTimer (TimerType.TcFindMembers);
1926 filter = accepting_filter;
1928 if ((mt & MemberTypes.Field) != 0) {
1929 if (fields != null) {
1930 int len = fields.Count;
1931 for (int i = 0; i < len; i++) {
1932 FieldBase f = (FieldBase) fields [i];
1934 if ((f.ModFlags & modflags) == 0)
1936 if ((f.ModFlags & static_mask) != static_flags)
1939 FieldBuilder fb = f.FieldBuilder;
1940 if (fb != null && filter (fb, criteria) == true) {
1941 if (members == null)
1942 members = new ArrayList ();
1949 if (constants != null) {
1950 int len = constants.Count;
1951 for (int i = 0; i < len; i++) {
1952 Const con = (Const) constants [i];
1954 if ((con.ModFlags & modflags) == 0)
1956 if ((con.ModFlags & static_mask) != static_flags)
1959 FieldBuilder fb = con.FieldBuilder;
1962 fb = con.FieldBuilder;
1964 if (fb != null && filter (fb, criteria) == true) {
1965 if (members == null)
1966 members = new ArrayList ();
1974 if ((mt & MemberTypes.Method) != 0) {
1975 if (methods != null) {
1976 int len = methods.Count;
1977 for (int i = 0; i < len; i++) {
1978 Method m = (Method) methods [i];
1980 if ((m.ModFlags & modflags) == 0)
1982 if ((m.ModFlags & static_mask) != static_flags)
1985 MethodBuilder mb = m.MethodBuilder;
1987 if (mb != null && filter (mb, criteria) == true) {
1988 if (members == null)
1989 members = new ArrayList ();
1996 if (operators != null) {
1997 int len = operators.Count;
1998 for (int i = 0; i < len; i++) {
1999 Operator o = (Operator) operators [i];
2001 if ((o.ModFlags & modflags) == 0)
2003 if ((o.ModFlags & static_mask) != static_flags)
2006 MethodBuilder ob = o.MethodBuilder;
2007 if (ob != null && filter (ob, criteria) == true) {
2008 if (members == null)
2009 members = new ArrayList ();
2016 if (events != null) {
2017 foreach (Event e in events) {
2018 if ((e.ModFlags & modflags) == 0)
2020 if ((e.ModFlags & static_mask) != static_flags)
2023 MethodBuilder b = e.AddBuilder;
2024 if (b != null && filter (b, criteria)) {
2025 if (members == null)
2026 members = new ArrayList (4);
2031 b = e.RemoveBuilder;
2032 if (b != null && filter (b, criteria)) {
2033 if (members == null)
2034 members = new ArrayList (4);
2041 if (properties != null) {
2042 int len = properties.Count;
2043 for (int i = 0; i < len; i++) {
2044 Property p = (Property) properties [i];
2046 if ((p.ModFlags & modflags) == 0)
2048 if ((p.ModFlags & static_mask) != static_flags)
2054 if (b != null && filter (b, criteria) == true) {
2055 if (members == null)
2056 members = new ArrayList ();
2062 if (b != null && filter (b, criteria) == true) {
2063 if (members == null)
2064 members = new ArrayList ();
2071 if (indexers != null) {
2072 int len = indexers.Count;
2073 for (int i = 0; i < len; i++) {
2074 Indexer ix = (Indexer) indexers [i];
2076 if ((ix.ModFlags & modflags) == 0)
2078 if ((ix.ModFlags & static_mask) != static_flags)
2084 if (b != null && filter (b, criteria) == true) {
2085 if (members == null)
2086 members = new ArrayList ();
2092 if (b != null && filter (b, criteria) == true) {
2093 if (members == null)
2094 members = new ArrayList ();
2102 if ((mt & MemberTypes.Event) != 0) {
2103 if (events != null) {
2104 int len = events.Count;
2105 for (int i = 0; i < len; i++) {
2106 Event e = (Event) events [i];
2108 if ((e.ModFlags & modflags) == 0)
2110 if ((e.ModFlags & static_mask) != static_flags)
2113 MemberInfo eb = e.EventBuilder;
2114 if (eb != null && filter (eb, criteria) == true) {
2115 if (members == null)
2116 members = new ArrayList ();
2118 members.Add (e.EventBuilder);
2124 if ((mt & MemberTypes.Property) != 0){
2125 if (properties != null) {
2126 int len = properties.Count;
2127 for (int i = 0; i < len; i++) {
2128 Property p = (Property) properties [i];
2130 if ((p.ModFlags & modflags) == 0)
2132 if ((p.ModFlags & static_mask) != static_flags)
2135 MemberInfo pb = p.PropertyBuilder;
2136 if (pb != null && filter (pb, criteria) == true) {
2137 if (members == null)
2138 members = new ArrayList ();
2140 members.Add (p.PropertyBuilder);
2145 if (indexers != null) {
2146 int len = indexers.Count;
2147 for (int i = 0; i < len; i++) {
2148 Indexer ix = (Indexer) indexers [i];
2150 if ((ix.ModFlags & modflags) == 0)
2152 if ((ix.ModFlags & static_mask) != static_flags)
2155 MemberInfo ib = ix.PropertyBuilder;
2156 if (ib != null && filter (ib, criteria) == true) {
2157 if (members == null)
2158 members = new ArrayList ();
2160 members.Add (ix.PropertyBuilder);
2166 if ((mt & MemberTypes.NestedType) != 0)
2167 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2169 if ((mt & MemberTypes.Constructor) != 0){
2170 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2171 int len = instance_constructors.Count;
2172 for (int i = 0; i < len; i++) {
2173 Constructor c = (Constructor) instance_constructors [i];
2175 ConstructorBuilder cb = c.ConstructorBuilder;
2176 if (cb != null && filter (cb, criteria) == true) {
2177 if (members == null)
2178 members = new ArrayList ();
2185 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2186 ConstructorBuilder cb =
2187 default_static_constructor.ConstructorBuilder;
2189 if (cb != null && filter (cb, criteria) == true) {
2190 if (members == null)
2191 members = new ArrayList ();
2199 // Lookup members in base if requested.
2201 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2202 if (TypeBuilder.BaseType != null) {
2203 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2204 if (list.Count > 0) {
2205 if (members == null)
2206 members = new ArrayList ();
2208 members.AddRange (list);
2213 Timer.StopTimer (TimerType.TcFindMembers);
2215 if (members == null)
2216 return MemberList.Empty;
2218 return new MemberList (members);
2221 public override MemberCache MemberCache {
2223 return member_cache;
2227 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2228 MemberFilter filter, object criteria)
2230 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2233 return ds.FindMembers (mt, bf, filter, criteria);
2235 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2239 /// Emits the values for the constants
2241 public void EmitConstants ()
2243 if (constants != null)
2244 foreach (Const con in constants)
2249 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2254 foreach (MemberCore mc in al) {
2255 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2259 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2264 public virtual void VerifyMembers ()
2267 // Check for internal or private fields that were never assigned
2269 if (Report.WarningLevel >= 3) {
2270 CheckMemberUsage (properties, "property");
2271 CheckMemberUsage (methods, "method");
2272 CheckMemberUsage (constants, "constant");
2274 if (fields != null){
2275 foreach (FieldBase f in fields) {
2276 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2280 if ((f.caching_flags & Flags.IsAssigned) == 0)
2281 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2284 const int error_code = 414;
2286 const int error_code = 169;
2288 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2289 f.GetSignatureForError ());
2295 // Only report 649 on level 4
2297 if (Report.WarningLevel < 4)
2300 if ((f.caching_flags & Flags.IsAssigned) != 0)
2303 Constant c = New.Constantify (f.Type.Type);
2304 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2305 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2311 // TODO: move to ClassOrStruct
2312 void EmitConstructors ()
2314 if (instance_constructors == null)
2317 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2318 bool has_compliant_args = false;
2320 foreach (Constructor c in instance_constructors) {
2324 catch (Exception e) {
2325 throw new InternalErrorException (c, e);
2328 if (has_compliant_args)
2331 has_compliant_args = c.HasCompliantArgs;
2333 if (!has_compliant_args)
2334 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2336 foreach (Constructor c in instance_constructors) {
2340 catch (Exception e) {
2341 throw new InternalErrorException (c, e);
2348 /// Emits the code, this step is performed after all
2349 /// the types, enumerations, constructors
2351 public virtual void EmitType ()
2353 if (OptAttributes != null)
2354 OptAttributes.Emit ();
2358 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2359 for (int i = offset; i < gen_params.Length; i++)
2360 CurrentTypeParameters [i - offset].Emit ();
2365 // Structs with no fields need to have at least one byte.
2366 // The right thing would be to set the PackingSize in a DefineType
2367 // but there are no functions that allow interfaces *and* the size to
2371 if (Kind == Kind.Struct && first_nonstatic_field == null){
2372 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2373 FieldAttributes.Private);
2375 if (HasExplicitLayout){
2376 object [] ctor_args = new object [1];
2379 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2380 TypeManager.field_offset_attribute_ctor, ctor_args);
2381 fb.SetCustomAttribute (cba);
2387 EmitConstructors ();
2389 // Can not continue if constants are broken
2391 if (Report.Errors > 0)
2394 if (default_static_constructor != null)
2395 default_static_constructor.Emit ();
2397 if (methods != null){
2398 for (int i = 0; i < methods.Count; ++i)
2399 ((Method)methods[i]).Emit ();
2402 if (operators != null)
2403 foreach (Operator o in operators)
2406 if (properties != null)
2407 foreach (Property p in properties)
2410 if (indexers != null) {
2411 foreach (Indexer indx in indexers)
2417 foreach (FieldBase f in fields)
2420 if (events != null){
2421 foreach (Event e in Events)
2425 if (delegates != null) {
2426 foreach (Delegate d in Delegates) {
2431 if (pending != null)
2432 if (pending.VerifyPendingMethods ())
2435 if (Report.Errors > 0)
2438 if (compiler_generated != null) {
2439 foreach (CompilerGeneratedClass c in compiler_generated) {
2440 if (!c.DefineMembers ())
2441 throw new InternalErrorException ();
2443 foreach (CompilerGeneratedClass c in compiler_generated)
2448 public override void CloseType ()
2450 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2454 caching_flags |= Flags.CloseTypeCreated;
2455 TypeBuilder.CreateType ();
2456 } catch (TypeLoadException){
2458 // This is fine, the code still created the type
2460 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2461 // Console.WriteLine (e.Message);
2462 } catch (Exception e) {
2463 throw new InternalErrorException (this, e);
2467 foreach (TypeContainer tc in Types)
2468 if (tc.Kind == Kind.Struct)
2471 foreach (TypeContainer tc in Types)
2472 if (tc.Kind != Kind.Struct)
2476 if (Delegates != null)
2477 foreach (Delegate d in Delegates)
2480 if (CompilerGenerated != null)
2481 foreach (CompilerGeneratedClass c in CompilerGenerated)
2488 initialized_fields = null;
2489 initialized_static_fields = null;
2491 ordered_explicit_member_list = null;
2492 ordered_member_list = null;
2497 compiler_generated = null;
2498 default_constructor = null;
2499 default_static_constructor = null;
2501 OptAttributes = null;
2504 member_cache = null;
2508 // Performs the validation on a Method's modifiers (properties have
2509 // the same properties).
2511 public bool MethodModifiersValid (MemberCore mc)
2513 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2514 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2515 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2517 int flags = mc.ModFlags;
2520 // At most one of static, virtual or override
2522 if ((flags & Modifiers.STATIC) != 0){
2523 if ((flags & vao) != 0){
2524 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2525 mc.GetSignatureForError ());
2530 if (Kind == Kind.Struct){
2531 if ((flags & va) != 0){
2532 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2537 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2538 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2539 mc.GetSignatureForError ());
2544 // If the declaration includes the abstract modifier, then the
2545 // declaration does not include static, virtual or extern
2547 if ((flags & Modifiers.ABSTRACT) != 0){
2548 if ((flags & Modifiers.EXTERN) != 0){
2550 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2554 if ((flags & Modifiers.SEALED) != 0) {
2555 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2559 if ((flags & Modifiers.VIRTUAL) != 0){
2560 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2564 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2565 Report.SymbolRelatedToPreviousError (this);
2566 Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2567 mc.GetSignatureForError (), GetSignatureForError ());
2572 if ((flags & Modifiers.PRIVATE) != 0){
2573 if ((flags & vao) != 0){
2574 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2579 if ((flags & Modifiers.SEALED) != 0){
2580 if ((flags & Modifiers.OVERRIDE) == 0){
2581 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2589 public Constructor DefaultStaticConstructor {
2590 get { return default_static_constructor; }
2593 protected override bool VerifyClsCompliance ()
2595 if (!base.VerifyClsCompliance ())
2600 Type base_type = TypeBuilder.BaseType;
2601 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2602 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2609 /// Checks whether container name is CLS Compliant
2611 void VerifyClsName ()
2613 Hashtable base_members = base_cache == null ?
2615 base_cache.GetPublicMembers ();
2616 Hashtable this_members = new Hashtable ();
2618 foreach (DictionaryEntry entry in defined_names) {
2619 MemberCore mc = (MemberCore)entry.Value;
2620 if (!mc.IsClsComplianceRequired ())
2623 string name = (string) entry.Key;
2624 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2626 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2627 object found = base_members [lcase];
2628 if (found == null) {
2629 found = this_members [lcase];
2630 if (found == null) {
2631 this_members.Add (lcase, mc);
2636 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2639 if (found is MemberInfo) {
2640 if (basename == ((MemberInfo) found).Name)
2642 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2644 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2647 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2649 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2656 /// Performs checks for an explicit interface implementation. First it
2657 /// checks whether the `interface_type' is a base inteface implementation.
2658 /// Then it checks whether `name' exists in the interface type.
2660 public virtual bool VerifyImplements (InterfaceMemberBase mb)
2662 if (ifaces != null) {
2663 foreach (Type t in ifaces){
2664 if (t == mb.InterfaceType)
2669 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2670 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2671 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2675 public override Type LookupAnyGeneric (string typeName)
2677 if (types != null) {
2678 foreach (TypeContainer tc in types) {
2682 int pos = tc.Basename.LastIndexOf ('`');
2683 if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2684 return tc.TypeBuilder;
2688 return base.LookupAnyGeneric (typeName);
2691 public void Mark_HasEquals ()
2693 cached_method |= CachedMethods.Equals;
2696 public void Mark_HasGetHashCode ()
2698 cached_method |= CachedMethods.GetHashCode;
2702 /// Method container contains Equals method
2704 public bool HasEquals {
2706 return (cached_method & CachedMethods.Equals) != 0;
2711 /// Method container contains GetHashCode method
2713 public bool HasGetHashCode {
2715 return (cached_method & CachedMethods.GetHashCode) != 0;
2719 public bool HasStaticFieldInitializer {
2721 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2725 cached_method |= CachedMethods.HasStaticFieldInitializer;
2727 cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2735 string IMemberContainer.Name {
2741 Type IMemberContainer.Type {
2747 MemberCache IMemberContainer.MemberCache {
2749 return member_cache;
2753 bool IMemberContainer.IsInterface {
2755 return Kind == Kind.Interface;
2759 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2761 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2763 if (GenericType != null)
2764 return TypeManager.FindMembers (GenericType, mt, new_bf,
2767 return FindMembers (mt, new_bf, null, null);
2771 // Generates xml doc comments (if any), and if required,
2772 // handle warning report.
2774 internal override void GenerateDocComment (DeclSpace ds)
2776 DocUtil.GenerateTypeDocComment (this, ds);
2779 public override string DocCommentHeader {
2780 get { return "T:"; }
2783 public virtual MemberCache BaseCache {
2785 if (base_cache != null)
2787 if (TypeBuilder.BaseType != null)
2788 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2789 if (TypeBuilder.IsInterface)
2790 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2796 public abstract class ClassOrStruct : TypeContainer {
2797 ListDictionary declarative_security;
2799 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2800 MemberName name, Attributes attrs, Kind kind)
2801 : base (ns, parent, name, attrs, kind)
2805 protected override bool AddToContainer (MemberCore symbol, string name)
2807 if (name == MemberName.Name) {
2808 if (symbol is TypeParameter) {
2809 Report.Error (694, symbol.Location,
2810 "Type parameter `{0}' has same name as " +
2811 "containing type, or method", name);
2815 Report.SymbolRelatedToPreviousError (this);
2816 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2817 symbol.GetSignatureForError ());
2821 return base.AddToContainer (symbol, name);
2824 public override void VerifyMembers ()
2826 base.VerifyMembers ();
2828 if ((events != null) && Report.WarningLevel >= 3) {
2829 foreach (Event e in events){
2830 if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2833 if ((e.caching_flags & Flags.IsUsed) == 0)
2834 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2839 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2841 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2842 if (declarative_security == null)
2843 declarative_security = new ListDictionary ();
2845 a.ExtractSecurityPermissionSet (declarative_security);
2849 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2850 HasExplicitLayout = true;
2853 base.ApplyAttributeBuilder (a, cb);
2857 /// Defines the default constructors
2859 protected void DefineDefaultConstructor (bool is_static)
2861 // The default instance constructor is public
2862 // If the class is abstract, the default constructor is protected
2863 // The default static constructor is private
2867 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2869 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2872 Constructor c = new Constructor (this, MemberName.Name, mods,
2873 Parameters.EmptyReadOnlyParameters,
2874 new GeneratedBaseInitializer (Location),
2878 c.Block = new ToplevelBlock (null, Location);
2881 public override bool Define ()
2883 if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer)
2884 DefineDefaultConstructor (true);
2886 if (default_static_constructor != null)
2887 default_static_constructor.Define ();
2889 return base.Define ();
2892 public override void Emit ()
2896 if (declarative_security != null) {
2897 foreach (DictionaryEntry de in declarative_security) {
2898 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2903 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name)
2905 return NamespaceEntry.LookupExtensionMethod (extensionType, this, name);
2908 protected override TypeAttributes TypeAttr {
2910 if (default_static_constructor == null)
2911 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2913 return base.TypeAttr;
2919 // TODO: should be sealed
2920 public class Class : ClassOrStruct {
2921 const int AllowedModifiers =
2924 Modifiers.PROTECTED |
2925 Modifiers.INTERNAL |
2927 Modifiers.ABSTRACT |
2932 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2934 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2936 : base (ns, parent, name, attrs, Kind.Class)
2938 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2939 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2941 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2942 Report.FeatureIsNotISO1 (Location, "static classes");
2946 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2948 if (part.Name == "System.Object")
2949 Report.Error (537, part.Location,
2950 "The class System.Object cannot have a base class or implement an interface.");
2951 base.AddBasesForPart (part, bases);
2954 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2956 if (a.Type == TypeManager.attribute_usage_type) {
2957 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2958 TypeBuilder.FullName != "System.Attribute") {
2959 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2963 if (a.Type == TypeManager.conditional_attribute_type &&
2964 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2965 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2969 if (a.Type == TypeManager.comimport_attr_type &&
2970 !attributes.Contains (TypeManager.guid_attr_type)) {
2971 a.Error_MissingGuidAttribute ();
2975 if (a.Type == TypeManager.extension_attribute_type) {
2976 a.Error_MisusedExtensionAttribute ();
2980 if (AttributeTester.IsAttributeExcluded (a.Type))
2983 base.ApplyAttributeBuilder (a, cb);
2986 public override AttributeTargets AttributeTargets {
2988 return AttributeTargets.Class;
2992 protected override void DefineContainerMembers (MemberCoreArrayList list)
2998 base.DefineContainerMembers (list);
3002 foreach (MemberCore m in list) {
3003 if (m is Operator) {
3004 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
3008 if (m is Destructor) {
3009 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
3013 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
3014 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
3019 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
3023 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3026 if (m is Constructor) {
3027 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3031 Method method = m as Method;
3032 if (method != null && method.Parameters.HasExtensionMethodType) {
3033 Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
3037 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3040 base.DefineContainerMembers (list);
3043 public override TypeBuilder DefineType ()
3045 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3046 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3050 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3051 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3055 return base.DefineType ();
3058 protected override bool DoDefineMembers ()
3060 if (InstanceConstructors == null && !IsStatic)
3061 DefineDefaultConstructor (false);
3063 return base.DoDefineMembers ();
3066 public override void Emit ()
3070 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
3071 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
3074 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3076 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3078 if (base_class == null) {
3079 if (RootContext.StdLib)
3080 base_class = TypeManager.system_object_expr;
3081 else if (Name != "System.Object")
3082 base_class = TypeManager.system_object_expr;
3084 if (Kind == Kind.Class && base_class is TypeParameterExpr){
3086 689, base_class.Location,
3087 "Cannot derive from `{0}' because it is a type parameter",
3088 base_class.GetSignatureForError ());
3092 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
3093 Report.Error (1521, base_class.Location, "Invalid base type");
3097 if (base_class.IsSealed){
3098 Report.SymbolRelatedToPreviousError (base_class.Type);
3099 if (base_class.Type.IsAbstract) {
3100 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3101 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3103 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3104 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3109 if (!base_class.CanInheritFrom ()){
3110 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3111 GetSignatureForError (), base_class.GetSignatureForError ());
3115 if (!base_class.AsAccessible (this, ModFlags)) {
3116 Report.SymbolRelatedToPreviousError (base_class.Type);
3117 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3118 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3123 if (base_class.Type != TypeManager.object_type) {
3124 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3125 GetSignatureForError (), base_class.GetSignatureForError ());
3129 if (ifaces != null) {
3130 foreach (TypeExpr t in ifaces)
3131 Report.SymbolRelatedToPreviousError (t.Type);
3132 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3139 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3140 /// Valid only for attribute classes.
3141 public bool IsExcluded ()
3143 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3144 return (caching_flags & Flags.Excluded) != 0;
3146 caching_flags &= ~Flags.Excluded_Undetected;
3148 if (OptAttributes == null)
3151 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3156 foreach (Attribute a in attrs) {
3157 string condition = a.GetConditionalAttributeValue ();
3158 if (RootContext.AllDefines.Contains (condition))
3162 caching_flags |= Flags.Excluded;
3168 return (ModFlags & Modifiers.STATIC) != 0;
3173 // FIXME: How do we deal with the user specifying a different
3176 protected override TypeAttributes TypeAttr {
3178 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3180 ta |= StaticClassAttribute;
3186 public sealed class Struct : ClassOrStruct {
3188 // Modifiers allowed in a struct declaration
3190 const int AllowedModifiers =
3193 Modifiers.PROTECTED |
3194 Modifiers.INTERNAL |
3198 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3199 int mod, Attributes attrs)
3200 : base (ns, parent, name, attrs, Kind.Struct)
3204 if (parent.Parent == null)
3205 accmods = Modifiers.INTERNAL;
3207 accmods = Modifiers.PRIVATE;
3209 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3211 this.ModFlags |= Modifiers.SEALED;
3214 public override AttributeTargets AttributeTargets {
3216 return AttributeTargets.Struct;
3220 const TypeAttributes DefaultTypeAttributes =
3221 TypeAttributes.SequentialLayout |
3222 TypeAttributes.Sealed |
3223 TypeAttributes.BeforeFieldInit;
3226 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3228 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3230 // If we are compiling our runtime,
3231 // and we are defining ValueType, then our
3232 // base is `System.Object'.
3234 if (base_class == null) {
3235 if (!RootContext.StdLib && Name == "System.ValueType")
3236 base_class = TypeManager.system_object_expr;
3238 base_class = TypeManager.system_valuetype_expr;
3245 // FIXME: Allow the user to specify a different set of attributes
3246 // in some cases (Sealed for example is mandatory for a class,
3247 // but what SequentialLayout can be changed
3249 protected override TypeAttributes TypeAttr {
3251 return base.TypeAttr | DefaultTypeAttributes;
3255 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3257 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3258 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3259 field.GetSignatureForError ());
3262 base.RegisterFieldForInitialization (field, expression);
3270 public sealed class Interface : TypeContainer, IMemberContainer {
3273 /// Modifiers allowed in a class declaration
3275 public const int AllowedModifiers =
3278 Modifiers.PROTECTED |
3279 Modifiers.INTERNAL |
3283 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3285 : base (ns, parent, name, attrs, Kind.Interface)
3289 if (parent.Parent == null)
3290 accmods = Modifiers.INTERNAL;
3292 accmods = Modifiers.PRIVATE;
3294 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3297 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3299 if (a.Type == TypeManager.comimport_attr_type &&
3300 !attributes.Contains (TypeManager.guid_attr_type)) {
3301 a.Error_MissingGuidAttribute ();
3304 base.ApplyAttributeBuilder (a, cb);
3308 public override AttributeTargets AttributeTargets {
3310 return AttributeTargets.Interface;
3314 const TypeAttributes DefaultTypeAttributes =
3315 TypeAttributes.AutoLayout |
3316 TypeAttributes.Abstract |
3317 TypeAttributes.Interface;
3319 protected override TypeAttributes TypeAttr {
3321 return base.TypeAttr | DefaultTypeAttributes;
3325 protected override bool VerifyClsCompliance ()
3327 if (!base.VerifyClsCompliance ())
3330 if (ifaces != null) {
3331 foreach (Type t in ifaces) {
3332 if (AttributeTester.IsClsCompliant (t))
3335 Report.SymbolRelatedToPreviousError (t);
3336 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3337 GetSignatureForError (), TypeManager.CSharpName (t));
3345 // It is used as a base class for all property based members
3346 // This includes properties, indexers, and events
3347 public abstract class PropertyBasedMember : InterfaceMemberBase
3349 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3350 Expression type, int mod, int allowed_mod, bool is_iface,
3351 MemberName name, Attributes attrs)
3352 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3356 protected override bool CheckForDuplications ()
3358 throw new NotSupportedException ();
3361 protected override bool VerifyClsCompliance ()
3363 if (!base.VerifyClsCompliance ())
3366 if (!AttributeTester.IsClsCompliant (MemberType)) {
3367 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3368 GetSignatureForError ());
3376 public abstract class MethodCore : InterfaceMemberBase
3378 public readonly Parameters Parameters;
3379 protected ToplevelBlock block;
3381 public MethodCore (DeclSpace parent, GenericMethod generic,
3382 Expression type, int mod, int allowed_mod, bool is_iface,
3383 MemberName name, Attributes attrs, Parameters parameters)
3384 : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
3386 Parameters = parameters;
3390 // Returns the System.Type array for the parameters of this method
3392 public Type [] ParameterTypes {
3394 return Parameters.Types;
3398 public Parameters ParameterInfo
3405 public ToplevelBlock Block {
3415 protected override bool CheckBase ()
3417 // Check whether arguments were correct.
3418 if (!DefineParameters (Parameters))
3421 if (!base.CheckBase ())
3427 // TODO: create a special method for operators only to make code better
3428 protected bool IsDuplicateImplementation (MethodCore method)
3433 Operator op2 = null;
3434 Operator op1 = null;
3436 if (!(method.MemberName.Equals (MemberName)))
3438 op1 = this as Operator;
3439 if (op1 == null || !(op1.OperatorType == Operator.OpType.Explicit || op1.OperatorType == Operator.OpType.Implicit))
3442 op2 = method as Operator;
3443 if (op2 == null || !(op2.OperatorType == Operator.OpType.Explicit || op2.OperatorType == Operator.OpType.Implicit))
3446 op1 = this as Operator;
3447 op2 = method as Operator;
3450 Type[] param_types = method.ParameterTypes;
3451 // This never happen. Rewrite this as Equal
3452 if (param_types == null && ParameterTypes == null)
3454 if (param_types == null || ParameterTypes == null)
3457 if (param_types.Length != ParameterTypes.Length)
3460 if (method.Parameters.HasArglist != Parameters.HasArglist)
3465 for (int i = 0; i < param_types.Length; i++) {
3466 if (param_types [i] != ParameterTypes [i])
3470 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3473 // TODO: make operator compatible with MethodCore to avoid this
3474 if (op1 != null && op2 != null) {
3475 if (MemberType != method.MemberType)
3483 // Try to report 663: method only differs on out/ref
3485 Parameters info = ParameterInfo;
3486 Parameters other_info = method.ParameterInfo;
3487 for (int i = 0; i < info.Count; i++) {
3488 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)) {
3489 Report.SymbolRelatedToPreviousError (method);
3490 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3491 GetSignatureForError ());
3496 Report.SymbolRelatedToPreviousError (method);
3497 if (this is Operator && method is Operator)
3498 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3500 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3506 // Returns a string that represents the signature for this
3507 // member which should be used in XML documentation.
3509 public override string GetDocCommentName (DeclSpace ds)
3511 return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3515 // Raised (and passed an XmlElement that contains the comment)
3516 // when GenerateDocComment is writing documentation expectedly.
3518 // FIXME: with a few effort, it could be done with XmlReader,
3519 // that means removal of DOM use.
3521 internal override void OnGenerateDocComment (XmlElement el)
3523 DocUtil.OnMethodGenerateDocComment (this, el);
3527 // Represents header string for documentation comment.
3529 public override string DocCommentHeader
3531 get { return "M:"; }
3534 public virtual void SetYields ()
3536 ModFlags |= Modifiers.METHOD_YIELDS;
3539 protected override bool VerifyClsCompliance ()
3541 if (!base.VerifyClsCompliance ())
3544 if (Parameters.HasArglist) {
3545 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3548 if (!AttributeTester.IsClsCompliant (MemberType)) {
3549 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3550 GetSignatureForError ());
3553 Parameters.VerifyClsCompliance ();
3559 public abstract class InterfaceMemberBase : MemberBase {
3561 // Whether this is an interface member.
3563 public bool IsInterface;
3566 // If true, this is an explicit interface implementation
3568 public bool IsExplicitImpl;
3570 protected bool is_external_implementation;
3573 // The interface type we are explicitly implementing
3575 public Type InterfaceType;
3578 // The method we're overriding if this is an override method.
3580 protected MethodInfo base_method;
3582 readonly int explicit_mod_flags;
3583 public MethodAttributes flags;
3585 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3586 Expression type, int mod, int allowed_mod, bool is_iface,
3587 MemberName name, Attributes attrs)
3588 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3591 IsInterface = is_iface;
3592 IsExplicitImpl = (MemberName.Left != null);
3593 explicit_mod_flags = mod;
3596 protected override bool CheckBase ()
3598 if (!base.CheckBase ())
3601 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3607 // Is null for System.Object while compiling corlib and base interfaces
3608 if (Parent.PartialContainer.BaseCache == null) {
3609 if ((ModFlags & Modifiers.NEW) != 0) {
3610 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3615 Type base_ret_type = null;
3616 base_method = FindOutBaseMethod (ref base_ret_type);
3618 // method is override
3619 if (base_method != null) {
3620 if (!CheckMethodAgainstBase (base_ret_type))
3623 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3624 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3626 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3627 Report.SymbolRelatedToPreviousError (base_method);
3628 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3629 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3632 if (OptAttributes != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3633 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3634 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3641 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3642 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3643 if (conflict_symbol != null) {
3644 Report.SymbolRelatedToPreviousError (conflict_symbol);
3646 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3647 else if (this is PropertyBase)
3648 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3650 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3652 Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3653 GetSignatureForError (), SimpleName.GetMemberType (this));
3658 if (conflict_symbol == null) {
3659 if ((ModFlags & Modifiers.NEW) != 0) {
3660 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3665 if ((ModFlags & Modifiers.NEW) == 0) {
3666 if (this is Method && conflict_symbol is MethodBase)
3669 Report.SymbolRelatedToPreviousError (conflict_symbol);
3670 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3671 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3678 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3679 // that have been defined.
3681 // `name' is the user visible name for reporting errors (this is used to
3682 // provide the right name regarding method names and properties)
3684 bool CheckMethodAgainstBase (Type base_method_type)
3688 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3689 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3690 Report.Error (506, Location,
3691 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3692 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3696 // Now we check that the overriden method is not final
3698 if (base_method.IsFinal) {
3699 Report.SymbolRelatedToPreviousError (base_method);
3700 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3701 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3705 // Check that the permissions are not being changed
3707 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3708 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3710 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3711 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3715 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3716 Report.SymbolRelatedToPreviousError (base_method);
3717 if (this is PropertyBasedMember) {
3718 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3719 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3722 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3723 GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3729 if ((ModFlags & Modifiers.NEW) == 0) {
3730 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3731 ModFlags |= Modifiers.NEW;
3732 Report.SymbolRelatedToPreviousError (base_method);
3733 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3734 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",
3735 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3737 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3738 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3742 if (base_method.IsAbstract && !IsInterface) {
3743 Report.SymbolRelatedToPreviousError (base_method);
3744 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3745 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3753 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3755 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3757 // when overriding protected internal, the method can be declared
3758 // protected internal only within the same assembly
3761 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3762 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3764 // assemblies differ - report an error
3768 } else if (thisp != base_classp) {
3770 // same assembly, but other attributes differ - report an error
3775 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3777 // if it's not "protected internal", it must be "protected"
3781 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3783 // protected within the same assembly - an error
3786 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3787 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3789 // protected ok, but other attributes differ - report an error
3795 return (thisp == base_classp);
3799 protected bool DefineParameters (Parameters parameters)
3801 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3803 if (!parameters.Resolve (rc))
3807 foreach (Parameter p in parameters.FixedParameters) {
3808 if (p.CheckAccessibility (this))
3811 Report.SymbolRelatedToPreviousError (p.ParameterType);
3812 if (this is Indexer)
3813 Report.Error (55, Location,
3814 "Inconsistent accessibility: parameter type `" +
3815 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3816 "accessible than indexer `" + GetSignatureForError () + "'");
3817 else if (this is Operator)
3818 Report.Error (57, Location,
3819 "Inconsistent accessibility: parameter type `" +
3820 TypeManager.CSharpName (p.ParameterType) + "' is less " +
3821 "accessible than operator `" + GetSignatureForError () + "'");
3823 Report.Error (51, Location,
3824 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3825 TypeManager.CSharpName (p.ParameterType), GetSignatureForError ());
3831 protected override bool DoDefine()
3833 if (!base.DoDefine ())
3836 if (IsExplicitImpl) {
3837 Expression expr = MemberName.Left.GetTypeExpression ();
3838 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
3842 InterfaceType = texpr.Type;
3844 if (!InterfaceType.IsInterface) {
3845 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3849 if (!Parent.PartialContainer.VerifyImplements (this))
3856 protected virtual bool DoDefineBase ()
3859 throw new InternalErrorException ();
3862 ModFlags = Modifiers.PUBLIC |
3863 Modifiers.ABSTRACT |
3864 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
3866 flags = MethodAttributes.Public |
3867 MethodAttributes.Abstract |
3868 MethodAttributes.HideBySig |
3869 MethodAttributes.NewSlot |
3870 MethodAttributes.Virtual;
3872 if (!Parent.PartialContainer.MethodModifiersValid (this))
3875 flags = Modifiers.MethodAttr (ModFlags);
3878 if (IsExplicitImpl) {
3879 Expression expr = MemberName.Left.GetTypeExpression ();
3880 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
3881 if (iface_texpr == null)
3884 InterfaceType = iface_texpr.Type;
3886 if (!InterfaceType.IsInterface) {
3887 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
3891 if (!Parent.PartialContainer.VerifyImplements (this))
3894 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3900 public override void Emit()
3902 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3903 // We are more strict than Microsoft and report CS0626 as error
3904 if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3905 Report.Error (626, Location,
3906 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3907 GetSignatureForError ());
3913 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3915 Report.SymbolRelatedToPreviousError (base_method);
3916 string base_name = TypeManager.GetFullNameSignature (base_method);
3917 string this_name = GetSignatureForError ();
3918 if (suffix != null) {
3919 base_name += suffix;
3920 this_name += suffix;
3923 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3924 this_name, Modifiers.GetDescription (ma), base_name);
3927 protected static string Error722 {
3929 return "`{0}': static types cannot be used as return types";
3934 /// For custom member duplication search in a container
3936 protected abstract bool CheckForDuplications ();
3939 /// Gets base method and its return type
3941 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3944 // The "short" name of this property / indexer / event. This is the
3945 // name without the explicit interface.
3947 public string ShortName
3949 get { return MemberName.Name; }
3950 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3953 protected override bool VerifyClsCompliance ()
3955 if (!base.VerifyClsCompliance ()) {
3956 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3957 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3960 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3961 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3966 if (GenericMethod != null)
3967 GenericMethod.VerifyClsCompliance ();
3972 public override bool IsUsed
3974 get { return IsExplicitImpl || base.IsUsed; }
3979 public abstract class MethodOrOperator : MethodCore, IMethodData
3981 public MethodBuilder MethodBuilder;
3982 ReturnParameter return_attributes;
3983 ListDictionary declarative_security;
3984 protected MethodData MethodData;
3987 ArrayList anonymous_methods;
3989 static string[] attribute_targets = new string [] { "method", "return" };
3991 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3992 int allowed_mod, bool is_interface, MemberName name,
3993 Attributes attrs, Parameters parameters)
3994 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3999 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4001 if (a.Target == AttributeTargets.ReturnValue) {
4002 if (return_attributes == null)
4003 return_attributes = new ReturnParameter (MethodBuilder, Location);
4005 return_attributes.ApplyAttributeBuilder (a, cb);
4009 if (a.IsInternalMethodImplAttribute) {
4010 is_external_implementation = true;
4013 if (a.Type == TypeManager.dllimport_type) {
4014 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4015 if ((ModFlags & extern_static) != extern_static) {
4016 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4018 is_external_implementation = true;
4021 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4022 if (declarative_security == null)
4023 declarative_security = new ListDictionary ();
4024 a.ExtractSecurityPermissionSet (declarative_security);
4028 MethodBuilder.SetCustomAttribute (cb);
4031 public override AttributeTargets AttributeTargets {
4033 return AttributeTargets.Method;
4037 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
4039 return new EmitContext (
4040 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
4043 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4045 if (anonymous_methods == null)
4046 anonymous_methods = new ArrayList ();
4047 anonymous_methods.Add (anonymous);
4050 protected bool DefineGenericMethod ()
4052 if (!DoDefineBase ())
4056 if (GenericMethod != null) {
4057 string method_name = MemberName.Name;
4059 if (IsExplicitImpl) {
4060 method_name = TypeManager.CSharpName (InterfaceType) +
4065 MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags); //, ReturnType, null);
4067 MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags);
4070 if (!GenericMethod.Define (MethodBuilder, block))
4078 public bool ResolveMembers ()
4080 if (!DefineGenericMethod ())
4083 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
4084 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
4085 if (iterator == null)
4089 if (anonymous_methods != null) {
4090 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4091 if (!ame.CreateAnonymousHelpers ())
4099 public override bool Define ()
4104 if (!CheckAbstractAndExtern (block != null))
4110 MethodData = new MethodData (
4111 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
4113 if (!MethodData.Define (Parent.PartialContainer))
4116 MethodBuilder = MethodData.MethodBuilder;
4118 if (!TypeManager.IsGenericParameter (MemberType)) {
4119 if (MemberType.IsAbstract && MemberType.IsSealed) {
4120 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4128 public override void Emit ()
4131 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
4132 MethodBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
4134 if (OptAttributes != null)
4135 OptAttributes.Emit ();
4137 if (declarative_security != null) {
4138 foreach (DictionaryEntry de in declarative_security) {
4139 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4146 protected void Error_ConditionalAttributeIsNotValid ()
4148 Report.Error (577, Location,
4149 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4150 GetSignatureForError ());
4153 public override bool IsOverloadable {
4159 public override string[] ValidAttributeTargets {
4161 return attribute_targets;
4165 #region IMethodData Members
4167 public CallingConventions CallingConventions {
4169 CallingConventions cc = Parameters.CallingConvention;
4170 if (Parameters.HasArglist && block != null)
4171 block.HasVarargs = true;
4174 if ((ModFlags & Modifiers.STATIC) == 0)
4175 cc |= CallingConventions.HasThis;
4177 // FIXME: How is `ExplicitThis' used in C#?
4183 public Type ReturnType {
4189 public MemberName MethodName {
4195 public Iterator Iterator {
4196 get { return iterator; }
4199 public new Location Location {
4201 return base.Location;
4205 protected override bool CheckBase ()
4207 if (!base.CheckBase ())
4210 // TODO: Destructor should derive from MethodCore
4211 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4212 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4213 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4221 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4223 public bool IsExcluded () {
4224 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4225 return (caching_flags & Flags.Excluded) != 0;
4227 caching_flags &= ~Flags.Excluded_Undetected;
4229 if (base_method == null) {
4230 if (OptAttributes == null)
4233 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4238 foreach (Attribute a in attrs) {
4239 string condition = a.GetConditionalAttributeValue ();
4240 if (condition == null)
4243 if (RootContext.AllDefines.Contains (condition))
4247 caching_flags |= Flags.Excluded;
4251 IMethodData md = TypeManager.GetMethod (base_method);
4253 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4254 caching_flags |= Flags.Excluded;
4260 if (md.IsExcluded ()) {
4261 caching_flags |= Flags.Excluded;
4267 GenericMethod IMethodData.GenericMethod {
4269 return GenericMethod;
4277 public class SourceMethod : ISourceMethod
4282 protected SourceMethod (DeclSpace parent, MethodBase builder,
4283 ISourceFile file, Location start, Location end)
4285 this.parent = parent;
4286 this.builder = builder;
4288 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
4291 public string Name {
4292 get { return builder.Name; }
4295 public int NamespaceID {
4296 get { return parent.NamespaceEntry.SymbolFileID; }
4301 if (builder is MethodBuilder)
4302 return ((MethodBuilder) builder).GetToken ().Token;
4303 else if (builder is ConstructorBuilder)
4304 return ((ConstructorBuilder) builder).GetToken ().Token;
4306 throw new NotSupportedException ();
4310 public void CloseMethod ()
4312 if (CodeGen.SymbolWriter != null)
4313 CodeGen.SymbolWriter.CloseMethod ();
4316 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
4318 if (CodeGen.SymbolWriter == null)
4323 Location start_loc = block.StartLocation;
4324 if (start_loc.IsNull)
4327 Location end_loc = block.EndLocation;
4331 ISourceFile file = start_loc.SourceFile;
4335 return new SourceMethod (
4336 parent, builder, file, start_loc, end_loc);
4340 public class Method : MethodOrOperator, IAnonymousHost {
4343 /// Modifiers allowed in a class declaration
4345 const int AllowedModifiers =
4348 Modifiers.PROTECTED |
4349 Modifiers.INTERNAL |
4354 Modifiers.OVERRIDE |
4355 Modifiers.ABSTRACT |
4357 Modifiers.METHOD_YIELDS |
4360 const int AllowedInterfaceModifiers =
4361 Modifiers.NEW | Modifiers.UNSAFE;
4364 // return_type can be "null" for VOID values.
4366 public Method (DeclSpace parent, GenericMethod generic,
4367 Expression return_type, int mod, bool is_iface,
4368 MemberName name, Parameters parameters, Attributes attrs)
4369 : base (parent, generic, return_type, mod,
4370 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4371 is_iface, name, attrs, parameters)
4375 public override string GetSignatureForError()
4377 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4380 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4382 Report.Error (17, location,
4383 "Program `{0}' has more than one entry point defined: `{1}'",
4384 CodeGen.FileName, TypeManager.CSharpSignature(b));
4387 bool IsEntryPoint ()
4389 if (ReturnType != TypeManager.void_type &&
4390 ReturnType != TypeManager.int32_type)
4393 if (Parameters.Count == 0)
4396 if (Parameters.Count > 1)
4399 Type t = Parameters.ParameterType (0);
4400 return t.IsArray && t.GetArrayRank () == 1 &&
4401 TypeManager.GetElementType (t) == TypeManager.string_type &&
4402 (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4405 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4407 if (a.Type == TypeManager.conditional_attribute_type) {
4408 if (IsExplicitImpl) {
4409 Error_ConditionalAttributeIsNotValid ();
4413 if (ReturnType != TypeManager.void_type) {
4414 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4418 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4419 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4424 Report.Error (582, Location, "Conditional not valid on interface members");
4428 if (MethodData.implementing != null) {
4429 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4430 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4431 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4435 for (int i = 0; i < Parameters.Count; ++i) {
4436 if ((Parameters.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4437 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4443 if (a.Type == TypeManager.extension_attribute_type) {
4444 a.Error_MisusedExtensionAttribute ();
4448 base.ApplyAttributeBuilder (a, cb);
4451 protected override bool CheckForDuplications ()
4453 ArrayList ar = Parent.PartialContainer.Methods;
4455 int arLen = ar.Count;
4457 for (int i = 0; i < arLen; i++) {
4458 Method m = (Method) ar [i];
4459 if (IsDuplicateImplementation (m))
4464 ar = Parent.PartialContainer.Properties;
4466 for (int i = 0; i < ar.Count; ++i) {
4467 PropertyBase pb = (PropertyBase) ar [i];
4468 if (pb.AreAccessorsDuplicateImplementation (this))
4473 ar = Parent.PartialContainer.Indexers;
4475 for (int i = 0; i < ar.Count; ++i) {
4476 PropertyBase pb = (PropertyBase) ar [i];
4477 if (pb.AreAccessorsDuplicateImplementation (this))
4482 ar = Parent.PartialContainer.Events;
4484 for (int i = 0; i < ar.Count; ++i) {
4485 Event ev = (Event) ar [i];
4486 if (ev.AreAccessorsDuplicateImplementation (this))
4497 public override bool Define ()
4499 if (!base.Define ())
4502 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4503 Error1599 (Location, ReturnType);
4507 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4508 Name == "Finalize" && !(this is Destructor)) {
4509 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4512 if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4513 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4514 Parent.PartialContainer.Mark_HasEquals ();
4515 else if (Parameters.Empty && Name == "GetHashCode")
4516 Parent.PartialContainer.Mark_HasGetHashCode ();
4519 if ((ModFlags & Modifiers.STATIC) == 0)
4522 if (Parameters.HasExtensionMethodType) {
4523 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4524 if (!Parent.IsTopLevel)
4525 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4526 GetSignatureForError ());
4528 if (TypeManager.extension_attribute_type == null)
4529 Report.Error (1110, Location,
4530 "`{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",
4531 GetSignatureForError ());
4533 ModFlags |= Modifiers.METHOD_EXTENSION;
4534 Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4535 CodeGen.Assembly.HasExtensionMethods = true;
4537 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4538 GetSignatureForError ());
4543 // This is used to track the Entry Point,
4545 if (RootContext.NeedsEntryPoint &&
4547 (RootContext.MainClass == null ||
4548 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4549 if (IsEntryPoint ()) {
4551 if (RootContext.EntryPoint == null) {
4552 if (Parent.IsGeneric || MemberName.IsGeneric) {
4553 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4554 GetSignatureForError ());
4556 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4557 md.SetMemberIsUsed ();
4559 RootContext.EntryPoint = MethodBuilder;
4560 RootContext.EntryPointLocation = Location;
4563 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4564 Error_DuplicateEntryPoint (MethodBuilder, Location);
4567 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4568 GetSignatureForError ());
4578 public override void Emit ()
4581 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4582 MethodData.Emit (Parent);
4585 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4586 MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4591 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4592 Location, MethodBuilder);
4597 public static void Error1599 (Location loc, Type t)
4599 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4602 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4604 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4605 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4610 if (mi.IsSpecialName)
4613 base_ret_type = mi.ReturnType;
4617 protected override bool VerifyClsCompliance ()
4619 if (!base.VerifyClsCompliance ())
4622 if (ParameterInfo.Count > 0) {
4623 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4625 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4632 public abstract class ConstructorInitializer : Expression
4634 readonly ArrayList argument_list;
4635 MethodGroupExpr base_constructor_group;
4637 public ConstructorInitializer (ArrayList argument_list, Location loc)
4639 this.argument_list = argument_list;
4643 public ArrayList Arguments {
4645 return argument_list;
4649 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4651 if (argument_list != null){
4652 foreach (Argument a in argument_list){
4653 if (!a.Resolve (ec, loc))
4658 if (this is ConstructorBaseInitializer) {
4659 if (ec.ContainerType.BaseType == null)
4662 type = ec.ContainerType.BaseType;
4663 if (ec.ContainerType.IsValueType) {
4664 Report.Error (522, loc,
4665 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4670 // It is legal to have "this" initializers that take no arguments
4671 // in structs, they are just no-ops.
4673 // struct D { public D (int a) : this () {}
4675 if (ec.ContainerType.IsValueType && argument_list == null)
4678 type = ec.ContainerType;
4681 base_constructor_group = MemberLookupFinal (
4682 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4683 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4684 loc) as MethodGroupExpr;
4686 if (base_constructor_group == null)
4689 base_constructor_group = base_constructor_group.OverloadResolve (
4690 ec, argument_list, false, loc);
4692 if (base_constructor_group == null)
4695 ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4697 if (base_ctor == caller_builder){
4698 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4704 public override Expression DoResolve (EmitContext ec)
4706 throw new NotSupportedException ();
4709 public override void Emit (EmitContext ec)
4711 // It can be null for static initializers
4712 if (base_constructor_group == null)
4715 ec.Mark (loc, false);
4717 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4719 base_constructor_group.EmitCall (ec, argument_list);
4723 public class ConstructorBaseInitializer : ConstructorInitializer {
4724 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4725 base (argument_list, l)
4730 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4731 public GeneratedBaseInitializer (Location loc):
4737 public class ConstructorThisInitializer : ConstructorInitializer {
4738 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4739 base (argument_list, l)
4744 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4745 public ConstructorBuilder ConstructorBuilder;
4746 public ConstructorInitializer Initializer;
4747 ListDictionary declarative_security;
4748 ArrayList anonymous_methods;
4749 bool has_compliant_args;
4752 // Modifiers allowed for a constructor.
4754 public const int AllowedModifiers =
4756 Modifiers.PROTECTED |
4757 Modifiers.INTERNAL |
4763 static readonly string[] attribute_targets = new string [] { "method" };
4766 // The spec claims that static is not permitted, but
4767 // my very own code has static constructors.
4769 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4770 ConstructorInitializer init, Location loc)
4771 : base (parent, null, null, mod, AllowedModifiers, false,
4772 new MemberName (name, loc), null, args)
4777 public bool HasCompliantArgs {
4778 get { return has_compliant_args; }
4781 public override AttributeTargets AttributeTargets {
4782 get { return AttributeTargets.Constructor; }
4785 public Iterator Iterator {
4786 get { return null; }
4790 // Returns true if this is a default constructor
4792 public bool IsDefault ()
4794 if ((ModFlags & Modifiers.STATIC) != 0)
4795 return Parameters.Empty;
4797 return Parameters.Empty &&
4798 (Initializer is ConstructorBaseInitializer) &&
4799 (Initializer.Arguments == null);
4802 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4804 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4805 if (declarative_security == null) {
4806 declarative_security = new ListDictionary ();
4808 a.ExtractSecurityPermissionSet (declarative_security);
4812 if (a.IsInternalMethodImplAttribute) {
4813 is_external_implementation = true;
4816 ConstructorBuilder.SetCustomAttribute (cb);
4819 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4821 if (anonymous_methods == null)
4822 anonymous_methods = new ArrayList ();
4823 anonymous_methods.Add (anonymous);
4826 public bool ResolveMembers ()
4828 if (anonymous_methods != null) {
4829 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4830 if (!ame.CreateAnonymousHelpers ())
4838 protected override bool CheckForDuplications ()
4840 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4842 int arLen = ar.Count;
4844 for (int i = 0; i < arLen; i++) {
4845 Constructor m = (Constructor) ar [i];
4846 if (IsDuplicateImplementation (m))
4853 protected override bool CheckBase ()
4855 if ((ModFlags & Modifiers.STATIC) != 0) {
4856 if (!Parameters.Empty) {
4857 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4858 GetSignatureForError ());
4862 // the rest can be ignored
4866 // Check whether arguments were correct.
4867 if (!DefineParameters (Parameters))
4870 if (!CheckForDuplications ())
4873 if (Parent.PartialContainer.Kind == Kind.Struct) {
4874 if (ParameterTypes.Length == 0) {
4875 Report.Error (568, Location,
4876 "Structs cannot contain explicit parameterless constructors");
4880 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4881 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4886 if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0) {
4887 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4894 // Creates the ConstructorBuilder
4896 public override bool Define ()
4898 if (ConstructorBuilder != null)
4901 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4902 MethodAttributes.SpecialName);
4904 if ((ModFlags & Modifiers.STATIC) != 0) {
4905 ca |= MethodAttributes.Static | MethodAttributes.Private;
4907 ca |= MethodAttributes.HideBySig;
4909 if ((ModFlags & Modifiers.PUBLIC) != 0)
4910 ca |= MethodAttributes.Public;
4911 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4912 if ((ModFlags & Modifiers.INTERNAL) != 0)
4913 ca |= MethodAttributes.FamORAssem;
4915 ca |= MethodAttributes.Family;
4916 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4917 ca |= MethodAttributes.Assembly;
4919 ca |= MethodAttributes.Private;
4922 if (!CheckAbstractAndExtern (block != null))
4925 // Check if arguments were correct.
4929 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4930 ca, CallingConventions,
4933 if ((ModFlags & Modifiers.UNSAFE) != 0)
4934 ConstructorBuilder.InitLocals = false;
4936 if (Parent.PartialContainer.IsComImport) {
4937 if (!IsDefault ()) {
4938 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4939 Parent.GetSignatureForError ());
4942 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4945 TypeManager.AddMethod (ConstructorBuilder, this);
4953 public override void Emit ()
4955 if (OptAttributes != null)
4956 OptAttributes.Emit ();
4960 EmitContext ec = CreateEmitContext (null, null);
4963 // If we use a "this (...)" constructor initializer, then
4964 // do not emit field initializers, they are initialized in the other constructor
4966 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4967 !(Initializer is ConstructorThisInitializer);
4969 if (emit_field_initializers)
4970 Parent.PartialContainer.ResolveFieldInitializers (ec);
4972 if (block != null) {
4973 // If this is a non-static `struct' constructor and doesn't have any
4974 // initializer, it must initialize all of the struct's fields.
4975 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4976 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4977 block.AddThisVariable (Parent, Location);
4979 if (!block.ResolveMeta (ec, ParameterInfo))
4983 if ((ModFlags & Modifiers.STATIC) == 0){
4984 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4985 Initializer = new GeneratedBaseInitializer (Location);
4988 // Spec mandates that Initializers will not have
4992 if ((Initializer != null) &&
4993 !Initializer.Resolve (ConstructorBuilder, ec))
4995 ec.IsStatic = false;
4998 Parameters.ApplyAttributes (ConstructorBuilder);
5000 SourceMethod source = SourceMethod.Create (
5001 Parent, ConstructorBuilder, block);
5003 bool unreachable = false;
5004 if (block != null) {
5005 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
5008 ec.EmitMeta (block);
5010 if (Report.Errors > 0)
5013 if (emit_field_initializers)
5014 Parent.PartialContainer.EmitFieldInitializers (ec);
5016 if (block.ScopeInfo != null) {
5017 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
5018 init.EmitStatement (ec);
5021 if (Initializer != null)
5022 Initializer.Emit (ec);
5024 ec.EmitResolvedTopBlock (block, unreachable);
5028 source.CloseMethod ();
5030 if (declarative_security != null) {
5031 foreach (DictionaryEntry de in declarative_security) {
5032 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5039 // Is never override
5040 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5045 public override string GetSignatureForError()
5047 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
5050 public override string[] ValidAttributeTargets {
5052 return attribute_targets;
5056 protected override bool VerifyClsCompliance ()
5058 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
5062 if (ParameterInfo.Count > 0) {
5063 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
5065 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
5067 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
5068 foreach (Type param in ParameterTypes) {
5069 if (param.IsArray) {
5075 has_compliant_args = true;
5079 #region IMethodData Members
5081 public System.Reflection.CallingConventions CallingConventions {
5083 CallingConventions cc = Parameters.CallingConvention;
5085 if (Parent.PartialContainer.Kind == Kind.Class)
5086 if ((ModFlags & Modifiers.STATIC) == 0)
5087 cc |= CallingConventions.HasThis;
5089 // FIXME: How is `ExplicitThis' used in C#?
5095 public new Location Location {
5097 return base.Location;
5101 public MemberName MethodName {
5107 public Type ReturnType {
5113 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5115 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
5116 EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
5117 ec.CurrentBlock = block;
5121 public bool IsExcluded()
5126 GenericMethod IMethodData.GenericMethod {
5136 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
5138 public interface IMethodData
5140 CallingConventions CallingConventions { get; }
5141 Location Location { get; }
5142 MemberName MethodName { get; }
5143 Type ReturnType { get; }
5144 GenericMethod GenericMethod { get; }
5145 Parameters ParameterInfo { get; }
5147 Iterator Iterator { get; }
5149 Attributes OptAttributes { get; }
5150 ToplevelBlock Block { get; set; }
5152 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5153 ObsoleteAttribute GetObsoleteAttribute ();
5154 string GetSignatureForError ();
5156 bool IsClsComplianceRequired ();
5157 void SetMemberIsUsed ();
5161 // Encapsulates most of the Method's state
5163 public class MethodData {
5165 readonly IMethodData method;
5167 public readonly GenericMethod GenericMethod;
5170 // Are we implementing an interface ?
5172 public MethodInfo implementing;
5177 protected InterfaceMemberBase member;
5178 protected int modifiers;
5179 protected MethodAttributes flags;
5180 protected Type declaring_type;
5181 protected MethodInfo parent_method;
5183 MethodBuilder builder = null;
5184 public MethodBuilder MethodBuilder {
5190 public Type DeclaringType {
5192 return declaring_type;
5196 public MethodData (InterfaceMemberBase member,
5197 int modifiers, MethodAttributes flags, IMethodData method)
5199 this.member = member;
5200 this.modifiers = modifiers;
5203 this.method = method;
5206 public MethodData (InterfaceMemberBase member,
5207 int modifiers, MethodAttributes flags,
5208 IMethodData method, MethodBuilder builder,
5209 GenericMethod generic, MethodInfo parent_method)
5210 : this (member, modifiers, flags, method)
5212 this.builder = builder;
5213 this.GenericMethod = generic;
5214 this.parent_method = parent_method;
5217 public bool Define (DeclSpace parent)
5219 string name = method.MethodName.Basename;
5220 string method_name = method.MethodName.FullName;
5222 TypeContainer container = parent.PartialContainer;
5224 PendingImplementation pending = container.PendingImplementations;
5225 if (pending != null){
5226 if (member is Indexer) // TODO: test it, but it should work without this IF
5227 implementing = pending.IsInterfaceIndexer (
5228 member.InterfaceType, method.ReturnType, method.ParameterInfo);
5230 implementing = pending.IsInterfaceMethod (
5231 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5233 if (member.InterfaceType != null){
5234 if (implementing == null){
5235 if (member is PropertyBase) {
5236 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5237 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5238 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5241 Report.Error (539, method.Location,
5242 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5243 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5247 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5248 Report.SymbolRelatedToPreviousError (implementing);
5249 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5250 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5254 method_name = member.InterfaceType.FullName +
5257 if (implementing != null) {
5258 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5259 if (prop_method == null) {
5260 if (TypeManager.IsSpecialMethod (implementing)) {
5261 Report.SymbolRelatedToPreviousError (implementing);
5262 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5263 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5264 implementing.Name.StartsWith ("get_") ? "get" : "set");
5266 } else if (implementing.DeclaringType.IsInterface) {
5267 if (!implementing.IsSpecialName) {
5268 Report.SymbolRelatedToPreviousError (implementing);
5269 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5270 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5273 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5274 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5275 Report.SymbolRelatedToPreviousError (implementing);
5276 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5277 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5286 // For implicit implementations, make sure we are public, for
5287 // explicit implementations, make sure we are private.
5289 if (implementing != null){
5291 // Setting null inside this block will trigger a more
5292 // verbose error reporting for missing interface implementations
5294 // The "candidate" function has been flagged already
5295 // but it wont get cleared
5297 if (member.IsExplicitImpl){
5298 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5299 Report.SymbolRelatedToPreviousError (implementing);
5300 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5301 method.GetSignatureForError ());
5305 if (implementing.DeclaringType.IsInterface) {
5307 // If this is an interface method implementation,
5308 // check for public accessibility
5310 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
5312 implementing = null;
5314 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5315 // We may never be private.
5316 implementing = null;
5318 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5320 // We may be protected if we're overriding something.
5322 implementing = null;
5327 // Static is not allowed
5329 if ((modifiers & Modifiers.STATIC) != 0){
5330 implementing = null;
5335 // If implementing is still valid, set flags
5337 if (implementing != null){
5339 // When implementing interface methods, set NewSlot
5340 // unless, we are overwriting a method.
5342 if (implementing.DeclaringType.IsInterface){
5343 if ((modifiers & Modifiers.OVERRIDE) == 0)
5344 flags |= MethodAttributes.NewSlot;
5347 MethodAttributes.Virtual |
5348 MethodAttributes.HideBySig;
5350 // Set Final unless we're virtual, abstract or already overriding a method.
5351 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5352 flags |= MethodAttributes.Final;
5355 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
5357 if (builder == null)
5360 if (container.CurrentType != null)
5361 declaring_type = container.CurrentType;
5363 declaring_type = container.TypeBuilder;
5365 if ((modifiers & Modifiers.UNSAFE) != 0)
5366 builder.InitLocals = false;
5369 if (implementing != null){
5371 // clear the pending implemntation flag
5373 if (member is Indexer) {
5374 pending.ImplementIndexer (
5375 member.InterfaceType, builder, method.ReturnType,
5376 method.ParameterInfo, member.IsExplicitImpl);
5378 pending.ImplementMethod (
5379 member.InterfaceType, name, method.ReturnType,
5380 method.ParameterInfo, member.IsExplicitImpl);
5382 if (member.IsExplicitImpl)
5383 container.TypeBuilder.DefineMethodOverride (
5384 builder, implementing);
5387 TypeManager.AddMethod (builder, method);
5389 if (GenericMethod != null) {
5390 bool is_override = member.IsExplicitImpl |
5391 ((modifiers & Modifiers.OVERRIDE) != 0);
5393 if (implementing != null)
5394 parent_method = implementing;
5396 EmitContext ec = method.CreateEmitContext (container, null);
5397 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5406 /// Create the MethodBuilder for the method
5408 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5410 if (builder == null) {
5411 builder = container.TypeBuilder.DefineMethod (
5412 method_name, flags, method.CallingConventions,
5413 method.ReturnType, ParameterTypes);
5417 #if GMCS_SOURCE && !MS_COMPATIBLE
5418 builder.SetGenericMethodSignature (
5419 flags, method.CallingConventions,
5420 method.ReturnType, ParameterTypes);
5427 public void Emit (DeclSpace parent)
5429 ToplevelBlock block = method.Block;
5433 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5435 ec = method.CreateEmitContext (parent, null);
5437 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5439 if (GenericMethod != null)
5440 GenericMethod.EmitAttributes ();
5442 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5445 // Handle destructors specially
5447 // FIXME: This code generates buggy code
5449 if (member is Destructor)
5450 EmitDestructor (ec, block);
5452 ec.EmitTopBlock (method, block);
5455 source.CloseMethod ();
5458 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5460 ILGenerator ig = ec.ig;
5462 Label finish = ig.DefineLabel ();
5464 block.SetDestructor ();
5466 ig.BeginExceptionBlock ();
5467 ec.ReturnLabel = finish;
5468 ec.HasReturnLabel = true;
5469 ec.EmitTopBlock (method, block);
5471 // ig.MarkLabel (finish);
5472 ig.BeginFinallyBlock ();
5474 if (ec.ContainerType.BaseType != null) {
5475 Expression member_lookup = Expression.MemberLookup (
5476 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5477 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5479 if (member_lookup != null){
5480 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5482 ig.Emit (OpCodes.Ldarg_0);
5483 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5487 ig.EndExceptionBlock ();
5488 //ig.MarkLabel (ec.ReturnLabel);
5489 ig.Emit (OpCodes.Ret);
5493 // TODO: Should derive from MethodCore
5494 public class Destructor : Method {
5496 static string[] attribute_targets = new string [] { "method" };
5498 public Destructor (DeclSpace parent, Expression return_type, int mod,
5499 string name, Parameters parameters, Attributes attrs,
5501 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5505 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5507 if (a.Type == TypeManager.conditional_attribute_type) {
5508 Error_ConditionalAttributeIsNotValid ();
5512 base.ApplyAttributeBuilder (a, cb);
5515 public override string GetSignatureForError ()
5517 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5520 public override string[] ValidAttributeTargets {
5522 return attribute_targets;
5527 abstract public class MemberBase : MemberCore {
5528 public Expression Type;
5529 public readonly DeclSpace ds;
5530 public readonly GenericMethod GenericMethod;
5533 // The type of this property / indexer / event
5535 protected Type member_type;
5536 public Type MemberType {
5538 if (member_type == null && Type != null) {
5539 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5540 Type = Type.ResolveAsTypeTerminal (rc, false);
5542 member_type = Type.Type;
5550 // The constructor is only exposed to our children
5552 protected MemberBase (DeclSpace parent, GenericMethod generic,
5553 Expression type, int mod, int allowed_mod, int def_mod,
5554 MemberName name, Attributes attrs)
5555 : base (parent, name, attrs)
5557 this.ds = generic != null ? generic : (DeclSpace) parent;
5559 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5560 GenericMethod = generic;
5561 if (GenericMethod != null)
5562 GenericMethod.ModFlags = ModFlags;
5565 protected virtual bool CheckBase ()
5567 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5568 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5572 if (Report.WarningLevel >= 4 &&
5573 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5574 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5575 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5576 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5581 protected virtual bool DoDefine ()
5583 if (MemberType == null)
5586 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5587 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5588 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5589 GetSignatureForError (), Parent.GetSignatureForError ());
5593 // verify accessibility
5594 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5595 Report.SymbolRelatedToPreviousError (MemberType);
5596 if (this is Property)
5597 Report.Error (53, Location,
5598 "Inconsistent accessibility: property type `" +
5599 TypeManager.CSharpName (MemberType) + "' is less " +
5600 "accessible than property `" + GetSignatureForError () + "'");
5601 else if (this is Indexer)
5602 Report.Error (54, Location,
5603 "Inconsistent accessibility: indexer return type `" +
5604 TypeManager.CSharpName (MemberType) + "' is less " +
5605 "accessible than indexer `" + GetSignatureForError () + "'");
5606 else if (this is MethodCore) {
5607 if (this is Operator)
5608 Report.Error (56, Location,
5609 "Inconsistent accessibility: return type `" +
5610 TypeManager.CSharpName (MemberType) + "' is less " +
5611 "accessible than operator `" + GetSignatureForError () + "'");
5613 Report.Error (50, Location,
5614 "Inconsistent accessibility: return type `" +
5615 TypeManager.CSharpName (MemberType) + "' is less " +
5616 "accessible than method `" + GetSignatureForError () + "'");
5618 Report.Error (52, Location,
5619 "Inconsistent accessibility: field type `" +
5620 TypeManager.CSharpName (MemberType) + "' is less " +
5621 "accessible than field `" + GetSignatureForError () + "'");
5629 protected bool IsTypePermitted ()
5631 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5632 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5640 // Abstract class for all fields
5642 abstract public class FieldBase : MemberBase {
5643 public FieldBuilder FieldBuilder;
5644 public Status status;
5645 protected Expression initializer;
5648 public enum Status : byte {
5649 HAS_OFFSET = 4 // Used by FieldMember.
5652 static readonly string[] attribute_targets = new string [] { "field" };
5654 protected FieldBase (DeclSpace parent, Expression type, int mod,
5655 int allowed_mod, MemberName name, Attributes attrs)
5656 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5659 if ((mod & Modifiers.ABSTRACT) != 0)
5660 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5663 public override AttributeTargets AttributeTargets {
5665 return AttributeTargets.Field;
5669 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5671 if (a.Type == TypeManager.field_offset_attribute_type) {
5672 status |= Status.HAS_OFFSET;
5674 if (!Parent.PartialContainer.HasExplicitLayout) {
5675 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5679 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5680 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5686 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5687 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5692 if (a.Type == TypeManager.marshal_as_attr_type) {
5693 UnmanagedMarshal marshal = a.GetMarshal (this);
5694 if (marshal != null) {
5695 FieldBuilder.SetMarshal (marshal);
5700 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5701 a.Error_InvalidSecurityParent ();
5705 FieldBuilder.SetCustomAttribute (cb);
5708 protected override bool CheckBase ()
5710 if (!base.CheckBase ())
5713 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5714 if (conflict_symbol == null) {
5715 if ((ModFlags & Modifiers.NEW) != 0) {
5716 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5721 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5722 Report.SymbolRelatedToPreviousError (conflict_symbol);
5723 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5724 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5730 public override bool Define()
5732 if (MemberType == null || Type == null)
5735 if (TypeManager.IsGenericParameter (MemberType))
5738 if (MemberType == TypeManager.void_type) {
5739 // TODO: wrong location
5740 Expression.Error_VoidInvalidInTheContext (Location);
5744 if (MemberType.IsSealed && MemberType.IsAbstract) {
5745 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5752 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5753 Report.Error (52, Location,
5754 "Inconsistent accessibility: field type `" +
5755 TypeManager.CSharpName (MemberType) + "' is less " +
5756 "accessible than field `" + GetSignatureForError () + "'");
5760 if (!IsTypePermitted ())
5767 // Represents header string for documentation comment.
5769 public override string DocCommentHeader {
5770 get { return "F:"; }
5773 public override void Emit ()
5776 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0) {
5777 FieldBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
5781 if (OptAttributes != null) {
5782 OptAttributes.Emit ();
5785 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5786 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5792 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5794 Report.SymbolRelatedToPreviousError (static_class);
5795 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5799 public Expression Initializer {
5801 if (value != null) {
5802 this.initializer = value;
5807 protected virtual bool IsFieldClsCompliant {
5809 if (FieldBuilder == null)
5812 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5816 public override string[] ValidAttributeTargets
5819 return attribute_targets;
5823 protected override bool VerifyClsCompliance ()
5825 if (!base.VerifyClsCompliance ())
5828 if (!IsFieldClsCompliant) {
5829 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5834 public void SetAssigned ()
5836 caching_flags |= Flags.IsAssigned;
5840 interface IFixedBuffer
5842 FieldInfo Element { get; }
5843 Type ElementType { get; }
5846 public class FixedFieldExternal: IFixedBuffer
5848 FieldInfo element_field;
5850 public FixedFieldExternal (FieldInfo fi)
5852 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5855 #region IFixedField Members
5857 public FieldInfo Element {
5859 return element_field;
5863 public Type ElementType {
5865 return element_field.FieldType;
5873 /// Fixed buffer implementation
5875 public class FixedField : FieldBase, IFixedBuffer
5877 public const string FixedElementName = "FixedElementField";
5878 static int GlobalCounter = 0;
5879 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5880 static FieldInfo[] fi;
5882 TypeBuilder fixed_buffer_type;
5883 FieldBuilder element;
5884 Expression size_expr;
5887 const int AllowedModifiers =
5890 Modifiers.PROTECTED |
5891 Modifiers.INTERNAL |
5894 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5895 Expression size_expr, Attributes attrs, Location loc):
5896 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5898 if (RootContext.Version == LanguageVersion.ISO_1)
5899 Report.FeatureIsNotISO1 (loc, "fixed size buffers");
5901 this.size_expr = size_expr;
5904 public override bool Define()
5907 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5908 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5911 if (Parent.PartialContainer.Kind != Kind.Struct) {
5912 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5913 GetSignatureForError ());
5916 if (!Parent.IsInUnsafeScope)
5917 Expression.UnsafeError (Location);
5919 if (!base.Define ())
5922 if (!TypeManager.IsPrimitiveType (MemberType)) {
5923 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",
5924 GetSignatureForError ());
5928 EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5929 Constant c = size_expr.ResolveAsConstant (ec, this);
5933 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5934 if (buffer_size_const == null)
5937 buffer_size = buffer_size_const.Value;
5939 if (buffer_size <= 0) {
5940 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5944 int type_size = Expression.GetTypeSize (MemberType);
5946 if (buffer_size > int.MaxValue / type_size) {
5947 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5948 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5952 buffer_size *= type_size;
5955 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5957 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5958 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5959 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5960 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5962 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5963 TypeManager.RegisterFieldBase (FieldBuilder, this);
5968 public override void Emit()
5971 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5973 object[] fi_val = new object[1];
5974 fi_val [0] = buffer_size;
5976 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5977 ctor_args, fi, fi_val);
5978 fixed_buffer_type.SetCustomAttribute (cab);
5981 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5982 FieldBuilder.SetCustomAttribute (cab);
5987 protected override bool IsFieldClsCompliant {
5993 #region IFixedField Members
5995 public FieldInfo Element {
6001 public Type ElementType {
6011 // The Field class is used to represents class/struct fields during parsing.
6013 public class Field : FieldBase {
6015 // Modifiers allowed in a class declaration
6017 const int AllowedModifiers =
6020 Modifiers.PROTECTED |
6021 Modifiers.INTERNAL |
6024 Modifiers.VOLATILE |
6028 public Field (DeclSpace parent, Expression type, int mod, string name,
6029 Attributes attrs, Location loc)
6030 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6035 public override bool Define ()
6037 if (!base.Define ())
6040 if ((ModFlags & Modifiers.VOLATILE) != 0){
6041 if (!MemberType.IsClass){
6042 Type vt = MemberType;
6044 if (TypeManager.IsEnumType (vt))
6045 vt = TypeManager.EnumToUnderlying (MemberType);
6047 if (!((vt == TypeManager.bool_type) ||
6048 (vt == TypeManager.sbyte_type) ||
6049 (vt == TypeManager.byte_type) ||
6050 (vt == TypeManager.short_type) ||
6051 (vt == TypeManager.ushort_type) ||
6052 (vt == TypeManager.int32_type) ||
6053 (vt == TypeManager.uint32_type) ||
6054 (vt == TypeManager.char_type) ||
6055 (vt == TypeManager.float_type) ||
6056 (!vt.IsValueType))){
6057 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6058 GetSignatureForError (), TypeManager.CSharpName (vt));
6063 if ((ModFlags & Modifiers.READONLY) != 0){
6064 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6065 GetSignatureForError ());
6070 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6072 if (Parent.PartialContainer.Kind == Kind.Struct &&
6073 ((fa & FieldAttributes.Static) == 0) &&
6074 MemberType == Parent.TypeBuilder &&
6075 !TypeManager.IsBuiltinType (MemberType)){
6076 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6077 "' causes a cycle in the structure layout");
6082 FieldBuilder = Parent.TypeBuilder.DefineField (
6083 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6085 TypeManager.RegisterFieldBase (FieldBuilder, this);
6087 catch (ArgumentException) {
6088 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6092 if (initializer != null)
6093 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
6094 new FieldInitializer (FieldBuilder, initializer));
6098 protected override bool VerifyClsCompliance ()
6100 if (!base.VerifyClsCompliance ())
6103 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6104 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6112 // `set' and `get' accessors are represented with an Accessor.
6114 public class Accessor : IAnonymousHost {
6116 // Null if the accessor is empty, or a Block if not
6118 public const int AllowedModifiers =
6120 Modifiers.PROTECTED |
6121 Modifiers.INTERNAL |
6124 public ToplevelBlock Block;
6125 public Attributes Attributes;
6126 public Location Location;
6127 public int ModFlags;
6129 public ArrayList AnonymousMethods;
6131 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6136 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6139 public void SetYields ()
6144 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6146 if (AnonymousMethods == null)
6147 AnonymousMethods = new ArrayList ();
6148 AnonymousMethods.Add (ame);
6152 // Ooouh Martin, templates are missing here.
6153 // When it will be possible move here a lot of child code and template method type.
6154 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6155 protected MethodData method_data;
6156 protected ToplevelBlock block;
6157 protected ListDictionary declarative_security;
6159 // The accessor are created event if they are not wanted.
6160 // But we need them because their names are reserved.
6161 // Field says whether accessor will be emited or not
6162 public readonly bool IsDummy;
6164 protected readonly string prefix;
6166 ReturnParameter return_attributes;
6168 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
6169 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6171 this.prefix = prefix;
6175 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
6177 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6178 accessor.Attributes)
6180 this.prefix = prefix;
6181 this.block = accessor.Block;
6184 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
6186 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6189 public void UpdateName (InterfaceMemberBase member)
6191 SetMemberName (SetupName (prefix, member, Location));
6194 #region IMethodData Members
6196 public abstract Iterator Iterator {
6200 public ToplevelBlock Block {
6210 public CallingConventions CallingConventions {
6212 return CallingConventions.Standard;
6216 public bool IsExcluded ()
6221 GenericMethod IMethodData.GenericMethod {
6227 public MemberName MethodName {
6233 public Type[] ParameterTypes {
6235 return ParameterInfo.Types;
6239 public abstract Parameters ParameterInfo { get ; }
6240 public abstract Type ReturnType { get; }
6241 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6245 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6247 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6248 a.Type == TypeManager.conditional_attribute_type) {
6249 Report.Error (1667, a.Location,
6250 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6251 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6255 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6256 if (declarative_security == null)
6257 declarative_security = new ListDictionary ();
6258 a.ExtractSecurityPermissionSet (declarative_security);
6262 if (a.Target == AttributeTargets.Method) {
6263 method_data.MethodBuilder.SetCustomAttribute (cb);
6267 if (a.Target == AttributeTargets.ReturnValue) {
6268 if (return_attributes == null)
6269 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6271 return_attributes.ApplyAttributeBuilder (a, cb);
6275 ApplyToExtraTarget (a, cb);
6278 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6280 throw new NotSupportedException ("You forgot to define special attribute target handling");
6283 // It is not supported for the accessors
6284 public sealed override bool Define()
6286 throw new NotSupportedException ();
6289 public void Emit (DeclSpace parent)
6291 EmitMethod (parent);
6294 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0)
6295 method_data.MethodBuilder.SetCustomAttribute (TypeManager.compiler_generated_attr);
6297 if (OptAttributes != null)
6298 OptAttributes.Emit ();
6300 if (declarative_security != null) {
6301 foreach (DictionaryEntry de in declarative_security) {
6302 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6309 protected virtual void EmitMethod (DeclSpace parent)
6311 method_data.Emit (parent);
6314 public override bool IsClsComplianceRequired()
6319 public bool IsDuplicateImplementation (MethodCore method)
6321 if (!MemberName.Equals (method.MemberName))
6324 Type[] param_types = method.ParameterTypes;
6326 if (param_types == null || param_types.Length != ParameterTypes.Length)
6329 for (int i = 0; i < param_types.Length; i++)
6330 if (param_types [i] != ParameterTypes [i])
6333 Report.SymbolRelatedToPreviousError (method);
6334 Report.Error (82, Location, "A member `{0}' is already reserved",
6335 method.GetSignatureForError ());
6339 public override bool IsUsed
6349 public new Location Location {
6351 return base.Location;
6355 public virtual bool ResolveMembers ()
6361 // Represents header string for documentation comment.
6363 public override string DocCommentHeader {
6364 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6370 // Properties and Indexers both generate PropertyBuilders, we use this to share
6371 // their common bits.
6373 abstract public class PropertyBase : PropertyBasedMember {
6375 public class GetMethod : PropertyMethod
6377 static string[] attribute_targets = new string [] { "method", "return" };
6379 public GetMethod (PropertyBase method):
6380 base (method, "get_")
6384 public GetMethod (PropertyBase method, Accessor accessor):
6385 base (method, accessor, "get_")
6389 public override MethodBuilder Define (DeclSpace parent)
6391 if (!CheckForDuplications ())
6397 base.Define (parent);
6399 method_data = new MethodData (method, ModFlags, flags, this);
6401 if (!method_data.Define (parent))
6404 return method_data.MethodBuilder;
6407 public override Type ReturnType {
6409 return method.MemberType;
6413 public override Parameters ParameterInfo {
6415 return Parameters.EmptyReadOnlyParameters;
6419 public override string[] ValidAttributeTargets {
6421 return attribute_targets;
6426 public class SetMethod : PropertyMethod {
6428 static string[] attribute_targets = new string [] { "method", "param", "return" };
6429 ImplicitParameter param_attr;
6430 protected Parameters parameters;
6432 public SetMethod (PropertyBase method):
6433 base (method, "set_")
6437 public SetMethod (PropertyBase method, Accessor accessor):
6438 base (method, accessor, "set_")
6442 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6444 if (a.Target == AttributeTargets.Parameter) {
6445 if (param_attr == null)
6446 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6448 param_attr.ApplyAttributeBuilder (a, cb);
6452 base.ApplyAttributeBuilder (a, cb);
6455 public override Parameters ParameterInfo {
6457 if (parameters == null)
6458 DefineParameters ();
6463 protected virtual void DefineParameters ()
6465 parameters = Parameters.CreateFullyResolved (
6466 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location));
6469 public override MethodBuilder Define (DeclSpace parent)
6471 if (!CheckForDuplications ())
6477 base.Define (parent);
6479 method_data = new MethodData (method, ModFlags, flags, this);
6481 if (!method_data.Define (parent))
6484 return method_data.MethodBuilder;
6487 public override Type ReturnType {
6489 return TypeManager.void_type;
6493 public override string[] ValidAttributeTargets {
6495 return attribute_targets;
6500 static string[] attribute_targets = new string [] { "property" };
6502 public abstract class PropertyMethod : AbstractPropertyEventMethod
6504 protected readonly PropertyBase method;
6505 protected MethodAttributes flags;
6507 ArrayList anonymous_methods;
6510 public PropertyMethod (PropertyBase method, string prefix)
6511 : base (method, prefix)
6513 this.method = method;
6516 public PropertyMethod (PropertyBase method, Accessor accessor,
6518 : base (method, accessor, prefix)
6520 this.method = method;
6521 this.ModFlags = accessor.ModFlags;
6522 yields = accessor.Yields;
6523 anonymous_methods = accessor.AnonymousMethods;
6525 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6526 Report.FeatureIsNotISO1 (Location, "access modifiers on properties");
6530 public override Iterator Iterator {
6531 get { return iterator; }
6534 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6536 if (a.IsInternalMethodImplAttribute) {
6537 method.is_external_implementation = true;
6540 base.ApplyAttributeBuilder (a, cb);
6543 public override AttributeTargets AttributeTargets {
6545 return AttributeTargets.Method;
6549 public override bool IsClsComplianceRequired ()
6551 return method.IsClsComplianceRequired ();
6554 public override bool ResolveMembers ()
6557 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6558 if (iterator == null)
6562 if (anonymous_methods != null) {
6563 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6564 if (!ame.CreateAnonymousHelpers ())
6572 public virtual MethodBuilder Define (DeclSpace parent)
6574 TypeContainer container = parent.PartialContainer;
6577 // Check for custom access modifier
6579 if ((ModFlags & Modifiers.Accessibility) == 0) {
6580 ModFlags |= method.ModFlags;
6581 flags = method.flags;
6583 if (container.Kind == Kind.Interface)
6584 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6585 GetSignatureForError ());
6587 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6588 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6591 CheckModifiers (ModFlags);
6592 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6593 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6594 flags = Modifiers.MethodAttr (ModFlags);
6595 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6598 CheckAbstractAndExtern (block != null);
6602 public bool HasCustomAccessModifier
6605 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6609 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6611 return new EmitContext (method,
6612 ds, method.ds, method.Location, ig, ReturnType,
6613 method.ModFlags, false);
6616 public override ObsoleteAttribute GetObsoleteAttribute ()
6618 return method.GetObsoleteAttribute ();
6621 public override string GetSignatureForError()
6623 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6626 void CheckModifiers (int modflags)
6628 modflags &= Modifiers.Accessibility;
6630 int mflags = method.ModFlags & Modifiers.Accessibility;
6632 if ((mflags & Modifiers.PUBLIC) != 0) {
6633 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6635 else if ((mflags & Modifiers.PROTECTED) != 0) {
6636 if ((mflags & Modifiers.INTERNAL) != 0)
6637 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6639 flags |= Modifiers.PRIVATE;
6641 else if ((mflags & Modifiers.INTERNAL) != 0)
6642 flags |= Modifiers.PRIVATE;
6644 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6645 Report.Error (273, Location,
6646 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6647 GetSignatureForError (), method.GetSignatureForError ());
6651 public override bool IsOverloadable {
6657 protected bool CheckForDuplications ()
6659 if ((caching_flags & Flags.TestMethodDuplication) == 0)
6662 ArrayList ar = Parent.PartialContainer.Methods;
6664 int arLen = ar.Count;
6666 for (int i = 0; i < arLen; i++) {
6667 Method m = (Method) ar [i];
6668 if (IsDuplicateImplementation (m))
6677 public PropertyMethod Get, Set;
6678 public PropertyBuilder PropertyBuilder;
6679 public MethodBuilder GetBuilder, SetBuilder;
6681 protected bool define_set_first = false;
6683 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6684 int allowed_mod, bool is_iface, MemberName name,
6685 Attributes attrs, bool define_set_first)
6686 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
6688 this.define_set_first = define_set_first;
6691 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6693 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6694 a.Error_InvalidSecurityParent ();
6698 PropertyBuilder.SetCustomAttribute (cb);
6701 public override AttributeTargets AttributeTargets {
6703 return AttributeTargets.Property;
6707 public override bool Define ()
6712 if (!IsTypePermitted ())
6718 protected override bool DoDefine ()
6720 if (!base.DoDefine ())
6724 // Accessors modifiers check
6726 if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6727 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6728 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6729 GetSignatureForError ());
6733 if ((Get.IsDummy || Set.IsDummy)
6734 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6735 Report.Error (276, Location,
6736 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6737 GetSignatureForError ());
6742 if (MemberType.IsGenericParameter)
6746 if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6747 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6756 GetBuilder = Get.Define (Parent);
6757 return (Get.IsDummy) ? true : GetBuilder != null;
6760 bool DefineSet (bool define)
6765 SetBuilder = Set.Define (Parent);
6766 return (Set.IsDummy) ? true : SetBuilder != null;
6769 protected bool DefineAccessors ()
6771 return DefineSet (define_set_first) &&
6773 DefineSet (!define_set_first);
6776 protected abstract PropertyInfo ResolveBaseProperty ();
6778 // TODO: rename to Resolve......
6779 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6781 PropertyInfo base_property = ResolveBaseProperty ();
6782 if (base_property == null)
6785 base_ret_type = base_property.PropertyType;
6786 MethodInfo get_accessor = base_property.GetGetMethod (true);
6787 MethodInfo set_accessor = base_property.GetSetMethod (true);
6788 MethodAttributes get_accessor_access, set_accessor_access;
6790 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6791 if (Get != null && !Get.IsDummy && get_accessor == null) {
6792 Report.SymbolRelatedToPreviousError (base_property);
6793 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6796 if (Set != null && !Set.IsDummy && set_accessor == null) {
6797 Report.SymbolRelatedToPreviousError (base_property);
6798 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6803 // Check base class accessors access
6806 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6807 get_accessor_access = set_accessor_access = 0;
6808 if ((ModFlags & Modifiers.NEW) == 0) {
6809 if (get_accessor != null) {
6810 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6811 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6813 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6814 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6817 if (set_accessor != null) {
6818 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6819 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6821 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6822 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6826 // When one accessor does not exist and property hides base one
6827 // we need to propagate this upwards
6828 if (set_accessor == null)
6829 set_accessor = get_accessor;
6832 // Get the less restrictive access
6834 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6837 public override void Emit ()
6840 // The PropertyBuilder can be null for explicit implementations, in that
6841 // case, we do not actually emit the ".property", so there is nowhere to
6842 // put the attribute
6844 if (PropertyBuilder != null && OptAttributes != null)
6845 OptAttributes.Emit ();
6857 /// Tests whether accessors are not in collision with some method (CS0111)
6859 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6861 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6864 public override bool IsUsed
6870 return Get.IsUsed | Set.IsUsed;
6874 protected override void SetMemberName (MemberName new_name)
6876 base.SetMemberName (new_name);
6878 Get.UpdateName (this);
6879 Set.UpdateName (this);
6882 public override string[] ValidAttributeTargets {
6884 return attribute_targets;
6889 // Represents header string for documentation comment.
6891 public override string DocCommentHeader {
6892 get { return "P:"; }
6896 public class Property : PropertyBase {
6897 const int AllowedModifiers =
6900 Modifiers.PROTECTED |
6901 Modifiers.INTERNAL |
6905 Modifiers.OVERRIDE |
6906 Modifiers.ABSTRACT |
6909 Modifiers.METHOD_YIELDS |
6912 const int AllowedInterfaceModifiers =
6915 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6918 Field field = new Field (
6920 Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & Modifiers.STATIC),
6921 CompilerGeneratedClass.MakeName (null, "CompilerGeneratedField"),
6923 ((TypeContainer)Parent).AddField (field);
6926 get_block.Block = new ToplevelBlock (block, null, Location);
6927 Return r = new Return (new SimpleName(field.Name, Location), Location);
6928 get_block.Block.AddStatement (r);
6929 get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6932 Parameters parameters = new Parameters (new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location));
6933 set_block.Block = new ToplevelBlock (block, parameters, Location);
6934 Assign a = new Assign (new SimpleName(field.Name, Location), new SimpleName ("value", Location));
6935 set_block.Block.AddStatement (new StatementExpression(a));
6936 set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6939 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6940 MemberName name, Attributes attrs, Accessor get_block,
6941 Accessor set_block, bool define_set_first)
6942 : this (parent, type, mod, is_iface, name, attrs, get_block, set_block,
6943 define_set_first, null)
6947 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6948 MemberName name, Attributes attrs, Accessor get_block,
6949 Accessor set_block, bool define_set_first, Block current_block)
6950 : base (parent, type, mod,
6951 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6952 is_iface, name, attrs, define_set_first)
6954 if (RootContext.Version >= LanguageVersion.LINQ &&
6956 (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6957 get_block != null && get_block.Block == null &&
6958 set_block != null && set_block.Block == null)
6959 CreateAutomaticProperty (current_block, get_block, set_block);
6961 if (get_block == null)
6962 Get = new GetMethod (this);
6964 Get = new GetMethod (this, get_block);
6966 if (set_block == null)
6967 Set = new SetMethod (this);
6969 Set = new SetMethod (this, set_block);
6972 public override bool Define ()
6974 if (!DoDefineBase ())
6977 if (!base.Define ())
6983 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6985 if (!DefineAccessors ())
6988 // FIXME - PropertyAttributes.HasDefault ?
6990 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6991 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6994 PropertyBuilder.SetGetMethod (GetBuilder);
6997 PropertyBuilder.SetSetMethod (SetBuilder);
6999 TypeManager.RegisterProperty (PropertyBuilder, this);
7003 protected override PropertyInfo ResolveBaseProperty ()
7005 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7006 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
7011 /// Gigantic workaround for lameness in SRE follows :
7012 /// This class derives from EventInfo and attempts to basically
7013 /// wrap around the EventBuilder so that FindMembers can quickly
7014 /// return this in it search for members
7016 public class MyEventBuilder : EventInfo {
7019 // We use this to "point" to our Builder which is
7020 // not really a MemberInfo
7022 EventBuilder MyBuilder;
7025 // We "catch" and wrap these methods
7027 MethodInfo raise, remove, add;
7029 EventAttributes attributes;
7030 Type declaring_type, reflected_type, event_type;
7035 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7037 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7039 // And now store the values in our own fields.
7041 declaring_type = type_builder;
7043 reflected_type = type_builder;
7045 attributes = event_attr;
7048 this.event_type = event_type;
7052 // Methods that you have to override. Note that you only need
7053 // to "implement" the variants that take the argument (those are
7054 // the "abstract" methods, the others (GetAddMethod()) are
7057 public override MethodInfo GetAddMethod (bool nonPublic)
7062 public override MethodInfo GetRemoveMethod (bool nonPublic)
7067 public override MethodInfo GetRaiseMethod (bool nonPublic)
7073 // These methods make "MyEventInfo" look like a Builder
7075 public void SetRaiseMethod (MethodBuilder raiseMethod)
7077 raise = raiseMethod;
7078 MyBuilder.SetRaiseMethod (raiseMethod);
7081 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7083 remove = removeMethod;
7084 MyBuilder.SetRemoveOnMethod (removeMethod);
7087 public void SetAddOnMethod (MethodBuilder addMethod)
7090 MyBuilder.SetAddOnMethod (addMethod);
7093 public void SetCustomAttribute (CustomAttributeBuilder cb)
7095 MyBuilder.SetCustomAttribute (cb);
7098 public override object [] GetCustomAttributes (bool inherit)
7100 // FIXME : There's nothing which can be seemingly done here because
7101 // we have no way of getting at the custom attribute objects of the
7106 public override object [] GetCustomAttributes (Type t, bool inherit)
7108 // FIXME : Same here !
7112 public override bool IsDefined (Type t, bool b)
7117 public override EventAttributes Attributes {
7123 public override string Name {
7129 public override Type DeclaringType {
7131 return declaring_type;
7135 public override Type ReflectedType {
7137 return reflected_type;
7141 public Type EventType {
7147 public void SetUsed ()
7149 if (my_event != null) {
7150 // my_event.SetAssigned ();
7151 my_event.SetMemberIsUsed ();
7157 /// For case when event is declared like property (with add and remove accessors).
7159 public class EventProperty: Event {
7160 abstract class AEventPropertyAccessor : AEventAccessor
7162 readonly ArrayList anonymous_methods;
7164 public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
7165 base (method, accessor, prefix)
7167 this.anonymous_methods = accessor.AnonymousMethods;
7170 public override MethodBuilder Define (DeclSpace ds)
7172 CheckAbstractAndExtern (block != null);
7173 return base.Define (ds);
7176 public override string GetSignatureForError ()
7178 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
7181 public override bool ResolveMembers ()
7183 if (anonymous_methods == null)
7186 foreach (AnonymousMethodExpression ame in anonymous_methods) {
7187 if (!ame.CreateAnonymousHelpers ())
7196 sealed class AddDelegateMethod: AEventPropertyAccessor
7198 public AddDelegateMethod (Event method, Accessor accessor):
7199 base (method, accessor, "add_")
7203 protected override MethodInfo DelegateMethodInfo {
7205 return TypeManager.delegate_combine_delegate_delegate;
7210 sealed class RemoveDelegateMethod: AEventPropertyAccessor
7212 public RemoveDelegateMethod (Event method, Accessor accessor):
7213 base (method, accessor, "remove_")
7217 protected override MethodInfo DelegateMethodInfo {
7219 return TypeManager.delegate_remove_delegate_delegate;
7225 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7227 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
7228 bool is_iface, MemberName name,
7229 Attributes attrs, Accessor add, Accessor remove)
7230 : base (parent, type, mod_flags, is_iface, name, attrs)
7232 Add = new AddDelegateMethod (this, add);
7233 Remove = new RemoveDelegateMethod (this, remove);
7236 public override bool Define()
7238 if (!base.Define ())
7247 public override string[] ValidAttributeTargets {
7249 return attribute_targets;
7255 /// Event is declared like field.
7257 public class EventField : Event {
7258 abstract class EventFieldAccessor : AEventAccessor
7260 protected EventFieldAccessor (Event method, string prefix)
7261 : base (method, prefix)
7265 protected override void EmitMethod(DeclSpace parent)
7267 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7270 MethodBuilder mb = method_data.MethodBuilder;
7271 ILGenerator ig = mb.GetILGenerator ();
7273 // TODO: because we cannot use generics yet
7274 FieldInfo field_info = ((EventField)method).FieldBuilder;
7276 if (parent is Class) {
7277 mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7280 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7281 ig.Emit (OpCodes.Ldsfld, field_info);
7282 ig.Emit (OpCodes.Ldarg_0);
7283 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7284 ig.Emit (OpCodes.Castclass, method.MemberType);
7285 ig.Emit (OpCodes.Stsfld, field_info);
7287 ig.Emit (OpCodes.Ldarg_0);
7288 ig.Emit (OpCodes.Ldarg_0);
7289 ig.Emit (OpCodes.Ldfld, field_info);
7290 ig.Emit (OpCodes.Ldarg_1);
7291 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7292 ig.Emit (OpCodes.Castclass, method.MemberType);
7293 ig.Emit (OpCodes.Stfld, field_info);
7295 ig.Emit (OpCodes.Ret);
7299 sealed class AddDelegateMethod: EventFieldAccessor
7301 public AddDelegateMethod (Event method):
7302 base (method, "add_")
7306 protected override MethodInfo DelegateMethodInfo {
7308 return TypeManager.delegate_combine_delegate_delegate;
7313 sealed class RemoveDelegateMethod: EventFieldAccessor
7315 public RemoveDelegateMethod (Event method):
7316 base (method, "remove_")
7320 protected override MethodInfo DelegateMethodInfo {
7322 return TypeManager.delegate_remove_delegate_delegate;
7328 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7329 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7331 public FieldBuilder FieldBuilder;
7332 public Expression Initializer;
7334 public EventField (DeclSpace parent, Expression type, int mod_flags,
7335 bool is_iface, MemberName name,
7337 : base (parent, type, mod_flags, is_iface, name, attrs)
7339 Add = new AddDelegateMethod (this);
7340 Remove = new RemoveDelegateMethod (this);
7343 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7345 if (a.Target == AttributeTargets.Field) {
7346 FieldBuilder.SetCustomAttribute (cb);
7350 if (a.Target == AttributeTargets.Method) {
7351 int errors = Report.Errors;
7352 Add.ApplyAttributeBuilder (a, cb);
7353 if (errors == Report.Errors)
7354 Remove.ApplyAttributeBuilder (a, cb);
7358 base.ApplyAttributeBuilder (a, cb);
7361 public override bool Define()
7363 if (!base.Define ())
7369 // FIXME: We are unable to detect whether generic event is used because
7370 // we are using FieldExpr instead of EventExpr for event access in that
7371 // case. When this issue will be fixed this hack can be removed.
7372 if (TypeManager.IsGenericType (MemberType))
7375 FieldBuilder = Parent.TypeBuilder.DefineField (
7377 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7378 TypeManager.RegisterEventField (EventBuilder, this);
7380 if (Initializer != null) {
7381 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7382 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7383 GetSignatureForError ());
7387 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7388 new FieldInitializer (FieldBuilder, Initializer));
7394 public override string[] ValidAttributeTargets
7397 return IsInterface ? attribute_targets_interface : attribute_targets;
7402 public abstract class Event : PropertyBasedMember {
7403 public abstract class AEventAccessor : AbstractPropertyEventMethod
7405 protected readonly Event method;
7406 ImplicitParameter param_attr;
7408 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7410 protected AEventAccessor (Event method, string prefix)
7411 : base (method, prefix)
7413 this.method = method;
7414 this.ModFlags = method.ModFlags;
7417 protected AEventAccessor (Event method, Accessor accessor, string prefix)
7418 : base (method, accessor, prefix)
7420 this.method = method;
7421 this.ModFlags = method.ModFlags;
7424 public override Iterator Iterator {
7425 get { return null; }
7428 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7430 if (a.IsInternalMethodImplAttribute) {
7431 method.is_external_implementation = true;
7434 base.ApplyAttributeBuilder (a, cb);
7437 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7439 if (a.Target == AttributeTargets.Parameter) {
7440 if (param_attr == null)
7441 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7443 param_attr.ApplyAttributeBuilder (a, cb);
7447 base.ApplyAttributeBuilder (a, cb);
7450 public override AttributeTargets AttributeTargets {
7452 return AttributeTargets.Method;
7456 public override bool IsClsComplianceRequired ()
7458 return method.IsClsComplianceRequired ();
7461 public virtual MethodBuilder Define (DeclSpace parent)
7463 method_data = new MethodData (method, method.ModFlags,
7464 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7466 if (!method_data.Define (parent))
7469 MethodBuilder mb = method_data.MethodBuilder;
7470 ParameterInfo.ApplyAttributes (mb);
7474 protected abstract MethodInfo DelegateMethodInfo { get; }
7476 public override Type ReturnType {
7478 return TypeManager.void_type;
7482 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7484 return new EmitContext (
7485 ds, method.Parent, Location, ig, ReturnType,
7486 method.ModFlags, false);
7489 public override ObsoleteAttribute GetObsoleteAttribute ()
7491 return method.GetObsoleteAttribute ();
7494 public override string[] ValidAttributeTargets {
7496 return attribute_targets;
7500 public override Parameters ParameterInfo {
7502 return method.parameters;
7508 const int AllowedModifiers =
7511 Modifiers.PROTECTED |
7512 Modifiers.INTERNAL |
7517 Modifiers.OVERRIDE |
7519 Modifiers.ABSTRACT |
7522 const int AllowedInterfaceModifiers =
7525 public AEventAccessor Add, Remove;
7526 public MyEventBuilder EventBuilder;
7527 public MethodBuilder AddBuilder, RemoveBuilder;
7529 Parameters parameters;
7531 protected Event (DeclSpace parent, Expression type, int mod_flags,
7532 bool is_iface, MemberName name, Attributes attrs)
7533 : base (parent, null, type, mod_flags,
7534 is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
7539 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7541 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7542 a.Error_InvalidSecurityParent ();
7546 EventBuilder.SetCustomAttribute (cb);
7549 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7551 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7554 public override AttributeTargets AttributeTargets {
7556 return AttributeTargets.Event;
7560 public override bool Define ()
7562 if (!DoDefineBase ())
7568 if (!TypeManager.IsDelegateType (MemberType)) {
7569 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7573 parameters = Parameters.CreateFullyResolved (
7574 new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location));
7580 // Now define the accessors
7583 AddBuilder = Add.Define (Parent);
7584 if (AddBuilder == null)
7587 RemoveBuilder = Remove.Define (Parent);
7588 if (RemoveBuilder == null)
7591 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
7592 EventBuilder.SetAddOnMethod (AddBuilder);
7593 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7597 public override void Emit ()
7599 if (OptAttributes != null) {
7600 OptAttributes.Emit ();
7604 Remove.Emit (Parent);
7609 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7611 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7612 Parent.TypeBuilder, Name);
7617 ParameterData pd = TypeManager.GetParameterData (mi);
7618 base_ret_type = pd.ParameterType (0);
7623 // Represents header string for documentation comment.
7625 public override string DocCommentHeader {
7626 get { return "E:"; }
7631 public class Indexer : PropertyBase
7633 public class GetIndexerMethod : GetMethod
7635 public GetIndexerMethod (PropertyBase method):
7640 public GetIndexerMethod (PropertyBase method, Accessor accessor):
7641 base (method, accessor)
7645 public override Parameters ParameterInfo {
7647 return ((Indexer)method).parameters;
7652 public class SetIndexerMethod: SetMethod
7654 public SetIndexerMethod (PropertyBase method):
7659 public SetIndexerMethod (PropertyBase method, Accessor accessor):
7660 base (method, accessor)
7664 protected override void DefineParameters ()
7666 parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
7667 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7671 const int AllowedModifiers =
7674 Modifiers.PROTECTED |
7675 Modifiers.INTERNAL |
7679 Modifiers.OVERRIDE |
7684 const int AllowedInterfaceModifiers =
7687 public readonly Parameters parameters;
7689 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7690 bool is_iface, Parameters parameters, Attributes attrs,
7691 Accessor get_block, Accessor set_block, bool define_set_first)
7692 : base (parent, type, mod,
7693 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7694 is_iface, name, attrs, define_set_first)
7696 if (type == TypeManager.system_void_expr)
7697 Report.Error (620, name.Location, "An indexer return type cannot be `void'");
7699 this.parameters = parameters;
7701 if (get_block == null)
7702 Get = new GetIndexerMethod (this);
7704 Get = new GetIndexerMethod (this, get_block);
7706 if (set_block == null)
7707 Set = new SetIndexerMethod (this);
7709 Set = new SetIndexerMethod (this, set_block);
7712 protected override bool CheckForDuplications ()
7714 ArrayList ar = Parent.PartialContainer.Indexers;
7716 int arLen = ar.Count;
7718 for (int i = 0; i < arLen; i++) {
7719 Indexer m = (Indexer) ar [i];
7720 if (IsDuplicateImplementation (m))
7728 bool IsDuplicateImplementation (Indexer indexer)
7730 if (this == indexer)
7733 if (!MemberName.Equals (indexer.MemberName))
7736 Type[] param_types = indexer.parameters.Types;
7738 // When it is not yet defined
7739 if (param_types == null)
7742 if (param_types.Length != parameters.Count)
7745 for (int i = 0; i < param_types.Length; i++)
7746 if (param_types [i] != parameters.Types [i])
7749 Report.SymbolRelatedToPreviousError (indexer);
7750 Report.Error (111, Location, TypeContainer.Error111, indexer.GetSignatureForError ());
7755 public override bool Define ()
7757 if (!DoDefineBase ())
7760 if (!base.Define ())
7763 if (!DefineParameters (parameters))
7766 if (OptAttributes != null) {
7767 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7768 if (indexer_attr != null) {
7769 // Remove the attribute from the list because it is not emitted
7770 OptAttributes.Attrs.Remove (indexer_attr);
7772 string name = indexer_attr.GetIndexerAttributeValue ();
7778 if (IsExplicitImpl) {
7779 Report.Error (415, indexer_attr.Location,
7780 "The `IndexerName' attribute is valid only on an " +
7781 "indexer that is not an explicit interface member declaration");
7785 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7786 Report.Error (609, indexer_attr.Location,
7787 "Cannot set the `IndexerName' attribute on an indexer marked override");
7793 if (InterfaceType != null) {
7794 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7795 if (base_IndexerName != Name)
7796 ShortName = base_IndexerName;
7799 if (!Parent.PartialContainer.AddMember (this) ||
7800 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7806 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7808 if (!DefineAccessors ())
7812 // Setup iterator if we are one
7813 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7814 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7815 if (iterator == null)
7821 // Now name the parameters
7823 Parameter [] p = parameters.FixedParameters;
7825 // TODO: should be done in parser and it needs to do cycle
7826 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7827 CSharpParser.Error_ParameterModifierNotValid (Location);
7832 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7833 Name, PropertyAttributes.None, MemberType, parameters.Types);
7836 PropertyBuilder.SetGetMethod (GetBuilder);
7839 PropertyBuilder.SetSetMethod (SetBuilder);
7841 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
7846 public override string GetDocCommentName (DeclSpace ds)
7848 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7851 public override string GetSignatureForError ()
7853 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7854 if (MemberName.Left != null) {
7856 sb.Append (MemberName.Left);
7859 sb.Append (".this");
7860 sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7861 return sb.ToString ();
7864 public override bool IsOverloadable {
7870 protected override PropertyInfo ResolveBaseProperty ()
7872 return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7873 Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
7876 protected override bool VerifyClsCompliance ()
7878 if (!base.VerifyClsCompliance ())
7881 parameters.VerifyClsCompliance ();
7886 public class Operator : MethodOrOperator, IAnonymousHost {
7888 const int AllowedModifiers =
7894 public enum OpType : byte {
7904 // Unary and Binary operators
7927 // Implicit and Explicit
7931 // Just because of enum
7935 public readonly OpType OperatorType;
7937 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7938 int mod_flags, Parameters parameters,
7939 ToplevelBlock block, Attributes attrs, Location loc)
7940 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7941 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7943 OperatorType = type;
7947 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7949 if (a.Type == TypeManager.conditional_attribute_type) {
7950 Error_ConditionalAttributeIsNotValid ();
7954 base.ApplyAttributeBuilder (a, cb);
7957 protected override bool CheckForDuplications ()
7959 ArrayList ar = Parent.PartialContainer.Operators;
7961 int arLen = ar.Count;
7963 for (int i = 0; i < arLen; i++) {
7964 Operator o = (Operator) ar [i];
7965 if (IsDuplicateImplementation (o))
7970 ar = Parent.PartialContainer.Methods;
7972 int arLen = ar.Count;
7974 for (int i = 0; i < arLen; i++) {
7975 Method m = (Method) ar [i];
7976 if (IsDuplicateImplementation (m))
7984 public override bool Define ()
7986 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7987 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7988 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7992 // imlicit and explicit operator of same types are not allowed
7993 if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
7994 EnableOverloadChecks ();
7996 if (!base.Define ())
7999 if (MemberType == TypeManager.void_type) {
8000 Report.Error (590, Location, "User-defined operators cannot return void");
8004 Type declaring_type = MethodData.DeclaringType;
8005 Type return_type = MemberType;
8006 Type first_arg_type = ParameterTypes [0];
8008 // Rules for conversion operators
8010 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8011 if (first_arg_type == return_type && first_arg_type == declaring_type){
8012 Report.Error (555, Location,
8013 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
8018 if (TypeManager.IsEqual (declaring_type, return_type)) {
8019 conv_type = first_arg_type;
8020 } else if (TypeManager.IsEqual (declaring_type, first_arg_type)) {
8021 conv_type = return_type;
8022 } else if (TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
8023 conv_type = first_arg_type;
8024 } else if (TypeManager.IsNullableTypeOf (first_arg_type, declaring_type)) {
8025 conv_type = return_type;
8027 Report.Error (556, Location,
8028 "User-defined conversion must convert to or from the enclosing type");
8033 // Because IsInterface and IsClass are not supported
8035 if (!TypeManager.IsGenericParameter (conv_type)) {
8036 if (conv_type.IsInterface) {
8037 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
8038 GetSignatureForError ());
8042 if (conv_type.IsClass) {
8043 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
8044 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
8045 GetSignatureForError ());
8049 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
8050 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
8051 GetSignatureForError ());
8056 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8057 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
8058 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");
8061 } else if (Parameters.Count == 1) {
8062 // Checks for Unary operators
8064 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8065 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
8066 Report.Error (448, Location,
8067 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8070 if (first_arg_type != declaring_type) {
8072 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8077 if (first_arg_type != declaring_type){
8080 "The parameter of a unary operator must be the " +
8085 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8086 if (return_type != TypeManager.bool_type){
8089 "The return type of operator True or False " +
8096 // Checks for Binary operators
8098 if (first_arg_type != declaring_type &&
8099 ParameterTypes [1] != declaring_type){
8102 "One of the parameters of a binary operator must " +
8103 "be the containing type");
8111 protected override bool DoDefine ()
8113 if (!base.DoDefine ())
8116 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
8120 public override void Emit ()
8124 Parameters.ApplyAttributes (MethodBuilder);
8127 // abstract or extern methods have no bodies
8129 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8133 if ((flags & MethodAttributes.PinvokeImpl) == 0)
8134 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
8136 ec = CreateEmitContext (Parent, null);
8138 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
8139 ec.EmitTopBlock (this, Block);
8142 source.CloseMethod ();
8147 // Operator cannot be override
8148 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
8153 public static string GetName (OpType ot)
8156 case OpType.LogicalNot:
8158 case OpType.OnesComplement:
8160 case OpType.Increment:
8162 case OpType.Decrement:
8168 case OpType.Addition:
8170 case OpType.Subtraction:
8172 case OpType.UnaryPlus:
8174 case OpType.UnaryNegation:
8176 case OpType.Multiply:
8178 case OpType.Division:
8180 case OpType.Modulus:
8182 case OpType.BitwiseAnd:
8184 case OpType.BitwiseOr:
8186 case OpType.ExclusiveOr:
8188 case OpType.LeftShift:
8190 case OpType.RightShift:
8192 case OpType.Equality:
8194 case OpType.Inequality:
8196 case OpType.GreaterThan:
8198 case OpType.LessThan:
8200 case OpType.GreaterThanOrEqual:
8202 case OpType.LessThanOrEqual:
8204 case OpType.Implicit:
8206 case OpType.Explicit:
8212 public static OpType GetOperatorType (string name)
8214 if (name.StartsWith ("op_")){
8215 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8216 if (Unary.oper_names [i] == name)
8220 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8221 if (Binary.oper_names [i] == name)
8228 public override string GetSignatureForError ()
8230 StringBuilder sb = new StringBuilder ();
8231 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8232 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8235 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8238 sb.Append (Parameters.GetSignatureForError ());
8239 return sb.ToString ();
8244 // This is used to compare method signatures
8246 struct MethodSignature {
8248 public Type RetType;
8249 public Type [] Parameters;
8252 /// This delegate is used to extract methods which have the
8253 /// same signature as the argument
8255 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8257 public MethodSignature (string name, Type ret_type, Type [] parameters)
8262 if (parameters == null)
8263 Parameters = Type.EmptyTypes;
8265 Parameters = parameters;
8268 public override string ToString ()
8271 if (Parameters.Length != 0){
8272 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8273 for (int i = 0; i < Parameters.Length; i++){
8274 sb.Append (Parameters [i]);
8275 if (i+1 < Parameters.Length)
8278 pars = sb.ToString ();
8281 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8284 public override int GetHashCode ()
8286 return Name.GetHashCode ();
8289 public override bool Equals (Object o)
8291 MethodSignature other = (MethodSignature) o;
8293 if (other.Name != Name)
8296 if (other.RetType != RetType)
8299 if (Parameters == null){
8300 if (other.Parameters == null)
8305 if (other.Parameters == null)
8308 int c = Parameters.Length;
8309 if (other.Parameters.Length != c)
8312 for (int i = 0; i < c; i++)
8313 if (other.Parameters [i] != Parameters [i])
8319 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8321 MethodSignature sig = (MethodSignature) filter_criteria;
8323 if (m.Name != sig.Name)
8327 MethodInfo mi = m as MethodInfo;
8328 PropertyInfo pi = m as PropertyInfo;
8331 ReturnType = mi.ReturnType;
8332 else if (pi != null)
8333 ReturnType = pi.PropertyType;
8338 // we use sig.RetType == null to mean `do not check the
8339 // method return value.
8341 if (sig.RetType != null)
8342 if (ReturnType != sig.RetType)
8347 args = TypeManager.GetParameterData (mi).Types;
8349 args = TypeManager.GetArgumentTypes (pi);
8350 Type [] sigp = sig.Parameters;
8352 if (args.Length != sigp.Length)
8355 for (int i = args.Length; i > 0; ){
8357 if (args [i] != sigp [i])