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 {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
77 } catch (Exception e) {
78 throw new InternalErrorException (mc.Location, mc.GetSignatureForError (), e);
83 public virtual void Emit ()
85 foreach (MemberCore mc in this)
90 public class MethodArrayList : MemberCoreArrayList
98 CachedMethods cached_method;
99 TypeContainer container;
101 public MethodArrayList (TypeContainer container)
103 this.container = container;
107 /// Method container contains Equals method
109 public bool HasEquals {
111 cached_method |= CachedMethods.Equals;
115 return (cached_method & CachedMethods.Equals) != 0;
120 /// Method container contains GetHashCode method
122 public bool HasGetHashCode {
124 cached_method |= CachedMethods.GetHashCode;
128 return (cached_method & CachedMethods.GetHashCode) != 0;
132 public override void DefineContainerMembers ()
134 base.DefineContainerMembers ();
136 if (HasEquals && !HasGetHashCode) {
137 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
142 public sealed class IndexerArrayList : MemberCoreArrayList
145 /// The indexer name for this container
147 public string IndexerName = DefaultIndexerName;
149 bool seen_normal_indexers = false;
151 TypeContainer container;
153 public IndexerArrayList (TypeContainer container)
155 this.container = container;
159 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
160 /// class is consistent. Either it is `Item' or it is the name defined by all the
161 /// indexers with the `IndexerName' attribute.
163 /// Turns out that the IndexerNameAttribute is applied to each indexer,
164 /// but it is never emitted, instead a DefaultMember attribute is attached
167 public override void DefineContainerMembers()
169 base.DefineContainerMembers ();
171 string class_indexer_name = null;
174 // If there's both an explicit and an implicit interface implementation, the
175 // explicit one actually implements the interface while the other one is just
176 // a normal indexer. See bug #37714.
179 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
180 foreach (Indexer i in this) {
181 if (i.InterfaceType != null) {
182 if (seen_normal_indexers)
183 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
187 seen_normal_indexers = true;
189 if (class_indexer_name == null) {
190 class_indexer_name = i.ShortName;
194 if (i.ShortName != class_indexer_name)
195 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");
198 if (class_indexer_name != null)
199 IndexerName = class_indexer_name;
202 public override void Emit ()
206 if (!seen_normal_indexers)
209 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
210 container.TypeBuilder.SetCustomAttribute (cb);
214 public class OperatorArrayList: MemberCoreArrayList
216 TypeContainer container;
218 public OperatorArrayList (TypeContainer container)
220 this.container = container;
224 // Operator pair checking
229 public Type ret_type;
230 public Type type1, type2;
232 public Operator.OpType ot;
234 public OperatorEntry (int f, Operator o)
238 ret_type = o.MemberType;
239 Type [] pt = o.ParameterTypes;
246 public override int GetHashCode ()
248 return ret_type.GetHashCode ();
251 public override bool Equals (object o)
253 OperatorEntry other = (OperatorEntry) o;
255 if (other.ret_type != ret_type)
257 if (other.type1 != type1)
259 if (other.type2 != type2)
266 // Checks that some operators come in pairs:
272 // They are matched based on the return type and the argument types
274 void CheckPairedOperators ()
276 IDictionary pairs = new HybridDictionary ();
277 Operator true_op = null;
278 Operator false_op = null;
279 bool has_equality_or_inequality = false;
281 // Register all the operators we care about.
282 foreach (Operator op in this){
285 // Skip erroneous code.
286 if (op.MethodBuilder == null)
289 switch (op.OperatorType){
290 case Operator.OpType.Equality:
292 has_equality_or_inequality = true;
294 case Operator.OpType.Inequality:
296 has_equality_or_inequality = true;
299 case Operator.OpType.True:
302 case Operator.OpType.False:
306 case Operator.OpType.GreaterThan:
308 case Operator.OpType.LessThan:
311 case Operator.OpType.GreaterThanOrEqual:
313 case Operator.OpType.LessThanOrEqual:
319 OperatorEntry oe = new OperatorEntry (reg, op);
321 object o = pairs [oe];
325 oe = (OperatorEntry) o;
330 if (true_op != null){
331 if (false_op == null)
332 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
333 true_op.GetSignatureForError ());
334 } else if (false_op != null)
335 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
336 false_op.GetSignatureForError ());
339 // Look for the mistakes.
341 foreach (DictionaryEntry de in pairs){
342 OperatorEntry oe = (OperatorEntry) de.Key;
349 case Operator.OpType.Equality:
352 case Operator.OpType.Inequality:
355 case Operator.OpType.GreaterThan:
358 case Operator.OpType.LessThan:
361 case Operator.OpType.GreaterThanOrEqual:
364 case Operator.OpType.LessThanOrEqual:
368 Report.Error (216, oe.op.Location,
369 "The operator `{0}' requires a matching operator `{1}' to also be defined",
370 oe.op.GetSignatureForError (), s);
373 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
374 if (container.Methods == null || !container.Methods.HasEquals)
375 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
377 if (container.Methods == null || !container.Methods.HasGetHashCode)
378 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
382 public override void DefineContainerMembers ()
384 base.DefineContainerMembers ();
385 CheckPairedOperators ();
390 // Whether this is a struct, class or interface
391 public readonly Kind Kind;
393 // Holds a list of classes and structures
394 protected ArrayList types;
396 // Holds the list of properties
397 MemberCoreArrayList properties;
399 // Holds the list of enumerations
400 MemberCoreArrayList enums;
402 // Holds the list of delegates
403 MemberCoreArrayList delegates;
405 // Holds the list of constructors
406 protected MemberCoreArrayList instance_constructors;
408 // Holds the list of fields
409 MemberCoreArrayList fields;
411 // Holds a list of fields that have initializers
412 protected ArrayList initialized_fields;
414 // Holds a list of static fields that have initializers
415 protected ArrayList initialized_static_fields;
417 // Holds the list of constants
418 MemberCoreArrayList constants;
421 MemberCoreArrayList interfaces;
423 // Holds the methods.
424 MethodArrayList methods;
427 protected MemberCoreArrayList events;
429 // Holds the indexers
430 IndexerArrayList indexers;
432 // Holds the operators
433 MemberCoreArrayList operators;
435 // Holds the compiler generated classes
436 ArrayList compiler_generated;
439 // Pointers to the default constructor and the default static constructor
441 protected Constructor default_constructor;
442 protected Constructor default_static_constructor;
445 // Points to the first non-static field added to the container.
447 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
448 // and the first one's as good as any.
450 FieldBase first_nonstatic_field = null;
453 // This one is computed after we can distinguish interfaces
454 // from classes from the arraylist `type_bases'
457 TypeExpr[] iface_exprs;
460 ArrayList type_bases;
462 bool members_resolved;
463 bool members_resolved_ok;
464 bool members_defined;
465 bool members_defined_ok;
467 // The interfaces we implement.
468 protected Type[] ifaces;
470 // The base member cache and our member cache
471 MemberCache base_cache;
472 MemberCache member_cache;
474 public const string DefaultIndexerName = "Item";
477 GenericTypeParameterBuilder[] gen_params;
480 ArrayList partial_parts;
483 /// The pending methods that need to be implemented
484 // (interfaces or abstract methods)
486 PendingImplementation pending;
488 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
489 Attributes attrs, Kind kind)
490 : base (ns, parent, name, attrs)
492 if (parent != null && parent.NamespaceEntry != ns)
493 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
496 this.PartialContainer = this;
499 public bool AddMember (MemberCore symbol)
501 return AddToContainer (symbol, symbol.MemberName.MethodName);
504 protected virtual bool AddMemberType (DeclSpace ds)
506 return AddToContainer (ds, ds.Basename);
509 public void AddConstant (Const constant)
511 if (!AddMember (constant))
514 if (constants == null)
515 constants = new MemberCoreArrayList ();
517 constants.Add (constant);
520 public void AddEnum (Mono.CSharp.Enum e)
522 if (!AddMemberType (e))
526 enums = new MemberCoreArrayList ();
531 public TypeContainer AddTypeContainer (TypeContainer tc, bool is_interface)
533 if (!AddMemberType (tc))
537 if (interfaces == null)
538 interfaces = new MemberCoreArrayList ();
542 types = new ArrayList (2);
548 public virtual TypeContainer AddPartial (TypeContainer nextPart, bool is_interface)
550 return AddPartial (nextPart, nextPart.Basename, is_interface);
553 protected TypeContainer AddPartial (TypeContainer nextPart, string name, bool is_interface)
555 nextPart.ModFlags |= Modifiers.PARTIAL;
556 TypeContainer tc = defined_names [name] as TypeContainer;
559 return AddTypeContainer (nextPart, is_interface);
561 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
562 Report.SymbolRelatedToPreviousError (tc);
563 Error_MissingPartialModifier (nextPart);
567 if (tc.Kind != nextPart.Kind) {
568 Report.SymbolRelatedToPreviousError (tc);
569 Report.Error (261, nextPart.Location,
570 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
571 nextPart.GetSignatureForError ());
575 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility) &&
576 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
577 (nextPart.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
578 Report.SymbolRelatedToPreviousError (tc);
579 Report.Error (262, nextPart.Location,
580 "Partial declarations of `{0}' have conflicting accessibility modifiers",
581 nextPart.GetSignatureForError ());
585 if (tc.MemberName.IsGeneric) {
586 TypeParameter[] tc_names = tc.TypeParameters;
587 TypeParameterName[] part_names = nextPart.MemberName.TypeArguments.GetDeclarations ();
589 for (int i = 0; i < tc_names.Length; ++i) {
590 if (tc_names[i].Name == part_names[i].Name)
593 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
594 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
595 tc.GetSignatureForError ());
600 if (tc.partial_parts == null)
601 tc.partial_parts = new ArrayList (1);
603 tc.ModFlags |= nextPart.ModFlags;
604 if (nextPart.attributes != null) {
605 if (tc.attributes == null)
606 tc.attributes = nextPart.attributes;
608 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
611 nextPart.PartialContainer = tc;
612 tc.partial_parts.Add (nextPart);
616 public void AddDelegate (Delegate d)
618 if (!AddMemberType (d))
621 if (delegates == null)
622 delegates = new MemberCoreArrayList ();
627 public void AddMethod (Method method)
629 if (!AddMember (method))
633 methods = new MethodArrayList (this);
635 if (method.MemberName.Left != null)
636 methods.Insert (0, method);
638 methods.Add (method);
642 // Do not use this method: use AddMethod.
644 // This is only used by iterators.
646 public void AppendMethod (Method method)
648 if (!AddMember (method))
652 methods = new MethodArrayList (this);
654 methods.Add (method);
657 public void AddConstructor (Constructor c)
659 if (c.Name != MemberName.Name) {
660 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
663 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
666 if (default_static_constructor != null) {
667 Report.SymbolRelatedToPreviousError (default_static_constructor);
668 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
672 default_static_constructor = c;
674 if (c.Parameters.Empty){
675 if (default_constructor != null) {
676 Report.SymbolRelatedToPreviousError (default_constructor);
677 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
680 default_constructor = c;
683 if (instance_constructors == null)
684 instance_constructors = new MemberCoreArrayList ();
686 instance_constructors.Add (c);
690 internal static string Error111 {
692 return "`{0}' is already defined. Rename this member or use different parameter types";
696 public void AddField (FieldMember field)
698 if (!AddMember (field))
702 fields = new MemberCoreArrayList ();
706 if ((field.ModFlags & Modifiers.STATIC) != 0)
709 if (first_nonstatic_field == null) {
710 first_nonstatic_field = field;
714 if (Kind == Kind.Struct &&
715 first_nonstatic_field.Parent != field.Parent &&
716 RootContext.WarningLevel >= 3) {
717 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
718 Report.Warning (282, 3, field.Location,
719 "struct instance field `{0}' found in different declaration from instance field `{1}'",
720 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
724 public void AddProperty (Property prop)
726 if (!AddMember (prop) ||
727 !AddMember (prop.Get) || !AddMember (prop.Set))
730 if (properties == null)
731 properties = new MemberCoreArrayList ();
733 if (prop.MemberName.Left != null)
734 properties.Insert (0, prop);
736 properties.Add (prop);
739 public void AddEvent (Event e)
744 if (e is EventProperty) {
745 if (!AddMember (e.Add))
748 if (!AddMember (e.Remove))
753 events = new MemberCoreArrayList ();
759 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
761 public void AddIndexer (Indexer i)
763 if (indexers == null)
764 indexers = new IndexerArrayList (this);
766 if (i.IsExplicitImpl)
767 indexers.Insert (0, i);
772 public void AddOperator (Operator op)
777 if (operators == null)
778 operators = new OperatorArrayList (this);
783 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
785 Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
787 if (compiler_generated == null)
788 compiler_generated = new ArrayList ();
790 compiler_generated.Add (c);
793 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
795 if (a.Type == TypeManager.default_member_type) {
796 if (Indexers != null) {
797 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
802 base.ApplyAttributeBuilder (a, cb);
805 public override AttributeTargets AttributeTargets {
807 throw new NotSupportedException ();
811 public ArrayList Types {
817 public MethodArrayList Methods {
823 public ArrayList Constants {
829 public ArrayList Interfaces {
835 public ArrayList CompilerGenerated {
837 return compiler_generated;
841 protected Type BaseType {
843 return TypeBuilder.BaseType;
847 public ArrayList Bases {
857 public ArrayList Fields {
863 public ArrayList InstanceConstructors {
865 return instance_constructors;
869 public ArrayList Properties {
875 public ArrayList Events {
881 public ArrayList Enums {
887 public ArrayList Indexers {
893 public ArrayList Operators {
899 public ArrayList Delegates {
905 protected override TypeAttributes TypeAttr {
907 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
911 public string IndexerName {
913 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
917 public bool IsComImport {
919 if (OptAttributes == null)
922 return OptAttributes.Contains (TypeManager.comimport_attr_type);
926 public virtual void RegisterFieldForInitialization (FieldBase field)
928 if ((field.ModFlags & Modifiers.STATIC) != 0){
929 if (initialized_static_fields == null)
930 initialized_static_fields = new ArrayList (4);
932 initialized_static_fields.Add (field);
934 if (initialized_fields == null)
935 initialized_fields = new ArrayList (4);
937 initialized_fields.Add (field);
942 // Emits the instance field initializers
944 public bool EmitFieldInitializers (EmitContext ec)
949 fields = initialized_static_fields;
951 fields = initialized_fields;
957 foreach (FieldBase f in fields) {
958 f.EmitInitializer (ec);
963 public override string DocComment {
975 public PendingImplementation PendingImplementations {
976 get { return pending; }
979 public override bool GetClsCompliantAttributeValue ()
981 if (PartialContainer != this)
982 return PartialContainer.GetClsCompliantAttributeValue ();
984 return base.GetClsCompliantAttributeValue ();
987 public void AddBasesForPart (DeclSpace part, ArrayList bases)
989 // FIXME: get rid of partial_parts and store lists of bases of each part here
990 // assumed, not verified: 'part' is in 'partial_parts'
991 ((TypeContainer) part).Bases = bases;
994 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1000 int count = Bases.Count;
1001 int start = 0, i, j;
1003 if (Kind == Kind.Class){
1004 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
1010 if (!name.IsInterface) {
1011 // base_class could be a class, struct, enum, delegate.
1012 // This is validated in GetClassBases.
1018 TypeExpr [] ifaces = new TypeExpr [count-start];
1020 for (i = start, j = 0; i < count; i++, j++){
1021 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
1022 if (resolved == null) {
1026 ifaces [j] = resolved;
1029 return ifaces.Length == 0 ? null : ifaces;
1033 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1035 ArrayList ifaces = new ArrayList (0);
1036 if (iface_exprs != null)
1037 ifaces.AddRange (iface_exprs);
1039 foreach (TypeContainer part in partial_parts) {
1040 TypeExpr new_base_class;
1041 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1042 if (new_base_class != TypeManager.system_object_expr) {
1043 if (base_class == TypeManager.system_object_expr)
1044 base_class = new_base_class;
1046 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1047 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1048 Report.Error (263, part.Location,
1049 "Partial declarations of `{0}' must not specify different base classes",
1050 part.GetSignatureForError ());
1057 if (new_ifaces == null)
1060 foreach (TypeExpr iface in new_ifaces) {
1061 if (ifaces.Contains (iface))
1068 if (ifaces.Count == 0)
1071 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1075 /// This function computes the Base class and also the
1076 /// list of interfaces that the class or struct @c implements.
1078 /// The return value is an array (might be null) of
1079 /// interfaces implemented (as Types).
1081 /// The @base_class argument is set to the base object or null
1082 /// if this is `System.Object'.
1084 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1086 TypeExpr[] ifaces = GetNormalBases (out base_class);
1091 int count = ifaces.Length;
1093 for (int i = 0; i < count; i++) {
1094 TypeExpr iface = (TypeExpr) ifaces [i];
1096 if (!iface.IsInterface) {
1097 if (Kind != Kind.Class) {
1098 // TODO: location of symbol related ....
1099 Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
1101 else if (base_class != null)
1102 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1103 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1105 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1106 GetSignatureForError (), iface.GetSignatureForError ());
1111 for (int x = 0; x < i; x++) {
1112 if (iface.Equals (ifaces [x])) {
1113 Report.Error (528, Location,
1114 "`{0}' is already listed in " +
1115 "interface list", iface.GetSignatureForError ());
1120 if ((Kind == Kind.Interface) &&
1121 !iface.AsAccessible (Parent, ModFlags)) {
1122 Report.Error (61, Location,
1123 "Inconsistent accessibility: base " +
1124 "interface `{0}' is less accessible " +
1125 "than interface `{1}'", iface.Name,
1133 bool CheckGenericInterfaces (Type[] ifaces)
1136 ArrayList already_checked = new ArrayList ();
1138 for (int i = 0; i < ifaces.Length; i++) {
1139 Type iface = ifaces [i];
1140 foreach (Type t in already_checked) {
1144 Type[] infered = new Type [CountTypeParameters];
1145 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1148 Report.Error (695, Location,
1149 "`{0}' cannot implement both `{1}' and `{2}' " +
1150 "because they may unify for some type parameter substitutions",
1151 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1152 TypeManager.CSharpName (t));
1156 already_checked.Add (iface);
1165 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1167 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1170 bool DefineTypeBuilder ()
1174 if (TypeManager.NamespaceClash (Name, Location)) {
1178 ModuleBuilder builder = CodeGen.Module.Builder;
1179 Type default_parent = null;
1180 if (Kind == Kind.Struct)
1181 default_parent = TypeManager.value_type;
1182 TypeBuilder = builder.DefineType (
1183 Name, TypeAttr, default_parent, null);
1185 TypeBuilder builder = Parent.TypeBuilder;
1187 TypeBuilder = builder.DefineNestedType (
1188 Basename, TypeAttr, null, null);
1190 } catch (ArgumentException) {
1191 Report.RuntimeMissingSupport (Location, "static classes");
1195 TypeManager.AddUserType (this);
1199 string[] param_names = new string [TypeParameters.Length];
1200 for (int i = 0; i < TypeParameters.Length; i++)
1201 param_names [i] = TypeParameters [i].Name;
1203 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1205 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1206 for (int i = offset; i < gen_params.Length; i++)
1207 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1211 iface_exprs = GetClassBases (out base_type);
1212 if (partial_parts != null) {
1213 iface_exprs = GetNormalPartialBases (ref base_type);
1217 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1218 // which in turn should have called DefineType()s on base types if necessary.
1220 // None of the code below should trigger DefineType()s on classes that we depend on.
1221 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1223 // Let's do it as soon as possible, since code below can call DefineType() on classes
1224 // that depend on us to be populated before they are.
1226 if (!(this is CompilerGeneratedClass))
1227 RootContext.RegisterOrder (this);
1229 if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
1230 Report.Error (698, base_type.Location,
1231 "A generic type cannot derive from `{0}' because it is an attribute class",
1236 if (!CheckRecursiveDefinition (this))
1239 if (base_type != null) {
1240 TypeBuilder.SetParent (base_type.Type);
1242 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1243 if (obsolete_attr != null && !IsInObsoleteScope)
1244 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1247 // add interfaces that were not added at type creation
1248 if (iface_exprs != null) {
1249 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1253 foreach (Type itype in ifaces)
1254 TypeBuilder.AddInterfaceImplementation (itype);
1256 foreach (TypeExpr ie in iface_exprs) {
1257 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1258 if ((oa != null) && !IsInObsoleteScope)
1259 AttributeTester.Report_ObsoleteMessage (
1260 oa, ie.GetSignatureForError (), Location);
1263 if (!CheckGenericInterfaces (ifaces))
1266 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1273 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1275 public override TypeBuilder DefineType ()
1277 if (TypeBuilder != null)
1283 if (!DefineTypeBuilder ()) {
1288 if (partial_parts != null) {
1289 foreach (TypeContainer part in partial_parts)
1290 part.TypeBuilder = TypeBuilder;
1293 if (!(this is CompilerGeneratedClass)) {
1294 if (!ResolveMembers ()) {
1300 if (!DefineNestedTypes ()) {
1308 public bool ResolveMembers ()
1310 if (members_resolved)
1311 return members_resolved_ok;
1313 members_resolved_ok = DoResolveMembers ();
1314 members_resolved = true;
1316 return members_resolved_ok;
1319 protected virtual bool DoResolveMembers ()
1321 if (methods != null) {
1322 foreach (Method method in methods) {
1323 if (!method.ResolveMembers ())
1328 if (instance_constructors != null) {
1329 foreach (Constructor c in instance_constructors) {
1330 if (!c.ResolveMembers ())
1335 if (default_static_constructor != null) {
1336 if (!default_static_constructor.ResolveMembers ())
1340 if (operators != null) {
1341 foreach (Operator o in operators) {
1342 if (!o.ResolveMembers ())
1347 if (properties != null) {
1348 foreach (PropertyBase p in properties) {
1349 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1351 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1356 if (indexers != null) {
1357 foreach (PropertyBase p in indexers) {
1358 if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
1360 if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
1368 Constraints [] constraints;
1369 public override void SetParameterInfo (ArrayList constraints_list)
1371 if (PartialContainer == this) {
1372 base.SetParameterInfo (constraints_list);
1376 if (constraints_list == null)
1379 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1381 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1382 for (int i = 0; i < constraints.Length; i++) {
1383 foreach (Constraints constraint in constraints_list) {
1384 if (constraint.TypeParameter == current_params [i].Name) {
1385 constraints [i] = constraint;
1392 bool UpdateTypeParameterConstraints ()
1394 if (constraints == null)
1397 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1398 for (int i = 0; i < current_params.Length; i++) {
1399 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1400 Report.SymbolRelatedToPreviousError (Location, "");
1401 Report.Error (265, PartialContainer.Location,
1402 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1403 PartialContainer.GetSignatureForError (), current_params [i].Name);
1411 public bool ResolveType ()
1413 if (!DoResolveType ())
1416 if (compiler_generated != null) {
1417 foreach (CompilerGeneratedClass c in compiler_generated)
1418 if (!c.ResolveType ())
1425 protected virtual bool DoResolveType ()
1427 if ((base_type != null) &&
1428 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1436 if (PartialContainer != this)
1437 throw new InternalErrorException ();
1439 TypeExpr current_type = null;
1441 foreach (TypeParameter type_param in CurrentTypeParameters) {
1442 if (!type_param.Resolve (this)) {
1448 if (partial_parts != null) {
1449 foreach (TypeContainer part in partial_parts) {
1450 if (!part.UpdateTypeParameterConstraints ()) {
1457 foreach (TypeParameter type_param in TypeParameters) {
1458 if (!type_param.DefineType (this)) {
1464 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1466 foreach (TypeParameter type_param in TypeParameters)
1467 if (!type_param.CheckDependencies ()) {
1472 if (current_type != null) {
1473 current_type = current_type.ResolveAsTypeTerminal (this, false);
1474 if (current_type == null) {
1479 CurrentType = current_type.Type;
1485 protected virtual bool DefineNestedTypes ()
1487 if (Interfaces != null) {
1488 foreach (TypeContainer iface in Interfaces)
1489 if (iface.DefineType () == null)
1493 if (Types != null) {
1494 foreach (TypeContainer tc in Types)
1495 if (tc.DefineType () == null)
1499 if (Delegates != null) {
1500 foreach (Delegate d in Delegates)
1501 if (d.DefineType () == null)
1505 if (Enums != null) {
1506 foreach (Enum en in Enums)
1507 if (en.DefineType () == null)
1511 if (compiler_generated != null) {
1512 foreach (CompilerGeneratedClass c in compiler_generated) {
1513 if (c.DefineType () == null)
1521 TypeContainer InTransit;
1523 protected bool CheckRecursiveDefinition (TypeContainer tc)
1525 if (InTransit != null) {
1526 Report.SymbolRelatedToPreviousError (this);
1527 if (this is Interface)
1529 529, tc.Location, "Inherited interface `{0}' causes a " +
1530 "cycle in the interface hierarchy of `{1}'",
1531 GetSignatureForError (), tc.GetSignatureForError ());
1534 146, tc.Location, "Circular base class dependency " +
1535 "involving `{0}' and `{1}'",
1536 tc.GetSignatureForError (), GetSignatureForError ());
1542 if (base_type != null) {
1543 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1544 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1545 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1549 if (iface_exprs != null) {
1550 foreach (TypeExpr iface in iface_exprs) {
1551 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1552 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1553 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1558 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1565 public static void Error_KeywordNotAllowed (Location loc)
1567 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1571 /// Populates our TypeBuilder with fields and methods
1573 public override bool DefineMembers ()
1575 if (members_defined)
1576 return members_defined_ok;
1578 if (!base.DefineMembers ())
1581 members_defined_ok = DoDefineMembers ();
1582 members_defined = true;
1584 return members_defined_ok;
1587 protected virtual bool DoDefineMembers ()
1589 if (iface_exprs != null) {
1590 foreach (TypeExpr iface in iface_exprs) {
1591 ConstructedType ct = iface as ConstructedType;
1592 if ((ct != null) && !ct.CheckConstraints (this))
1597 if (base_type != null) {
1598 ConstructedType ct = base_type as ConstructedType;
1599 if ((ct != null) && !ct.CheckConstraints (this))
1604 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1605 if (conflict_symbol == null) {
1606 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1607 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1609 if ((ModFlags & Modifiers.NEW) == 0) {
1610 Report.SymbolRelatedToPreviousError (conflict_symbol);
1611 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1612 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1617 DefineContainerMembers (constants);
1618 DefineContainerMembers (fields);
1620 if (Kind == Kind.Struct || Kind == Kind.Class) {
1621 pending = PendingImplementation.GetPendingImplementations (this);
1625 // Constructors are not in the defined_names array
1627 DefineContainerMembers (instance_constructors);
1629 DefineContainerMembers (properties);
1630 DefineContainerMembers (events);
1631 DefineContainerMembers (indexers);
1632 DefineContainerMembers (methods);
1633 DefineContainerMembers (operators);
1634 DefineContainerMembers (enums);
1635 DefineContainerMembers (delegates);
1637 if (CurrentType != null) {
1638 GenericType = CurrentType;
1643 member_cache = new MemberCache (this);
1644 if (partial_parts != null) {
1645 foreach (TypeContainer part in partial_parts)
1646 part.member_cache = member_cache;
1653 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1656 mcal.DefineContainerMembers ();
1659 public override bool Define ()
1661 if (compiler_generated != null) {
1662 foreach (CompilerGeneratedClass c in compiler_generated) {
1671 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1673 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1677 /// This function is based by a delegate to the FindMembers routine
1679 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1685 /// This filter is used by FindMembers, and we just keep
1686 /// a global for the filter to `AlwaysAccept'
1688 static MemberFilter accepting_filter;
1691 static TypeContainer ()
1693 accepting_filter = new MemberFilter (AlwaysAccept);
1696 public MethodInfo[] GetMethods ()
1698 ArrayList members = new ArrayList ();
1702 if (methods != null) {
1703 int len = methods.Count;
1704 for (int i = 0; i < len; i++) {
1705 Method m = (Method) methods [i];
1707 members.Add (m.MethodBuilder);
1711 if (operators != null) {
1712 int len = operators.Count;
1713 for (int i = 0; i < len; i++) {
1714 Operator o = (Operator) operators [i];
1716 members.Add (o.MethodBuilder);
1720 if (properties != null) {
1721 int len = properties.Count;
1722 for (int i = 0; i < len; i++) {
1723 Property p = (Property) properties [i];
1725 if (p.GetBuilder != null)
1726 members.Add (p.GetBuilder);
1727 if (p.SetBuilder != null)
1728 members.Add (p.SetBuilder);
1732 if (indexers != null) {
1733 int len = indexers.Count;
1734 for (int i = 0; i < len; i++) {
1735 Indexer ix = (Indexer) indexers [i];
1737 if (ix.GetBuilder != null)
1738 members.Add (ix.GetBuilder);
1739 if (ix.SetBuilder != null)
1740 members.Add (ix.SetBuilder);
1744 if (events != null) {
1745 int len = events.Count;
1746 for (int i = 0; i < len; i++) {
1747 Event e = (Event) events [i];
1749 if (e.AddBuilder != null)
1750 members.Add (e.AddBuilder);
1751 if (e.RemoveBuilder != null)
1752 members.Add (e.RemoveBuilder);
1756 MethodInfo[] retMethods = new MethodInfo [members.Count];
1757 members.CopyTo (retMethods, 0);
1761 // Indicated whether container has StructLayout attribute set Explicit
1762 public bool HasExplicitLayout {
1763 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1764 set { caching_flags |= Flags.HasExplicitLayout; }
1768 // Return the nested type with name @name. Ensures that the nested type
1769 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1771 public Type FindNestedType (string name)
1773 if (PartialContainer != this)
1774 throw new InternalErrorException ("should not happen");
1776 ArrayList [] lists = { types, enums, delegates, interfaces };
1778 for (int j = 0; j < lists.Length; ++j) {
1779 ArrayList list = lists [j];
1783 int len = list.Count;
1784 for (int i = 0; i < len; ++i) {
1785 DeclSpace ds = (DeclSpace) list [i];
1786 if (ds.Basename == name) {
1787 return ds.DefineType ();
1795 private void FindMembers_NestedTypes (int modflags,
1796 BindingFlags bf, MemberFilter filter, object criteria,
1797 ref ArrayList members)
1799 ArrayList [] lists = { types, enums, delegates, interfaces };
1801 for (int j = 0; j < lists.Length; ++j) {
1802 ArrayList list = lists [j];
1806 int len = list.Count;
1807 for (int i = 0; i < len; i++) {
1808 DeclSpace ds = (DeclSpace) list [i];
1810 if ((ds.ModFlags & modflags) == 0)
1813 TypeBuilder tb = ds.TypeBuilder;
1815 if (!(criteria is string) || ds.Basename.Equals (criteria))
1816 tb = ds.DefineType ();
1819 if (tb != null && (filter (tb, criteria) == true)) {
1820 if (members == null)
1821 members = new ArrayList ();
1830 /// This method returns the members of this type just like Type.FindMembers would
1831 /// Only, we need to use this for types which are _being_ defined because MS'
1832 /// implementation can't take care of that.
1835 // FIXME: return an empty static array instead of null, that cleans up
1836 // some code and is consistent with some coding conventions I just found
1840 // Notice that in various cases we check if our field is non-null,
1841 // something that would normally mean that there was a bug elsewhere.
1843 // The problem happens while we are defining p-invoke methods, as those
1844 // will trigger a FindMembers, but this happens before things are defined
1846 // Since the whole process is a no-op, it is fine to check for null here.
1848 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1849 MemberFilter filter, object criteria)
1851 ArrayList members = null;
1854 if ((bf & BindingFlags.Public) != 0)
1855 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1857 if ((bf & BindingFlags.NonPublic) != 0)
1858 modflags |= Modifiers.PRIVATE;
1860 int static_mask = 0, static_flags = 0;
1861 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1862 case BindingFlags.Static:
1863 static_mask = static_flags = Modifiers.STATIC;
1866 case BindingFlags.Instance:
1867 static_mask = Modifiers.STATIC;
1872 static_mask = static_flags = 0;
1876 Timer.StartTimer (TimerType.TcFindMembers);
1879 filter = accepting_filter;
1881 if ((mt & MemberTypes.Field) != 0) {
1882 if (fields != null) {
1883 int len = fields.Count;
1884 for (int i = 0; i < len; i++) {
1885 FieldMember f = (FieldMember) fields [i];
1887 if ((f.ModFlags & modflags) == 0)
1889 if ((f.ModFlags & static_mask) != static_flags)
1892 FieldBuilder fb = f.FieldBuilder;
1893 if (fb != null && filter (fb, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (constants != null) {
1903 int len = constants.Count;
1904 for (int i = 0; i < len; i++) {
1905 Const con = (Const) constants [i];
1907 if ((con.ModFlags & modflags) == 0)
1909 if ((con.ModFlags & static_mask) != static_flags)
1912 FieldBuilder fb = con.FieldBuilder;
1915 fb = con.FieldBuilder;
1917 if (fb != null && filter (fb, criteria) == true) {
1918 if (members == null)
1919 members = new ArrayList ();
1927 if ((mt & MemberTypes.Method) != 0) {
1928 if (methods != null) {
1929 int len = methods.Count;
1930 for (int i = 0; i < len; i++) {
1931 Method m = (Method) methods [i];
1933 if ((m.ModFlags & modflags) == 0)
1935 if ((m.ModFlags & static_mask) != static_flags)
1938 MethodBuilder mb = m.MethodBuilder;
1940 if (mb != null && filter (mb, criteria) == true) {
1941 if (members == null)
1942 members = new ArrayList ();
1949 if (operators != null) {
1950 int len = operators.Count;
1951 for (int i = 0; i < len; i++) {
1952 Operator o = (Operator) operators [i];
1954 if ((o.ModFlags & modflags) == 0)
1956 if ((o.ModFlags & static_mask) != static_flags)
1959 MethodBuilder ob = o.MethodBuilder;
1960 if (ob != null && filter (ob, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1969 if (events != null) {
1970 foreach (Event e in events) {
1971 if ((e.ModFlags & modflags) == 0)
1973 if ((e.ModFlags & static_mask) != static_flags)
1976 MethodBuilder b = e.AddBuilder;
1977 if (b != null && filter (b, criteria)) {
1978 if (members == null)
1979 members = new ArrayList (4);
1984 b = e.RemoveBuilder;
1985 if (b != null && filter (b, criteria)) {
1986 if (members == null)
1987 members = new ArrayList (4);
1994 if (properties != null) {
1995 int len = properties.Count;
1996 for (int i = 0; i < len; i++) {
1997 Property p = (Property) properties [i];
1999 if ((p.ModFlags & modflags) == 0)
2001 if ((p.ModFlags & static_mask) != static_flags)
2007 if (b != null && filter (b, criteria) == true) {
2008 if (members == null)
2009 members = new ArrayList ();
2015 if (b != null && filter (b, criteria) == true) {
2016 if (members == null)
2017 members = new ArrayList ();
2024 if (indexers != null) {
2025 int len = indexers.Count;
2026 for (int i = 0; i < len; i++) {
2027 Indexer ix = (Indexer) indexers [i];
2029 if ((ix.ModFlags & modflags) == 0)
2031 if ((ix.ModFlags & static_mask) != static_flags)
2037 if (b != null && filter (b, criteria) == true) {
2038 if (members == null)
2039 members = new ArrayList ();
2045 if (b != null && filter (b, criteria) == true) {
2046 if (members == null)
2047 members = new ArrayList ();
2055 if ((mt & MemberTypes.Event) != 0) {
2056 if (events != null) {
2057 int len = events.Count;
2058 for (int i = 0; i < len; i++) {
2059 Event e = (Event) events [i];
2061 if ((e.ModFlags & modflags) == 0)
2063 if ((e.ModFlags & static_mask) != static_flags)
2066 MemberInfo eb = e.EventBuilder;
2067 if (eb != null && filter (eb, criteria) == true) {
2068 if (members == null)
2069 members = new ArrayList ();
2071 members.Add (e.EventBuilder);
2077 if ((mt & MemberTypes.Property) != 0){
2078 if (properties != null) {
2079 int len = properties.Count;
2080 for (int i = 0; i < len; i++) {
2081 Property p = (Property) properties [i];
2083 if ((p.ModFlags & modflags) == 0)
2085 if ((p.ModFlags & static_mask) != static_flags)
2088 MemberInfo pb = p.PropertyBuilder;
2089 if (pb != null && filter (pb, criteria) == true) {
2090 if (members == null)
2091 members = new ArrayList ();
2093 members.Add (p.PropertyBuilder);
2098 if (indexers != null) {
2099 int len = indexers.Count;
2100 for (int i = 0; i < len; i++) {
2101 Indexer ix = (Indexer) indexers [i];
2103 if ((ix.ModFlags & modflags) == 0)
2105 if ((ix.ModFlags & static_mask) != static_flags)
2108 MemberInfo ib = ix.PropertyBuilder;
2109 if (ib != null && filter (ib, criteria) == true) {
2110 if (members == null)
2111 members = new ArrayList ();
2113 members.Add (ix.PropertyBuilder);
2119 if ((mt & MemberTypes.NestedType) != 0)
2120 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2122 if ((mt & MemberTypes.Constructor) != 0){
2123 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2124 int len = instance_constructors.Count;
2125 for (int i = 0; i < len; i++) {
2126 Constructor c = (Constructor) instance_constructors [i];
2128 ConstructorBuilder cb = c.ConstructorBuilder;
2129 if (cb != null && filter (cb, criteria) == true) {
2130 if (members == null)
2131 members = new ArrayList ();
2138 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2139 ConstructorBuilder cb =
2140 default_static_constructor.ConstructorBuilder;
2142 if (cb != null && filter (cb, criteria) == true) {
2143 if (members == null)
2144 members = new ArrayList ();
2152 // Lookup members in base if requested.
2154 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2155 if (TypeBuilder.BaseType != null) {
2156 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2157 if (list.Count > 0) {
2158 if (members == null)
2159 members = new ArrayList ();
2161 members.AddRange (list);
2166 Timer.StopTimer (TimerType.TcFindMembers);
2168 if (members == null)
2169 return MemberList.Empty;
2171 return new MemberList (members);
2174 public override MemberCache MemberCache {
2176 return member_cache;
2180 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2181 MemberFilter filter, object criteria)
2183 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2186 return ds.FindMembers (mt, bf, filter, criteria);
2188 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2192 /// Emits the values for the constants
2194 public void EmitConstants ()
2196 if (constants != null)
2197 foreach (Const con in constants)
2202 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2207 foreach (MemberCore mc in al) {
2208 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2212 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2217 public virtual void VerifyMembers ()
2220 // Check for internal or private fields that were never assigned
2222 if (RootContext.WarningLevel >= 3) {
2223 CheckMemberUsage (properties, "property");
2224 CheckMemberUsage (methods, "method");
2225 CheckMemberUsage (constants, "constant");
2227 if (fields != null){
2228 foreach (FieldMember f in fields) {
2229 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2233 if ((f.caching_flags & Flags.IsAssigned) == 0)
2234 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2237 const int error_code = 414;
2239 const int error_code = 169;
2241 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2242 f.GetSignatureForError ());
2248 // Only report 649 on level 4
2250 if (RootContext.WarningLevel < 4)
2253 if ((f.caching_flags & Flags.IsAssigned) != 0)
2256 Constant c = New.Constantify (f.Type.Type);
2257 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2258 f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2264 // TODO: move to ClassOrStruct
2265 void EmitConstructors ()
2267 if (instance_constructors == null)
2270 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2271 bool has_compliant_args = false;
2273 foreach (Constructor c in instance_constructors) {
2276 if (has_compliant_args)
2279 has_compliant_args = c.HasCompliantArgs;
2281 if (!has_compliant_args)
2282 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2284 foreach (Constructor c in instance_constructors)
2290 /// Emits the code, this step is performed after all
2291 /// the types, enumerations, constructors
2293 public virtual void EmitType ()
2295 if (OptAttributes != null)
2296 OptAttributes.Emit ();
2300 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2301 for (int i = offset; i < gen_params.Length; i++)
2302 CurrentTypeParameters [i - offset].EmitAttributes ();
2307 // Structs with no fields need to have at least one byte.
2308 // The right thing would be to set the PackingSize in a DefineType
2309 // but there are no functions that allow interfaces *and* the size to
2313 if (Kind == Kind.Struct && first_nonstatic_field == null){
2314 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2315 FieldAttributes.Private);
2317 if (HasExplicitLayout){
2318 object [] ctor_args = new object [1];
2321 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2322 TypeManager.field_offset_attribute_ctor, ctor_args);
2323 fb.SetCustomAttribute (cba);
2329 EmitConstructors ();
2331 // Can not continue if constants are broken
2333 if (Report.Errors > 0)
2336 if (default_static_constructor != null)
2337 default_static_constructor.Emit ();
2339 if (methods != null){
2340 foreach (Method m in methods)
2344 if (operators != null)
2345 foreach (Operator o in operators)
2348 if (properties != null)
2349 foreach (Property p in properties)
2352 if (indexers != null){
2357 foreach (FieldMember f in fields)
2360 if (events != null){
2361 foreach (Event e in Events)
2365 if (delegates != null) {
2366 foreach (Delegate d in Delegates) {
2371 if (enums != null) {
2372 foreach (Enum e in enums) {
2377 if (pending != null)
2378 if (pending.VerifyPendingMethods ())
2381 if (Report.Errors > 0)
2384 if (compiler_generated != null) {
2385 foreach (CompilerGeneratedClass c in compiler_generated) {
2386 if (!c.DefineMembers ())
2387 throw new InternalErrorException ();
2389 foreach (CompilerGeneratedClass c in compiler_generated)
2394 public override void CloseType ()
2396 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2400 caching_flags |= Flags.CloseTypeCreated;
2401 TypeBuilder.CreateType ();
2402 } catch (TypeLoadException){
2404 // This is fine, the code still created the type
2406 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2407 // Console.WriteLine (e.Message);
2409 Console.WriteLine ("In type: " + Name);
2414 foreach (Enum en in Enums)
2418 foreach (TypeContainer tc in Types)
2419 if (tc.Kind == Kind.Struct)
2422 foreach (TypeContainer tc in Types)
2423 if (tc.Kind != Kind.Struct)
2427 if (Delegates != null)
2428 foreach (Delegate d in Delegates)
2431 if (CompilerGenerated != null)
2432 foreach (CompilerGeneratedClass c in CompilerGenerated)
2440 initialized_fields = null;
2441 initialized_static_fields = null;
2448 compiler_generated = null;
2449 default_constructor = null;
2450 default_static_constructor = null;
2452 OptAttributes = null;
2455 member_cache = null;
2459 // Performs the validation on a Method's modifiers (properties have
2460 // the same properties).
2462 public bool MethodModifiersValid (MemberCore mc)
2464 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2465 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2466 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2468 int flags = mc.ModFlags;
2471 // At most one of static, virtual or override
2473 if ((flags & Modifiers.STATIC) != 0){
2474 if ((flags & vao) != 0){
2475 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2476 mc.GetSignatureForError ());
2481 if (Kind == Kind.Struct){
2482 if ((flags & va) != 0){
2483 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2488 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2489 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2490 mc.GetSignatureForError ());
2495 // If the declaration includes the abstract modifier, then the
2496 // declaration does not include static, virtual or extern
2498 if ((flags & Modifiers.ABSTRACT) != 0){
2499 if ((flags & Modifiers.EXTERN) != 0){
2501 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2505 if ((flags & Modifiers.SEALED) != 0) {
2506 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2510 if ((flags & Modifiers.VIRTUAL) != 0){
2511 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2515 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2516 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2521 if ((flags & Modifiers.PRIVATE) != 0){
2522 if ((flags & vao) != 0){
2523 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2528 if ((flags & Modifiers.SEALED) != 0){
2529 if ((flags & Modifiers.OVERRIDE) == 0){
2530 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2538 public Constructor DefaultStaticConstructor {
2539 get { return default_static_constructor; }
2542 protected override bool VerifyClsCompliance ()
2544 if (!base.VerifyClsCompliance ())
2549 Type base_type = TypeBuilder.BaseType;
2550 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2551 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2558 /// Checks whether container name is CLS Compliant
2560 void VerifyClsName ()
2562 Hashtable base_members = base_cache == null ?
2564 base_cache.GetPublicMembers ();
2565 Hashtable this_members = new Hashtable ();
2567 foreach (DictionaryEntry entry in defined_names) {
2568 MemberCore mc = (MemberCore)entry.Value;
2569 if (!mc.IsClsComplianceRequired ())
2572 string name = (string) entry.Key;
2573 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2575 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2576 object found = base_members [lcase];
2577 if (found == null) {
2578 found = this_members [lcase];
2579 if (found == null) {
2580 this_members.Add (lcase, mc);
2585 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2588 if (found is MemberInfo) {
2589 if (basename == ((MemberInfo) found).Name)
2591 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2593 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2596 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2598 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2605 /// Performs checks for an explicit interface implementation. First it
2606 /// checks whether the `interface_type' is a base inteface implementation.
2607 /// Then it checks whether `name' exists in the interface type.
2609 public virtual bool VerifyImplements (MemberBase mb)
2611 if (ifaces != null) {
2612 foreach (Type t in ifaces){
2613 if (t == mb.InterfaceType)
2618 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2619 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2620 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2624 public void Mark_HasEquals ()
2626 Methods.HasEquals = true;
2629 public void Mark_HasGetHashCode ()
2631 Methods.HasGetHashCode = true;
2638 string IMemberContainer.Name {
2644 Type IMemberContainer.Type {
2650 MemberCache IMemberContainer.MemberCache {
2652 return member_cache;
2656 bool IMemberContainer.IsInterface {
2658 return Kind == Kind.Interface;
2662 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2664 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2666 if (GenericType != null)
2667 return TypeManager.FindMembers (GenericType, mt, new_bf,
2670 return FindMembers (mt, new_bf, null, null);
2674 // Generates xml doc comments (if any), and if required,
2675 // handle warning report.
2677 internal override void GenerateDocComment (DeclSpace ds)
2679 DocUtil.GenerateTypeDocComment (this, ds);
2682 public override string DocCommentHeader {
2683 get { return "T:"; }
2686 public virtual MemberCache BaseCache {
2688 if (base_cache != null)
2690 if (TypeBuilder.BaseType != null)
2691 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2692 if (TypeBuilder.IsInterface)
2693 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2699 public abstract class ClassOrStruct : TypeContainer {
2700 ListDictionary declarative_security;
2702 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2703 MemberName name, Attributes attrs, Kind kind)
2704 : base (ns, parent, name, attrs, kind)
2708 protected override bool AddToContainer (MemberCore symbol, string name)
2710 if (name == MemberName.Name) {
2711 if (symbol is TypeParameter) {
2712 Report.Error (694, symbol.Location,
2713 "Type parameter `{0}' has same name as " +
2714 "containing type, or method", name);
2718 Report.SymbolRelatedToPreviousError (this);
2719 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2720 symbol.GetSignatureForError ());
2724 return base.AddToContainer (symbol, name);
2727 public override void VerifyMembers ()
2729 base.VerifyMembers ();
2731 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2732 foreach (Event e in events){
2733 if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2736 if ((e.caching_flags & Flags.IsUsed) == 0)
2737 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2742 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2744 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2745 if (declarative_security == null)
2746 declarative_security = new ListDictionary ();
2748 a.ExtractSecurityPermissionSet (declarative_security);
2752 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2753 HasExplicitLayout = true;
2756 base.ApplyAttributeBuilder (a, cb);
2760 /// Defines the default constructors
2762 protected void DefineDefaultConstructor (bool is_static)
2764 // The default instance constructor is public
2765 // If the class is abstract, the default constructor is protected
2766 // The default static constructor is private
2770 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2772 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2775 Constructor c = new Constructor (this, MemberName.Name, mods,
2776 Parameters.EmptyReadOnlyParameters,
2777 new GeneratedBaseInitializer (Location),
2781 c.Block = new ToplevelBlock (null, Location);
2784 void DefineFieldInitializers ()
2786 if (initialized_fields != null) {
2787 for (int i = 0; i < initialized_fields.Count; ++i) {
2788 FieldBase fb = (FieldBase)initialized_fields[i];
2789 fb.ResolveInitializer ();
2790 if (fb.HasDefaultInitializer && RootContext.Optimize) {
2791 // Field is re-initialized to its default value => removed
2792 initialized_fields.RemoveAt (i);
2798 if (initialized_static_fields != null) {
2799 bool has_complex_initializer = false;
2801 foreach (FieldBase fb in initialized_static_fields) {
2802 if (fb.ResolveInitializer () is Constant)
2805 has_complex_initializer = true;
2808 // Need special check to not optimize code like this
2809 // static int a = b = 5;
2810 // static int b = 0;
2811 if (!has_complex_initializer && RootContext.Optimize) {
2812 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2813 FieldBase fb = (FieldBase)initialized_static_fields[i];
2814 if (fb.HasDefaultInitializer) {
2815 initialized_static_fields.RemoveAt (i);
2821 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2822 DefineDefaultConstructor (true);
2828 public override bool Define ()
2830 DefineFieldInitializers ();
2832 if (default_static_constructor != null)
2833 default_static_constructor.Define ();
2835 return base.Define ();
2838 public override void Emit ()
2842 if (declarative_security != null) {
2843 foreach (DictionaryEntry de in declarative_security) {
2844 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2849 protected override TypeAttributes TypeAttr {
2851 if (default_static_constructor == null)
2852 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2854 return base.TypeAttr;
2860 // TODO: should be sealed
2861 public class Class : ClassOrStruct {
2862 const int AllowedModifiers =
2865 Modifiers.PROTECTED |
2866 Modifiers.INTERNAL |
2868 Modifiers.ABSTRACT |
2873 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2875 : base (ns, parent, name, attrs, Kind.Class)
2877 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2878 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2880 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2881 Report.FeatureIsNotStandardized (Location, "static classes");
2885 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2887 if (a.Type == TypeManager.attribute_usage_type) {
2888 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2889 TypeBuilder.FullName != "System.Attribute") {
2890 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2894 if (a.Type == TypeManager.conditional_attribute_type &&
2895 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2896 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2900 if (a.Type == TypeManager.comimport_attr_type &&
2901 !attributes.Contains (TypeManager.guid_attr_type)) {
2902 a.Error_MissingGuidAttribute ();
2906 if (AttributeTester.IsAttributeExcluded (a.Type))
2909 base.ApplyAttributeBuilder (a, cb);
2912 public override AttributeTargets AttributeTargets {
2914 return AttributeTargets.Class;
2918 protected override void DefineContainerMembers (MemberCoreArrayList list)
2924 base.DefineContainerMembers (list);
2928 foreach (MemberCore m in list) {
2929 if (m is Operator) {
2930 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2934 if (m is Destructor) {
2935 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2939 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2940 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2945 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2949 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2952 if (m is Constructor) {
2953 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2957 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2960 base.DefineContainerMembers (list);
2963 public override TypeBuilder DefineType ()
2965 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2966 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2970 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2971 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2975 return base.DefineType ();
2978 protected override bool DoDefineMembers ()
2980 if (InstanceConstructors == null && !IsStatic)
2981 DefineDefaultConstructor (false);
2983 return base.DoDefineMembers ();
2986 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2988 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2990 if (base_class == null) {
2991 if (RootContext.StdLib)
2992 base_class = TypeManager.system_object_expr;
2993 else if (Name != "System.Object")
2994 base_class = TypeManager.system_object_expr;
2996 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2998 689, base_class.Location,
2999 "Cannot derive from `{0}' because it is a type parameter",
3000 base_class.GetSignatureForError ());
3004 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
3005 Report.Error (1521, base_class.Location, "Invalid base type");
3009 if (base_class.IsSealed){
3010 Report.SymbolRelatedToPreviousError (base_class.Type);
3011 if (base_class.Type.IsAbstract) {
3012 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
3013 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3015 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
3016 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
3021 if (!base_class.CanInheritFrom ()){
3022 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
3023 GetSignatureForError (), base_class.GetSignatureForError ());
3027 if (!base_class.AsAccessible (this, ModFlags)) {
3028 Report.SymbolRelatedToPreviousError (base_class.Type);
3029 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
3030 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
3035 if (base_class != TypeManager.system_object_expr) {
3036 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
3037 GetSignatureForError (), base_class.GetSignatureForError ());
3041 if (ifaces != null) {
3042 foreach (TypeExpr t in ifaces)
3043 Report.SymbolRelatedToPreviousError (t.Type);
3044 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3051 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3052 /// Valid only for attribute classes.
3053 public bool IsExcluded ()
3055 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3056 return (caching_flags & Flags.Excluded) != 0;
3058 caching_flags &= ~Flags.Excluded_Undetected;
3060 if (OptAttributes == null)
3063 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3068 foreach (Attribute a in attrs) {
3069 string condition = a.GetConditionalAttributeValue ();
3070 if (RootContext.AllDefines.Contains (condition))
3074 caching_flags |= Flags.Excluded;
3080 return (ModFlags & Modifiers.STATIC) != 0;
3085 // FIXME: How do we deal with the user specifying a different
3088 protected override TypeAttributes TypeAttr {
3090 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3092 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
3098 public sealed class Struct : ClassOrStruct {
3100 // Modifiers allowed in a struct declaration
3102 const int AllowedModifiers =
3105 Modifiers.PROTECTED |
3106 Modifiers.INTERNAL |
3110 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3111 int mod, Attributes attrs)
3112 : base (ns, parent, name, attrs, Kind.Struct)
3116 if (parent.Parent == null)
3117 accmods = Modifiers.INTERNAL;
3119 accmods = Modifiers.PRIVATE;
3121 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3123 this.ModFlags |= Modifiers.SEALED;
3126 public override AttributeTargets AttributeTargets {
3128 return AttributeTargets.Struct;
3132 const TypeAttributes DefaultTypeAttributes =
3133 TypeAttributes.SequentialLayout |
3134 TypeAttributes.Sealed |
3135 TypeAttributes.BeforeFieldInit;
3138 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3140 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3142 // If we are compiling our runtime,
3143 // and we are defining ValueType, then our
3144 // base is `System.Object'.
3146 if (base_class == null) {
3147 if (!RootContext.StdLib && Name == "System.ValueType")
3148 base_class = TypeManager.system_object_expr;
3150 base_class = TypeManager.system_valuetype_expr;
3157 // FIXME: Allow the user to specify a different set of attributes
3158 // in some cases (Sealed for example is mandatory for a class,
3159 // but what SequentialLayout can be changed
3161 protected override TypeAttributes TypeAttr {
3163 return base.TypeAttr | DefaultTypeAttributes;
3167 public override void RegisterFieldForInitialization (FieldBase field)
3169 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3170 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3171 field.GetSignatureForError ());
3174 base.RegisterFieldForInitialization (field);
3182 public sealed class Interface : TypeContainer, IMemberContainer {
3185 /// Modifiers allowed in a class declaration
3187 public const int AllowedModifiers =
3190 Modifiers.PROTECTED |
3191 Modifiers.INTERNAL |
3195 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3197 : base (ns, parent, name, attrs, Kind.Interface)
3201 if (parent.Parent == null)
3202 accmods = Modifiers.INTERNAL;
3204 accmods = Modifiers.PRIVATE;
3206 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3209 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3211 if (a.Type == TypeManager.comimport_attr_type &&
3212 !attributes.Contains (TypeManager.guid_attr_type)) {
3213 a.Error_MissingGuidAttribute ();
3216 base.ApplyAttributeBuilder (a, cb);
3220 public override AttributeTargets AttributeTargets {
3222 return AttributeTargets.Interface;
3226 const TypeAttributes DefaultTypeAttributes =
3227 TypeAttributes.AutoLayout |
3228 TypeAttributes.Abstract |
3229 TypeAttributes.Interface;
3231 protected override TypeAttributes TypeAttr {
3233 return base.TypeAttr | DefaultTypeAttributes;
3237 protected override bool VerifyClsCompliance ()
3239 if (!base.VerifyClsCompliance ())
3242 if (ifaces != null) {
3243 foreach (Type t in ifaces) {
3244 if (AttributeTester.IsClsCompliant (t))
3247 Report.SymbolRelatedToPreviousError (t);
3248 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3249 GetSignatureForError (), TypeManager.CSharpName (t));
3257 public abstract class MethodCore : MemberBase {
3258 public readonly Parameters Parameters;
3259 protected ToplevelBlock block;
3262 // The method we're overriding if this is an override method.
3264 protected MethodInfo base_method = null;
3266 public MethodCore (DeclSpace parent, GenericMethod generic,
3267 Expression type, int mod, int allowed_mod, bool is_iface,
3268 MemberName name, Attributes attrs, Parameters parameters)
3269 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3272 Parameters = parameters;
3273 IsInterface = is_iface;
3277 // Returns the System.Type array for the parameters of this method
3279 public Type [] ParameterTypes {
3281 return Parameters.Types;
3285 public Parameters ParameterInfo
3292 public ToplevelBlock Block {
3302 public virtual void SetYields ()
3304 ModFlags |= Modifiers.METHOD_YIELDS;
3307 protected override bool CheckBase ()
3309 if (!base.CheckBase ())
3312 // Check whether arguments were correct.
3313 if (!DoDefineParameters ())
3316 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3322 // Is null for System.Object while compiling corlib and base interfaces
3323 if (Parent.PartialContainer.BaseCache == null) {
3324 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3325 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3330 Type base_ret_type = null;
3331 base_method = FindOutBaseMethod (ref base_ret_type);
3333 // method is override
3334 if (base_method != null) {
3336 if (!CheckMethodAgainstBase ())
3339 if ((ModFlags & Modifiers.NEW) == 0) {
3340 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3341 Report.SymbolRelatedToPreviousError (base_method);
3342 if (this is PropertyBase) {
3343 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3344 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3347 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3348 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3353 if (base_method.IsAbstract && !IsInterface) {
3354 Report.SymbolRelatedToPreviousError (base_method);
3355 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3356 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3361 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3362 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3366 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3367 Parent.PartialContainer.Mark_HasEquals ();
3368 else if (Name == "GetHashCode" && Parameters.Empty)
3369 Parent.PartialContainer.Mark_HasGetHashCode ();
3371 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3372 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3374 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3375 Report.SymbolRelatedToPreviousError (base_method);
3376 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3377 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3380 if (OptAttributes != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3381 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3382 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3389 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3390 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3391 if (conflict_symbol != null) {
3392 Report.SymbolRelatedToPreviousError (conflict_symbol);
3393 if (this is PropertyBase)
3394 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3396 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3398 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3402 if (conflict_symbol == null) {
3403 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3404 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3409 if ((ModFlags & Modifiers.NEW) == 0) {
3410 if (this is Method && conflict_symbol is MethodBase)
3413 Report.SymbolRelatedToPreviousError (conflict_symbol);
3414 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3415 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3422 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3423 // that have been defined.
3425 // `name' is the user visible name for reporting errors (this is used to
3426 // provide the right name regarding method names and properties)
3428 bool CheckMethodAgainstBase ()
3432 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3433 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3434 Report.Error (506, Location,
3435 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3436 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3440 // Now we check that the overriden method is not final
3442 if (base_method.IsFinal) {
3443 Report.SymbolRelatedToPreviousError (base_method);
3444 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3445 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3449 // Check that the permissions are not being changed
3451 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3452 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3454 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3455 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3460 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3461 ModFlags |= Modifiers.NEW;
3462 Report.SymbolRelatedToPreviousError (base_method);
3463 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3464 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",
3465 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3467 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3468 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3475 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3477 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3479 // when overriding protected internal, the method can be declared
3480 // protected internal only within the same assembly
3483 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3484 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3486 // assemblies differ - report an error
3490 } else if (thisp != base_classp) {
3492 // same assembly, but other attributes differ - report an error
3497 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3499 // if it's not "protected internal", it must be "protected"
3503 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3505 // protected within the same assembly - an error
3508 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3509 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3511 // protected ok, but other attributes differ - report an error
3517 return (thisp == base_classp);
3521 public bool CheckAbstractAndExtern (bool has_block)
3523 if (Parent.PartialContainer.Kind == Kind.Interface)
3527 if ((ModFlags & Modifiers.EXTERN) != 0) {
3528 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3529 GetSignatureForError ());
3533 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3534 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3535 GetSignatureForError ());
3539 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3540 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3541 GetSignatureForError ());
3549 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3551 Report.SymbolRelatedToPreviousError (base_method);
3552 string base_name = TypeManager.GetFullNameSignature (base_method);
3553 string this_name = GetSignatureForError ();
3554 if (suffix != null) {
3555 base_name += suffix;
3556 this_name += suffix;
3559 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3560 this_name, Modifiers.GetDescription (ma), base_name);
3563 protected static string Error722 {
3565 return "`{0}': static types cannot be used as return types";
3570 /// For custom member duplication search in a container
3572 protected abstract bool CheckForDuplications ();
3575 /// Gets base method and its return type
3577 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3579 protected bool DoDefineParameters ()
3581 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3583 // Check if arguments were correct
3584 if (!Parameters.Resolve (rc))
3587 return CheckParameters (ParameterTypes);
3590 bool CheckParameters (Type [] parameters)
3594 foreach (Type partype in parameters){
3595 if (partype == TypeManager.void_type) {
3596 // TODO: location is wrong
3597 Expression.Error_VoidInvalidInTheContext (Location);
3601 if (partype.IsPointer){
3602 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3606 if (ds.AsAccessible (partype, ModFlags))
3609 Report.SymbolRelatedToPreviousError (partype);
3610 if (this is Indexer)
3611 Report.Error (55, Location,
3612 "Inconsistent accessibility: parameter type `" +
3613 TypeManager.CSharpName (partype) + "' is less " +
3614 "accessible than indexer `" + GetSignatureForError () + "'");
3615 else if (this is Operator)
3616 Report.Error (57, Location,
3617 "Inconsistent accessibility: parameter type `" +
3618 TypeManager.CSharpName (partype) + "' is less " +
3619 "accessible than operator `" + GetSignatureForError () + "'");
3621 Report.Error (51, Location,
3622 "Inconsistent accessibility: parameter type `" +
3623 TypeManager.CSharpName (partype) + "' is less " +
3624 "accessible than method `" + GetSignatureForError () + "'");
3631 protected override bool VerifyClsCompliance ()
3633 if (!base.VerifyClsCompliance ()) {
3634 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3635 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3640 if (Parameters.HasArglist) {
3641 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3644 if (!AttributeTester.IsClsCompliant (MemberType)) {
3645 if (this is PropertyBase)
3646 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3647 GetSignatureForError ());
3649 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3650 GetSignatureForError ());
3653 Parameters.VerifyClsCompliance ();
3658 // TODO: create a special method for operators only to make code better
3659 protected bool IsDuplicateImplementation (MethodCore method)
3664 Operator op2 = null;
3665 Operator op1 = null;
3667 if (!(method.MemberName.Equals (MemberName)))
3669 op1 = this as Operator;
3670 if (op1 == null || !(op1.OperatorType == Operator.OpType.Explicit || op1.OperatorType == Operator.OpType.Implicit))
3673 op2 = method as Operator;
3674 if (op2 == null || !(op2.OperatorType == Operator.OpType.Explicit || op2.OperatorType == Operator.OpType.Implicit))
3677 op1 = this as Operator;
3678 op2 = method as Operator;
3681 Type[] param_types = method.ParameterTypes;
3682 // This never happen. Rewrite this as Equal
3683 if (param_types == null && ParameterTypes == null)
3685 if (param_types == null || ParameterTypes == null)
3688 if (param_types.Length != ParameterTypes.Length)
3691 if (method.Parameters.HasArglist != Parameters.HasArglist)
3696 for (int i = 0; i < param_types.Length; i++) {
3697 if (param_types [i] != ParameterTypes [i])
3701 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3704 // TODO: make operator compatible with MethodCore to avoid this
3705 if (op1 != null && op2 != null) {
3706 if (MemberType != method.MemberType)
3712 // Try to report 663: method only differs on out/ref
3714 Parameters info = ParameterInfo;
3715 Parameters other_info = method.ParameterInfo;
3716 for (int i = 0; i < info.Count; i++){
3718 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3719 Report.SymbolRelatedToPreviousError (method);
3720 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3721 GetSignatureForError ());
3724 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3725 Console.WriteLine ("this is: {0} {1}", Location, this);
3729 Report.SymbolRelatedToPreviousError (method);
3730 if (this is Operator && method is Operator)
3731 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3733 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3741 public override bool IsUsed {
3742 get { return IsExplicitImpl || base.IsUsed; }
3746 // Returns a string that represents the signature for this
3747 // member which should be used in XML documentation.
3749 public override string GetDocCommentName (DeclSpace ds)
3751 return DocUtil.GetMethodDocCommentName (this, ds);
3755 // Raised (and passed an XmlElement that contains the comment)
3756 // when GenerateDocComment is writing documentation expectedly.
3758 // FIXME: with a few effort, it could be done with XmlReader,
3759 // that means removal of DOM use.
3761 internal override void OnGenerateDocComment (XmlElement el)
3763 DocUtil.OnMethodGenerateDocComment (this, el);
3767 // Represents header string for documentation comment.
3769 public override string DocCommentHeader {
3770 get { return "M:"; }
3775 public abstract class MethodOrOperator : MethodCore, IMethodData
3777 public MethodBuilder MethodBuilder;
3778 ReturnParameter return_attributes;
3779 ListDictionary declarative_security;
3780 protected MethodData MethodData;
3783 ArrayList anonymous_methods;
3785 static string[] attribute_targets = new string [] { "method", "return" };
3787 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3788 int allowed_mod, bool is_interface, MemberName name,
3789 Attributes attrs, Parameters parameters)
3790 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3795 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3797 if (a.Target == AttributeTargets.ReturnValue) {
3798 if (return_attributes == null)
3799 return_attributes = new ReturnParameter (MethodBuilder, Location);
3801 return_attributes.ApplyAttributeBuilder (a, cb);
3805 if (a.Type == TypeManager.methodimpl_attr_type &&
3806 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3807 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3810 if (a.Type == TypeManager.dllimport_type) {
3811 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3812 if ((ModFlags & extern_static) != extern_static) {
3813 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3819 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3820 if (declarative_security == null)
3821 declarative_security = new ListDictionary ();
3822 a.ExtractSecurityPermissionSet (declarative_security);
3826 MethodBuilder.SetCustomAttribute (cb);
3829 public override AttributeTargets AttributeTargets {
3831 return AttributeTargets.Method;
3835 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3837 return new EmitContext (
3838 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3841 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
3843 if (anonymous_methods == null)
3844 anonymous_methods = new ArrayList ();
3845 anonymous_methods.Add (anonymous);
3848 protected bool DefineGenericMethod ()
3850 if (!DoDefineBase ())
3854 if (GenericMethod != null) {
3855 string method_name = MemberName.Name;
3857 if (IsExplicitImpl) {
3858 method_name = TypeManager.CSharpName (InterfaceType) +
3862 MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags);
3864 if (!GenericMethod.Define (MethodBuilder, block))
3872 public bool ResolveMembers ()
3874 if (!DefineGenericMethod ())
3877 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
3878 iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
3879 if (iterator == null)
3883 if (anonymous_methods != null) {
3884 foreach (AnonymousMethodExpression ame in anonymous_methods) {
3885 if (!ame.CreateAnonymousHelpers ())
3893 public override bool Define ()
3898 if (!CheckAbstractAndExtern (block != null))
3904 MethodData = new MethodData (
3905 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3907 if (!MethodData.Define (Parent.PartialContainer))
3910 MethodBuilder = MethodData.MethodBuilder;
3912 if (MemberType.IsAbstract && MemberType.IsSealed) {
3913 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3920 public override void Emit ()
3922 if (OptAttributes != null)
3923 OptAttributes.Emit ();
3925 if (declarative_security != null) {
3926 foreach (DictionaryEntry de in declarative_security) {
3927 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3934 protected void Error_ConditionalAttributeIsNotValid ()
3936 Report.Error (577, Location,
3937 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3938 GetSignatureForError ());
3941 public override bool MarkForDuplicationCheck ()
3943 caching_flags |= Flags.TestMethodDuplication;
3947 public override string[] ValidAttributeTargets {
3949 return attribute_targets;
3953 #region IMethodData Members
3955 public CallingConventions CallingConventions {
3957 CallingConventions cc = Parameters.CallingConvention;
3958 if (Parameters.HasArglist)
3959 block.HasVarargs = true;
3962 if ((ModFlags & Modifiers.STATIC) == 0)
3963 cc |= CallingConventions.HasThis;
3965 // FIXME: How is `ExplicitThis' used in C#?
3971 public Type ReturnType {
3977 public MemberName MethodName {
3983 public Iterator Iterator {
3984 get { return iterator; }
3987 public new Location Location {
3989 return base.Location;
3993 protected override bool CheckBase() {
3994 if (!base.CheckBase ())
3997 // TODO: Destructor should derive from MethodCore
3998 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3999 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4000 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4008 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4010 public bool IsExcluded () {
4011 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4012 return (caching_flags & Flags.Excluded) != 0;
4014 caching_flags &= ~Flags.Excluded_Undetected;
4016 if (base_method == null) {
4017 if (OptAttributes == null)
4020 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4025 foreach (Attribute a in attrs) {
4026 string condition = a.GetConditionalAttributeValue ();
4027 if (condition == null)
4030 if (RootContext.AllDefines.Contains (condition))
4034 caching_flags |= Flags.Excluded;
4038 IMethodData md = TypeManager.GetMethod (base_method);
4040 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4041 caching_flags |= Flags.Excluded;
4047 if (md.IsExcluded ()) {
4048 caching_flags |= Flags.Excluded;
4054 GenericMethod IMethodData.GenericMethod {
4056 return GenericMethod;
4064 public class SourceMethod : ISourceMethod
4069 protected SourceMethod (DeclSpace parent, MethodBase builder,
4070 ISourceFile file, Location start, Location end)
4072 this.parent = parent;
4073 this.builder = builder;
4075 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
4078 public string Name {
4079 get { return builder.Name; }
4082 public int NamespaceID {
4083 get { return parent.NamespaceEntry.SymbolFileID; }
4088 if (builder is MethodBuilder)
4089 return ((MethodBuilder) builder).GetToken ().Token;
4090 else if (builder is ConstructorBuilder)
4091 return ((ConstructorBuilder) builder).GetToken ().Token;
4093 throw new NotSupportedException ();
4097 public void CloseMethod ()
4099 if (CodeGen.SymbolWriter != null)
4100 CodeGen.SymbolWriter.CloseMethod ();
4103 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
4105 if (CodeGen.SymbolWriter == null)
4110 Location start_loc = block.StartLocation;
4111 if (start_loc.IsNull)
4114 Location end_loc = block.EndLocation;
4118 ISourceFile file = start_loc.SourceFile;
4122 return new SourceMethod (
4123 parent, builder, file, start_loc, end_loc);
4127 public class Method : MethodOrOperator, IAnonymousHost {
4130 /// Modifiers allowed in a class declaration
4132 const int AllowedModifiers =
4135 Modifiers.PROTECTED |
4136 Modifiers.INTERNAL |
4141 Modifiers.OVERRIDE |
4142 Modifiers.ABSTRACT |
4144 Modifiers.METHOD_YIELDS |
4147 const int AllowedInterfaceModifiers =
4148 Modifiers.NEW | Modifiers.UNSAFE;
4151 // return_type can be "null" for VOID values.
4153 public Method (DeclSpace parent, GenericMethod generic,
4154 Expression return_type, int mod, bool is_iface,
4155 MemberName name, Parameters parameters, Attributes attrs)
4156 : base (parent, generic, return_type, mod,
4157 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4158 is_iface, name, attrs, parameters)
4162 public override string GetSignatureForError()
4164 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4167 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4169 Report.Error (17, location,
4170 "Program `{0}' has more than one entry point defined: `{1}'",
4171 CodeGen.FileName, TypeManager.CSharpSignature(b));
4174 bool IsEntryPoint (Parameters pinfo)
4176 if (ReturnType != TypeManager.void_type &&
4177 ReturnType != TypeManager.int32_type)
4180 if (pinfo.Count == 0)
4183 if (pinfo.Count > 1)
4186 Type t = pinfo.ParameterType (0);
4188 (t.GetArrayRank () == 1) &&
4189 (TypeManager.GetElementType (t) == TypeManager.string_type) &&
4190 (pinfo.ParameterModifier (0) == Parameter.Modifier.NONE))
4196 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4198 if (a.Type == TypeManager.conditional_attribute_type) {
4199 if (IsExplicitImpl) {
4200 Error_ConditionalAttributeIsNotValid ();
4204 if (ReturnType != TypeManager.void_type) {
4205 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4209 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4210 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4215 Report.Error (582, Location, "Conditional not valid on interface members");
4219 if (MethodData.implementing != null) {
4220 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4221 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4225 for (int i = 0; i < ParameterInfo.Count; ++i) {
4226 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4227 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4233 base.ApplyAttributeBuilder (a, cb);
4236 protected override bool CheckForDuplications ()
4238 ArrayList ar = Parent.PartialContainer.Methods;
4240 int arLen = ar.Count;
4242 for (int i = 0; i < arLen; i++) {
4243 Method m = (Method) ar [i];
4244 if (IsDuplicateImplementation (m))
4249 ar = Parent.PartialContainer.Properties;
4251 for (int i = 0; i < ar.Count; ++i) {
4252 PropertyBase pb = (PropertyBase) ar [i];
4253 if (pb.AreAccessorsDuplicateImplementation (this))
4258 ar = Parent.PartialContainer.Indexers;
4260 for (int i = 0; i < ar.Count; ++i) {
4261 PropertyBase pb = (PropertyBase) ar [i];
4262 if (pb.AreAccessorsDuplicateImplementation (this))
4267 ar = Parent.PartialContainer.Events;
4269 for (int i = 0; i < ar.Count; ++i) {
4270 Event ev = (Event) ar [i];
4271 if (ev.AreAccessorsDuplicateImplementation (this))
4282 public override bool Define ()
4284 if (!base.Define ())
4287 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4288 Error1599 (Location, ReturnType);
4292 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4293 Name == "Finalize" && !(this is Destructor)) {
4294 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4298 // This is used to track the Entry Point,
4300 if (RootContext.NeedsEntryPoint && ((ModFlags & Modifiers.STATIC) != 0) &&
4302 (RootContext.MainClass == null ||
4303 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4304 if (IsEntryPoint (ParameterInfo)) {
4306 if (RootContext.EntryPoint == null) {
4307 if (Parent.IsGeneric || MemberName.IsGeneric) {
4308 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4309 GetSignatureForError ());
4311 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4312 md.SetMemberIsUsed ();
4314 RootContext.EntryPoint = MethodBuilder;
4315 RootContext.EntryPointLocation = Location;
4318 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4319 Error_DuplicateEntryPoint (MethodBuilder, Location);
4322 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4323 GetSignatureForError ());
4333 public override void Emit ()
4335 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4336 MethodData.Emit (Parent);
4343 public static void Error1599 (Location loc, Type t)
4345 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4348 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4350 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4351 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4356 if (mi.IsSpecialName)
4359 base_ret_type = mi.ReturnType;
4363 protected override bool VerifyClsCompliance ()
4365 if (!base.VerifyClsCompliance ())
4368 if (ParameterInfo.Count > 0) {
4369 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4371 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4378 public abstract class ConstructorInitializer {
4379 ArrayList argument_list;
4380 protected ConstructorInfo base_constructor;
4383 public ConstructorInitializer (ArrayList argument_list, Location loc)
4385 this.argument_list = argument_list;
4389 public ArrayList Arguments {
4391 return argument_list;
4395 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4397 Expression base_constructor_group;
4401 ec.CurrentBlock = block;
4403 if (argument_list != null){
4404 foreach (Argument a in argument_list){
4405 if (!a.Resolve (ec, loc))
4409 ec.CurrentBlock = null;
4411 if (this is ConstructorBaseInitializer) {
4412 if (ec.ContainerType.BaseType == null)
4415 t = ec.ContainerType.BaseType;
4416 if (ec.ContainerType.IsValueType) {
4417 Report.Error (522, loc,
4418 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4423 // It is legal to have "this" initializers that take no arguments
4424 // in structs, they are just no-ops.
4426 // struct D { public D (int a) : this () {}
4428 if (ec.ContainerType.IsValueType && argument_list == null)
4431 t = ec.ContainerType;
4434 base_constructor_group = Expression.MemberLookup (
4435 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4436 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4439 if (base_constructor_group == null){
4441 base_constructor_group = Expression.MemberLookup (
4442 t, null, t, ".ctor", MemberTypes.Constructor,
4443 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4447 int errors = Report.Errors;
4448 if (base_constructor_group != null)
4449 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4450 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4453 if (base_constructor == null) {
4454 if (errors == Report.Errors)
4455 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4456 argument_list == null ? 0 : argument_list.Count);
4461 Report.SymbolRelatedToPreviousError (base_constructor);
4462 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4463 base_constructor = null;
4467 if (base_constructor == caller_builder){
4468 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4475 public virtual void Emit (EmitContext ec)
4477 if (base_constructor != null){
4478 ec.Mark (loc, false);
4480 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4482 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4487 public class ConstructorBaseInitializer : ConstructorInitializer {
4488 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4489 base (argument_list, l)
4494 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4495 public GeneratedBaseInitializer (Location loc):
4501 public class ConstructorThisInitializer : ConstructorInitializer {
4502 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4503 base (argument_list, l)
4508 public class Constructor : MethodCore, IMethodData, IAnonymousHost {
4509 public ConstructorBuilder ConstructorBuilder;
4510 public ConstructorInitializer Initializer;
4511 ListDictionary declarative_security;
4512 ArrayList anonymous_methods;
4515 // Modifiers allowed for a constructor.
4517 public const int AllowedModifiers =
4519 Modifiers.PROTECTED |
4520 Modifiers.INTERNAL |
4526 static string[] attribute_targets = new string [] { "method" };
4528 public Iterator Iterator {
4529 get { return null; }
4532 bool has_compliant_args = false;
4534 // The spec claims that static is not permitted, but
4535 // my very own code has static constructors.
4537 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4538 ConstructorInitializer init, Location loc)
4539 : base (parent, null, null, mod, AllowedModifiers, false,
4540 new MemberName (name, loc), null, args)
4545 public bool HasCompliantArgs {
4546 get { return has_compliant_args; }
4549 public override AttributeTargets AttributeTargets {
4550 get { return AttributeTargets.Constructor; }
4555 // Returns true if this is a default constructor
4557 public bool IsDefault ()
4559 if ((ModFlags & Modifiers.STATIC) != 0)
4560 return Parameters.Empty;
4562 return Parameters.Empty &&
4563 (Initializer is ConstructorBaseInitializer) &&
4564 (Initializer.Arguments == null);
4567 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4569 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4570 if (declarative_security == null) {
4571 declarative_security = new ListDictionary ();
4573 a.ExtractSecurityPermissionSet (declarative_security);
4577 if (a.Type == TypeManager.methodimpl_attr_type &&
4578 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4579 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4582 ConstructorBuilder.SetCustomAttribute (cb);
4585 public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
4587 if (anonymous_methods == null)
4588 anonymous_methods = new ArrayList ();
4589 anonymous_methods.Add (anonymous);
4592 public bool ResolveMembers ()
4594 if (anonymous_methods != null) {
4595 foreach (AnonymousMethodExpression ame in anonymous_methods) {
4596 if (!ame.CreateAnonymousHelpers ())
4604 protected override bool CheckForDuplications ()
4606 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4608 int arLen = ar.Count;
4610 for (int i = 0; i < arLen; i++) {
4611 Constructor m = (Constructor) ar [i];
4612 if (IsDuplicateImplementation (m))
4619 protected override bool CheckBase ()
4621 if ((ModFlags & Modifiers.STATIC) != 0) {
4622 if (!Parameters.Empty) {
4623 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4624 GetSignatureForError ());
4628 // the rest can be ignored
4632 // Check whether arguments were correct.
4633 if (!DoDefineParameters ())
4636 if (!CheckForDuplications ())
4639 if (Parent.PartialContainer.Kind == Kind.Struct) {
4640 if (ParameterTypes.Length == 0) {
4641 Report.Error (568, Location,
4642 "Structs cannot contain explicit parameterless constructors");
4646 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4647 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4652 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4653 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4660 // Creates the ConstructorBuilder
4662 public override bool Define ()
4664 if (ConstructorBuilder != null)
4667 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4668 MethodAttributes.SpecialName);
4670 if ((ModFlags & Modifiers.STATIC) != 0) {
4671 ca |= MethodAttributes.Static | MethodAttributes.Private;
4673 ca |= MethodAttributes.HideBySig;
4675 if ((ModFlags & Modifiers.PUBLIC) != 0)
4676 ca |= MethodAttributes.Public;
4677 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4678 if ((ModFlags & Modifiers.INTERNAL) != 0)
4679 ca |= MethodAttributes.FamORAssem;
4681 ca |= MethodAttributes.Family;
4682 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4683 ca |= MethodAttributes.Assembly;
4685 ca |= MethodAttributes.Private;
4688 if (!CheckAbstractAndExtern (block != null))
4691 // Check if arguments were correct.
4695 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4696 ca, CallingConventions,
4699 if ((ModFlags & Modifiers.UNSAFE) != 0)
4700 ConstructorBuilder.InitLocals = false;
4702 if (Parent.PartialContainer.IsComImport) {
4703 if (!IsDefault ()) {
4704 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4705 Parent.GetSignatureForError ());
4708 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4711 TypeManager.AddMethod (ConstructorBuilder, this);
4719 public override void Emit ()
4721 if (OptAttributes != null)
4722 OptAttributes.Emit ();
4724 EmitContext ec = CreateEmitContext (null, null);
4726 if (block != null) {
4727 // If this is a non-static `struct' constructor and doesn't have any
4728 // initializer, it must initialize all of the struct's fields.
4729 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4730 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4731 block.AddThisVariable (Parent, Location);
4733 if (!block.ResolveMeta (ec, ParameterInfo))
4737 if ((ModFlags & Modifiers.STATIC) == 0){
4738 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4739 Initializer = new GeneratedBaseInitializer (Location);
4743 // Spec mandates that Initializers will not have
4747 if ((Initializer != null) &&
4748 !Initializer.Resolve (ConstructorBuilder, block, ec))
4750 ec.IsStatic = false;
4753 Parameters.ApplyAttributes (ConstructorBuilder);
4755 SourceMethod source = SourceMethod.Create (
4756 Parent, ConstructorBuilder, block);
4759 // Classes can have base initializers and instance field initializers.
4761 if (Parent.PartialContainer.Kind == Kind.Class){
4762 if ((ModFlags & Modifiers.STATIC) == 0){
4765 // If we use a "this (...)" constructor initializer, then
4766 // do not emit field initializers, they are initialized in the other constructor
4768 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4769 Parent.PartialContainer.EmitFieldInitializers (ec);
4773 bool unreachable = false;
4774 if (block != null) {
4775 ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable);
4776 ec.EmitMeta (block);
4778 if (block.ScopeInfo != null) {
4779 ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
4780 init.EmitStatement (ec);
4784 if (Initializer != null) {
4785 Initializer.Emit (ec);
4788 if ((ModFlags & Modifiers.STATIC) != 0)
4789 Parent.PartialContainer.EmitFieldInitializers (ec);
4792 ec.EmitResolvedTopBlock (block, unreachable);
4795 source.CloseMethod ();
4799 if (declarative_security != null) {
4800 foreach (DictionaryEntry de in declarative_security) {
4801 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4808 // Is never override
4809 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4814 public override string GetSignatureForError()
4816 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4819 public override string[] ValidAttributeTargets {
4821 return attribute_targets;
4825 protected override bool VerifyClsCompliance ()
4827 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4831 if (ParameterInfo.Count > 0) {
4832 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4834 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4836 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4837 foreach (Type param in ParameterTypes) {
4838 if (param.IsArray) {
4844 has_compliant_args = true;
4848 #region IMethodData Members
4850 public System.Reflection.CallingConventions CallingConventions {
4852 CallingConventions cc = Parameters.CallingConvention;
4854 if (Parent.PartialContainer.Kind == Kind.Class)
4855 if ((ModFlags & Modifiers.STATIC) == 0)
4856 cc |= CallingConventions.HasThis;
4858 // FIXME: How is `ExplicitThis' used in C#?
4864 public new Location Location {
4866 return base.Location;
4870 public MemberName MethodName {
4876 public Type ReturnType {
4882 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4884 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4885 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4888 public bool IsExcluded()
4893 GenericMethod IMethodData.GenericMethod {
4903 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4905 public interface IMethodData
4907 CallingConventions CallingConventions { get; }
4908 Location Location { get; }
4909 MemberName MethodName { get; }
4910 Type ReturnType { get; }
4911 GenericMethod GenericMethod { get; }
4912 Parameters ParameterInfo { get; }
4914 Iterator Iterator { get; }
4916 Attributes OptAttributes { get; }
4917 ToplevelBlock Block { get; set; }
4919 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4920 ObsoleteAttribute GetObsoleteAttribute ();
4921 string GetSignatureForError ();
4923 bool IsClsComplianceRequired ();
4924 void SetMemberIsUsed ();
4928 // Encapsulates most of the Method's state
4930 public class MethodData {
4932 readonly IMethodData method;
4934 public readonly GenericMethod GenericMethod;
4937 // Are we implementing an interface ?
4939 public MethodInfo implementing;
4944 protected MemberBase member;
4945 protected int modifiers;
4946 protected MethodAttributes flags;
4947 protected Type declaring_type;
4948 protected MethodInfo parent_method;
4950 MethodBuilder builder = null;
4951 public MethodBuilder MethodBuilder {
4957 public Type DeclaringType {
4959 return declaring_type;
4963 public MethodData (MemberBase member,
4964 int modifiers, MethodAttributes flags, IMethodData method)
4966 this.member = member;
4967 this.modifiers = modifiers;
4970 this.method = method;
4973 public MethodData (MemberBase member,
4974 int modifiers, MethodAttributes flags,
4975 IMethodData method, MethodBuilder builder,
4976 GenericMethod generic, MethodInfo parent_method)
4977 : this (member, modifiers, flags, method)
4979 this.builder = builder;
4980 this.GenericMethod = generic;
4981 this.parent_method = parent_method;
4984 public bool Define (DeclSpace parent)
4986 string name = method.MethodName.Basename;
4987 string method_name = method.MethodName.FullName;
4989 TypeContainer container = parent.PartialContainer;
4991 PendingImplementation pending = container.PendingImplementations;
4992 if (pending != null){
4993 if (member is Indexer) // TODO: test it, but it should work without this IF
4994 implementing = pending.IsInterfaceIndexer (
4995 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4997 implementing = pending.IsInterfaceMethod (
4998 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
5000 if (member.InterfaceType != null){
5001 if (implementing == null){
5002 if (member is PropertyBase) {
5003 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5004 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5005 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5008 Report.Error (539, method.Location,
5009 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5010 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5014 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5015 Report.SymbolRelatedToPreviousError (implementing);
5016 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5017 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5021 method_name = TypeManager.GetFullName (member.InterfaceType) +
5024 if (implementing != null) {
5025 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5026 if (prop_method == null) {
5027 if (implementing.IsSpecialName) {
5028 Report.SymbolRelatedToPreviousError (implementing);
5029 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
5030 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
5031 implementing.Name.StartsWith ("get_") ? "get" : "set");
5034 } else if (implementing.DeclaringType.IsInterface) {
5035 if (!implementing.IsSpecialName) {
5036 Report.SymbolRelatedToPreviousError (implementing);
5037 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5038 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5041 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5042 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5043 Report.SymbolRelatedToPreviousError (implementing);
5044 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5045 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5054 // For implicit implementations, make sure we are public, for
5055 // explicit implementations, make sure we are private.
5057 if (implementing != null){
5059 // Setting null inside this block will trigger a more
5060 // verbose error reporting for missing interface implementations
5062 // The "candidate" function has been flagged already
5063 // but it wont get cleared
5065 if (member.IsExplicitImpl){
5066 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
5067 Report.SymbolRelatedToPreviousError (implementing);
5068 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
5069 method.GetSignatureForError ());
5072 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5073 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5075 // If this is an interface method implementation,
5076 // check for public accessibility
5078 implementing = null;
5079 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5080 // We may never be private.
5081 implementing = null;
5082 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5084 // We may be protected if we're overriding something.
5086 implementing = null;
5091 // Static is not allowed
5093 if ((modifiers & Modifiers.STATIC) != 0){
5094 implementing = null;
5099 // If implementing is still valid, set flags
5101 if (implementing != null){
5103 // When implementing interface methods, set NewSlot
5104 // unless, we are overwriting a method.
5106 if (implementing.DeclaringType.IsInterface){
5107 if ((modifiers & Modifiers.OVERRIDE) == 0)
5108 flags |= MethodAttributes.NewSlot;
5111 MethodAttributes.Virtual |
5112 MethodAttributes.HideBySig;
5114 // Set Final unless we're virtual, abstract or already overriding a method.
5115 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5116 flags |= MethodAttributes.Final;
5119 EmitContext ec = method.CreateEmitContext (container, null);
5121 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
5123 if (builder == null)
5126 if (container.CurrentType != null)
5127 declaring_type = container.CurrentType;
5129 declaring_type = container.TypeBuilder;
5131 if ((modifiers & Modifiers.UNSAFE) != 0)
5132 builder.InitLocals = false;
5134 if (implementing != null){
5136 // clear the pending implemntation flag
5138 if (member is Indexer) {
5139 pending.ImplementIndexer (
5140 member.InterfaceType, builder, method.ReturnType,
5141 method.ParameterInfo, member.IsExplicitImpl);
5143 pending.ImplementMethod (
5144 member.InterfaceType, name, method.ReturnType,
5145 method.ParameterInfo, member.IsExplicitImpl);
5147 if (member.IsExplicitImpl)
5148 container.TypeBuilder.DefineMethodOverride (
5149 builder, implementing);
5153 TypeManager.AddMethod (builder, method);
5155 if (GenericMethod != null) {
5156 bool is_override = member.IsExplicitImpl |
5157 ((modifiers & Modifiers.OVERRIDE) != 0);
5159 if (implementing != null)
5160 parent_method = implementing;
5162 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5171 /// Create the MethodBuilder for the method
5173 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5175 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5177 if ((modifiers & extern_static) == extern_static) {
5179 if (method.OptAttributes != null) {
5180 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
5181 if (dllimport_attribute != null) {
5182 flags |= MethodAttributes.PinvokeImpl;
5183 builder = dllimport_attribute.DefinePInvokeMethod (
5184 container.TypeBuilder, method_name, flags,
5185 method.ReturnType, ParameterTypes);
5191 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5192 // We are more strict than Microsoft and report CS0626 like error
5193 if (method.OptAttributes == null ||
5194 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
5195 Report.Error (626, method.Location, "Method, operator, or accessor `{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation",
5196 method.GetSignatureForError ());
5201 if (builder == null) {
5202 builder = container.TypeBuilder.DefineMethod (
5203 method_name, flags, method.CallingConventions,
5204 method.ReturnType, ParameterTypes);
5208 #if GMCS_SOURCE && !MS_COMPATIBLE
5209 builder.SetGenericMethodSignature (
5210 flags, method.CallingConventions,
5211 method.ReturnType, ParameterTypes);
5218 public void Emit (DeclSpace parent)
5221 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5222 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5224 ec = method.CreateEmitContext (parent, null);
5226 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5228 if (GenericMethod != null)
5229 GenericMethod.EmitAttributes ();
5231 ToplevelBlock block = method.Block;
5233 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5236 // Handle destructors specially
5238 // FIXME: This code generates buggy code
5240 if (member is Destructor)
5241 EmitDestructor (ec, block);
5243 ec.EmitTopBlock (method, block);
5246 source.CloseMethod ();
5249 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5251 ILGenerator ig = ec.ig;
5253 Label finish = ig.DefineLabel ();
5255 block.SetDestructor ();
5257 ig.BeginExceptionBlock ();
5258 ec.ReturnLabel = finish;
5259 ec.HasReturnLabel = true;
5260 ec.EmitTopBlock (method, block);
5262 // ig.MarkLabel (finish);
5263 ig.BeginFinallyBlock ();
5265 if (ec.ContainerType.BaseType != null) {
5266 Expression member_lookup = Expression.MemberLookup (
5267 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5268 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5270 if (member_lookup != null){
5271 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5273 ig.Emit (OpCodes.Ldarg_0);
5274 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5278 ig.EndExceptionBlock ();
5279 //ig.MarkLabel (ec.ReturnLabel);
5280 ig.Emit (OpCodes.Ret);
5284 // TODO: Should derive from MethodCore
5285 public class Destructor : Method {
5287 static string[] attribute_targets = new string [] { "method" };
5289 public Destructor (DeclSpace parent, Expression return_type, int mod,
5290 string name, Parameters parameters, Attributes attrs,
5292 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5296 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5298 if (a.Type == TypeManager.conditional_attribute_type) {
5299 Error_ConditionalAttributeIsNotValid ();
5303 base.ApplyAttributeBuilder (a, cb);
5306 public override string GetSignatureForError ()
5308 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5311 public override string[] ValidAttributeTargets {
5313 return attribute_targets;
5318 abstract public class MemberBase : MemberCore {
5319 public Expression Type;
5321 public MethodAttributes flags;
5322 public readonly DeclSpace ds;
5323 public readonly GenericMethod GenericMethod;
5325 protected readonly int explicit_mod_flags;
5328 // The "short" name of this property / indexer / event. This is the
5329 // name without the explicit interface.
5331 public string ShortName {
5332 get { return MemberName.Name; }
5333 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
5337 // The type of this property / indexer / event
5339 protected Type member_type;
5340 public Type MemberType {
5342 if (member_type == null && Type != null) {
5343 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5344 Type = Type.ResolveAsTypeTerminal (rc, false);
5346 member_type = Type.Type;
5354 // Whether this is an interface member.
5356 public bool IsInterface;
5359 // If true, this is an explicit interface implementation
5361 public bool IsExplicitImpl;
5364 // The interface type we are explicitly implementing
5366 public Type InterfaceType = null;
5369 // The constructor is only exposed to our children
5371 protected MemberBase (DeclSpace parent, GenericMethod generic,
5372 Expression type, int mod, int allowed_mod, int def_mod,
5373 MemberName name, Attributes attrs)
5374 : base (parent, name, attrs)
5376 this.ds = generic != null ? generic : (DeclSpace) parent;
5377 explicit_mod_flags = mod;
5379 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5380 IsExplicitImpl = (MemberName.Left != null);
5381 GenericMethod = generic;
5382 if (GenericMethod != null)
5383 GenericMethod.ModFlags = ModFlags;
5386 protected virtual bool CheckBase ()
5388 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5389 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5393 if ((RootContext.WarningLevel >= 4) &&
5394 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5395 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5396 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5397 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5402 protected virtual bool DoDefineBase ()
5405 throw new InternalErrorException ();
5408 ModFlags = Modifiers.PUBLIC |
5409 Modifiers.ABSTRACT |
5410 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5412 flags = MethodAttributes.Public |
5413 MethodAttributes.Abstract |
5414 MethodAttributes.HideBySig |
5415 MethodAttributes.NewSlot |
5416 MethodAttributes.Virtual;
5418 if (!Parent.PartialContainer.MethodModifiersValid (this))
5421 flags = Modifiers.MethodAttr (ModFlags);
5424 if (IsExplicitImpl) {
5425 Expression expr = MemberName.Left.GetTypeExpression ();
5426 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
5427 if (iface_texpr == null)
5430 InterfaceType = iface_texpr.Type;
5432 if (!InterfaceType.IsInterface) {
5433 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5437 if (!Parent.PartialContainer.VerifyImplements (this))
5440 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5446 protected virtual bool DoDefine ()
5448 if (MemberType == null)
5451 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5452 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5453 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5454 GetSignatureForError (), Parent.GetSignatureForError ());
5458 // verify accessibility
5459 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5460 Report.SymbolRelatedToPreviousError (MemberType);
5461 if (this is Property)
5462 Report.Error (53, Location,
5463 "Inconsistent accessibility: property type `" +
5464 TypeManager.CSharpName (MemberType) + "' is less " +
5465 "accessible than property `" + GetSignatureForError () + "'");
5466 else if (this is Indexer)
5467 Report.Error (54, Location,
5468 "Inconsistent accessibility: indexer return type `" +
5469 TypeManager.CSharpName (MemberType) + "' is less " +
5470 "accessible than indexer `" + GetSignatureForError () + "'");
5471 else if (this is MethodCore) {
5472 if (this is Operator)
5473 Report.Error (56, Location,
5474 "Inconsistent accessibility: return type `" +
5475 TypeManager.CSharpName (MemberType) + "' is less " +
5476 "accessible than operator `" + GetSignatureForError () + "'");
5478 Report.Error (50, Location,
5479 "Inconsistent accessibility: return type `" +
5480 TypeManager.CSharpName (MemberType) + "' is less " +
5481 "accessible than method `" + GetSignatureForError () + "'");
5483 Report.Error (52, Location,
5484 "Inconsistent accessibility: field type `" +
5485 TypeManager.CSharpName (MemberType) + "' is less " +
5486 "accessible than field `" + GetSignatureForError () + "'");
5491 if (IsExplicitImpl) {
5492 Expression expr = MemberName.Left.GetTypeExpression ();
5493 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
5497 InterfaceType = texpr.Type;
5499 if (!InterfaceType.IsInterface) {
5500 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5504 if (!Parent.PartialContainer.VerifyImplements (this))
5512 protected bool IsTypePermitted ()
5514 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5515 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5521 protected override bool VerifyClsCompliance()
5523 if (base.VerifyClsCompliance ()) {
5524 if (GenericMethod != null)
5525 GenericMethod.VerifyClsCompliance ();
5530 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
5531 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5539 // Fields and Events both generate FieldBuilders, we use this to share
5540 // their common bits. This is also used to flag usage of the field
5542 abstract public class FieldBase : MemberBase {
5543 public FieldBuilder FieldBuilder;
5544 public Status status;
5545 protected Expression initializer;
5546 ExpressionStatement initializerStatement;
5549 public enum Status : byte {
5550 HAS_OFFSET = 4 // Used by FieldMember.
5553 static string[] attribute_targets = new string [] { "field" };
5556 /// Symbol with same name in base class/struct
5558 public MemberInfo conflict_symbol;
5560 protected FieldBase (DeclSpace parent, Expression type, int mod,
5561 int allowed_mod, MemberName name, Attributes attrs)
5562 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5567 public override AttributeTargets AttributeTargets {
5569 return AttributeTargets.Field;
5573 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5575 if (a.Type == TypeManager.marshal_as_attr_type) {
5576 UnmanagedMarshal marshal = a.GetMarshal (this);
5577 if (marshal != null) {
5578 FieldBuilder.SetMarshal (marshal);
5583 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5584 a.Error_InvalidSecurityParent ();
5588 FieldBuilder.SetCustomAttribute (cb);
5591 public void EmitInitializer (EmitContext ec)
5593 initializerStatement.EmitStatement (ec);
5596 protected override bool CheckBase ()
5598 if (!base.CheckBase ())
5605 conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5606 if (conflict_symbol == null) {
5607 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5608 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5613 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5614 Report.SymbolRelatedToPreviousError (conflict_symbol);
5615 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5616 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5622 public Expression Initializer {
5624 if (value != null) {
5625 this.initializer = value;
5626 Parent.PartialContainer.RegisterFieldForInitialization (this);
5631 protected virtual bool IsFieldClsCompliant {
5633 if (FieldBuilder == null)
5636 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5640 public Expression ResolveInitializer ()
5642 // TODO: again it's too heavy-weight
5643 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5644 ec.IsFieldInitializer = true;
5645 initializer = initializer.Resolve (ec);
5646 if (initializer == null)
5648 if (FieldBuilder == null)
5651 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5652 if ((ModFlags & Modifiers.STATIC) == 0)
5654 fe.InstanceExpression = CompilerGeneratedThis.Instance;
5657 initializerStatement = new Assign (fe, initializer, Location).ResolveStatement (ec);
5661 public bool HasDefaultInitializer
5665 Constant c = initializer as Constant;
5669 return c.IsDefaultInitializer (MemberType);
5673 public override string[] ValidAttributeTargets
5676 return attribute_targets;
5680 protected override bool VerifyClsCompliance ()
5682 if (!base.VerifyClsCompliance ())
5685 if (!IsFieldClsCompliant) {
5686 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5692 public void SetAssigned ()
5694 caching_flags |= Flags.IsAssigned;
5698 public abstract class FieldMember : FieldBase
5700 protected FieldMember (DeclSpace parent, Expression type, int mod,
5701 int allowed_mod, MemberName name, Attributes attrs)
5702 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5704 if ((mod & Modifiers.ABSTRACT) != 0)
5705 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5708 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5710 if (a.Type == TypeManager.field_offset_attribute_type)
5712 status |= Status.HAS_OFFSET;
5714 if (!Parent.PartialContainer.HasExplicitLayout) {
5715 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5719 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5720 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5726 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5727 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5732 base.ApplyAttributeBuilder (a, cb);
5735 public override bool Define()
5737 if (MemberType == null || Type == null)
5740 if (MemberType == TypeManager.void_type) {
5741 // TODO: wrong location
5742 Expression.Error_VoidInvalidInTheContext (Location);
5746 if (MemberType.IsSealed && MemberType.IsAbstract) {
5747 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5754 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5755 Report.Error (52, Location,
5756 "Inconsistent accessibility: field type `" +
5757 TypeManager.CSharpName (MemberType) + "' is less " +
5758 "accessible than field `" + GetSignatureForError () + "'");
5762 if (!IsTypePermitted ())
5768 public override void Emit ()
5770 if (OptAttributes != null) {
5771 OptAttributes.Emit ();
5774 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5775 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5781 public static void Error_VariableOfStaticClass (Location loc, string variableName, Type staticClass)
5783 Report.SymbolRelatedToPreviousError (staticClass);
5784 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5789 // Represents header string for documentation comment.
5791 public override string DocCommentHeader {
5792 get { return "F:"; }
5796 interface IFixedBuffer
5798 FieldInfo Element { get; }
5799 Type ElementType { get; }
5802 public class FixedFieldExternal: IFixedBuffer
5804 FieldInfo element_field;
5806 public FixedFieldExternal (FieldInfo fi)
5808 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5811 #region IFixedField Members
5813 public FieldInfo Element {
5815 return element_field;
5819 public Type ElementType {
5821 return element_field.FieldType;
5829 /// Fixed buffer implementation
5831 public class FixedField : FieldMember, IFixedBuffer
5833 public const string FixedElementName = "FixedElementField";
5834 static int GlobalCounter = 0;
5835 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5836 static FieldInfo[] fi;
5838 TypeBuilder fixed_buffer_type;
5839 FieldBuilder element;
5840 Expression size_expr;
5843 const int AllowedModifiers =
5846 Modifiers.PROTECTED |
5847 Modifiers.INTERNAL |
5850 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5851 Expression size_expr, Attributes attrs, Location loc):
5852 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5854 if (RootContext.Version == LanguageVersion.ISO_1)
5855 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5857 this.size_expr = size_expr;
5860 public override bool Define()
5863 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5864 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5867 if (Parent.PartialContainer.Kind != Kind.Struct) {
5868 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5869 GetSignatureForError ());
5873 if (!base.Define ())
5876 if (!TypeManager.IsPrimitiveType (MemberType)) {
5877 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",
5878 GetSignatureForError ());
5882 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5883 Constant c = size_expr.ResolveAsConstant (ec, this);
5887 IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
5888 if (buffer_size_const == null)
5891 buffer_size = buffer_size_const.Value;
5893 if (buffer_size <= 0) {
5894 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5898 int type_size = Expression.GetTypeSize (MemberType);
5900 if (buffer_size > int.MaxValue / type_size) {
5901 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5902 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5906 buffer_size *= type_size;
5909 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5911 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5912 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5913 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5914 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5916 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5917 TypeManager.RegisterFieldBase (FieldBuilder, this);
5922 public override void Emit()
5925 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5927 object[] fi_val = new object[1];
5928 fi_val [0] = buffer_size;
5930 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5931 ctor_args, fi, fi_val);
5932 fixed_buffer_type.SetCustomAttribute (cab);
5935 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5936 FieldBuilder.SetCustomAttribute (cab);
5941 protected override bool IsFieldClsCompliant {
5947 #region IFixedField Members
5949 public FieldInfo Element {
5955 public Type ElementType {
5965 // The Field class is used to represents class/struct fields during parsing.
5967 public class Field : FieldMember {
5969 // Modifiers allowed in a class declaration
5971 const int AllowedModifiers =
5974 Modifiers.PROTECTED |
5975 Modifiers.INTERNAL |
5978 Modifiers.VOLATILE |
5982 public Field (DeclSpace parent, Expression type, int mod, string name,
5983 Attributes attrs, Location loc)
5984 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5989 public override bool Define ()
5991 if (!base.Define ())
5994 if (RootContext.WarningLevel > 1){
5995 Type ptype = Parent.TypeBuilder.BaseType;
5997 // ptype is only null for System.Object while compiling corlib.
5999 TypeContainer.FindMembers (
6000 ptype, MemberTypes.Method,
6001 BindingFlags.Public |
6002 BindingFlags.Static | BindingFlags.Instance,
6003 System.Type.FilterName, Name);
6007 if ((ModFlags & Modifiers.VOLATILE) != 0){
6008 if (!MemberType.IsClass){
6009 Type vt = MemberType;
6011 if (TypeManager.IsEnumType (vt))
6012 vt = TypeManager.EnumToUnderlying (MemberType);
6014 if (!((vt == TypeManager.bool_type) ||
6015 (vt == TypeManager.sbyte_type) ||
6016 (vt == TypeManager.byte_type) ||
6017 (vt == TypeManager.short_type) ||
6018 (vt == TypeManager.ushort_type) ||
6019 (vt == TypeManager.int32_type) ||
6020 (vt == TypeManager.uint32_type) ||
6021 (vt == TypeManager.char_type) ||
6022 (vt == TypeManager.float_type) ||
6023 (!vt.IsValueType))){
6024 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6025 GetSignatureForError (), TypeManager.CSharpName (vt));
6030 if ((ModFlags & Modifiers.READONLY) != 0){
6031 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6032 GetSignatureForError ());
6037 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6039 if (Parent.PartialContainer.Kind == Kind.Struct &&
6040 ((fa & FieldAttributes.Static) == 0) &&
6041 MemberType == Parent.TypeBuilder &&
6042 !TypeManager.IsBuiltinType (MemberType)){
6043 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6044 "' causes a cycle in the structure layout");
6049 FieldBuilder = Parent.TypeBuilder.DefineField (
6050 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6052 TypeManager.RegisterFieldBase (FieldBuilder, this);
6054 catch (ArgumentException) {
6055 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6062 protected override bool VerifyClsCompliance ()
6064 if (!base.VerifyClsCompliance ())
6067 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6068 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6076 // `set' and `get' accessors are represented with an Accessor.
6078 public class Accessor : IAnonymousHost {
6080 // Null if the accessor is empty, or a Block if not
6082 public const int AllowedModifiers =
6084 Modifiers.PROTECTED |
6085 Modifiers.INTERNAL |
6088 public ToplevelBlock Block;
6089 public Attributes Attributes;
6090 public Location Location;
6091 public int ModFlags;
6093 public ArrayList AnonymousMethods;
6095 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6100 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6103 public void SetYields ()
6108 public void AddAnonymousMethod (AnonymousMethodExpression ame)
6110 if (AnonymousMethods == null)
6111 AnonymousMethods = new ArrayList ();
6112 AnonymousMethods.Add (ame);
6116 // Ooouh Martin, templates are missing here.
6117 // When it will be possible move here a lot of child code and template method type.
6118 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6119 protected MethodData method_data;
6120 protected ToplevelBlock block;
6121 protected ListDictionary declarative_security;
6123 // The accessor are created event if they are not wanted.
6124 // But we need them because their names are reserved.
6125 // Field says whether accessor will be emited or not
6126 public readonly bool IsDummy;
6128 protected readonly string prefix;
6130 ReturnParameter return_attributes;
6132 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6133 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6135 this.prefix = prefix;
6139 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6141 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6142 accessor.Attributes)
6144 this.prefix = prefix;
6145 this.block = accessor.Block;
6148 static MemberName SetupName (string prefix, MemberBase member, Location loc)
6150 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6153 public void UpdateName (MemberBase member)
6155 SetMemberName (SetupName (prefix, member, Location));
6158 #region IMethodData Members
6160 public abstract Iterator Iterator {
6164 public ToplevelBlock Block {
6174 public CallingConventions CallingConventions {
6176 return CallingConventions.Standard;
6180 public bool IsExcluded ()
6185 GenericMethod IMethodData.GenericMethod {
6191 public MemberName MethodName {
6197 public Type[] ParameterTypes {
6199 return ParameterInfo.Types;
6203 public abstract Parameters ParameterInfo { get ; }
6204 public abstract Type ReturnType { get; }
6205 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6209 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6211 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6212 a.Type == TypeManager.conditional_attribute_type) {
6213 Report.Error (1667, a.Location,
6214 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6215 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6219 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6220 if (declarative_security == null)
6221 declarative_security = new ListDictionary ();
6222 a.ExtractSecurityPermissionSet (declarative_security);
6226 if (a.Target == AttributeTargets.Method) {
6227 method_data.MethodBuilder.SetCustomAttribute (cb);
6231 if (a.Target == AttributeTargets.ReturnValue) {
6232 if (return_attributes == null)
6233 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6235 return_attributes.ApplyAttributeBuilder (a, cb);
6239 ApplyToExtraTarget (a, cb);
6242 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6244 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6247 public override bool Define()
6249 throw new NotSupportedException ();
6252 public void Emit (DeclSpace parent)
6254 EmitMethod (parent);
6256 if (OptAttributes != null)
6257 OptAttributes.Emit ();
6259 if (declarative_security != null) {
6260 foreach (DictionaryEntry de in declarative_security) {
6261 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6268 protected virtual void EmitMethod (DeclSpace parent)
6270 method_data.Emit (parent);
6273 public override bool IsClsComplianceRequired()
6278 public bool IsDuplicateImplementation (MethodCore method)
6280 if (!MemberName.Equals (method.MemberName))
6283 Type[] param_types = method.ParameterTypes;
6285 if (param_types.Length != ParameterTypes.Length)
6288 for (int i = 0; i < param_types.Length; i++)
6289 if (param_types [i] != ParameterTypes [i])
6292 Report.SymbolRelatedToPreviousError (method);
6293 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6297 public override bool IsUsed
6307 public new Location Location {
6309 return base.Location;
6314 // Represents header string for documentation comment.
6316 public override string DocCommentHeader {
6317 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6323 // Properties and Indexers both generate PropertyBuilders, we use this to share
6324 // their common bits.
6326 abstract public class PropertyBase : MethodCore {
6328 public class GetMethod : PropertyMethod
6330 static string[] attribute_targets = new string [] { "method", "return" };
6332 public GetMethod (MethodCore method):
6333 base (method, "get_")
6337 public GetMethod (MethodCore method, Accessor accessor):
6338 base (method, accessor, "get_")
6342 public override MethodBuilder Define (DeclSpace parent)
6344 base.Define (parent);
6346 method_data = new MethodData (method, ModFlags, flags, this);
6348 if (!method_data.Define (parent))
6351 return method_data.MethodBuilder;
6354 public override Type ReturnType {
6356 return method.MemberType;
6360 public override Parameters ParameterInfo {
6362 return Parameters.EmptyReadOnlyParameters;
6366 public override string[] ValidAttributeTargets {
6368 return attribute_targets;
6373 public class SetMethod : PropertyMethod {
6375 static string[] attribute_targets = new string [] { "method", "param", "return" };
6376 ImplicitParameter param_attr;
6377 protected Parameters parameters;
6379 public SetMethod (MethodCore method):
6380 base (method, "set_")
6384 public SetMethod (MethodCore method, Accessor accessor):
6385 base (method, accessor, "set_")
6389 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6391 if (a.Target == AttributeTargets.Parameter) {
6392 if (param_attr == null)
6393 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6395 param_attr.ApplyAttributeBuilder (a, cb);
6399 base.ApplyAttributeBuilder (a, cb);
6402 public override Parameters ParameterInfo {
6408 protected virtual void DefineParameters ()
6410 parameters = new Parameters (
6411 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6412 new Type[] { method.MemberType });
6415 public override MethodBuilder Define (DeclSpace parent)
6417 DefineParameters ();
6421 base.Define (parent);
6423 method_data = new MethodData (method, ModFlags, flags, this);
6425 if (!method_data.Define (parent))
6428 return method_data.MethodBuilder;
6431 public override Type ReturnType {
6433 return TypeManager.void_type;
6437 public override string[] ValidAttributeTargets {
6439 return attribute_targets;
6444 static string[] attribute_targets = new string [] { "property" };
6446 public abstract class PropertyMethod : AbstractPropertyEventMethod
6448 protected readonly MethodCore method;
6449 protected MethodAttributes flags;
6451 ArrayList anonymous_methods;
6454 public PropertyMethod (MethodCore method, string prefix)
6455 : base (method, prefix)
6457 this.method = method;
6460 public PropertyMethod (MethodCore method, Accessor accessor,
6462 : base (method, accessor, prefix)
6464 this.method = method;
6465 this.ModFlags = accessor.ModFlags;
6466 yields = accessor.Yields;
6467 anonymous_methods = accessor.AnonymousMethods;
6469 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6470 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6474 public override Iterator Iterator {
6475 get { return iterator; }
6478 public override AttributeTargets AttributeTargets {
6480 return AttributeTargets.Method;
6484 public override bool IsClsComplianceRequired ()
6486 return method.IsClsComplianceRequired ();
6489 public bool ResolveMembers ()
6492 iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
6493 if (iterator == null)
6497 if (anonymous_methods != null) {
6498 foreach (AnonymousMethodExpression ame in anonymous_methods) {
6499 if (!ame.CreateAnonymousHelpers ())
6507 public virtual MethodBuilder Define (DeclSpace parent)
6509 if (!method.CheckAbstractAndExtern (block != null))
6512 TypeContainer container = parent.PartialContainer;
6515 // Check for custom access modifier
6517 if (ModFlags == 0) {
6518 ModFlags = method.ModFlags;
6519 flags = method.flags;
6521 if (container.Kind == Kind.Interface)
6522 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6523 GetSignatureForError ());
6525 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6526 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6529 CheckModifiers (ModFlags);
6530 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6531 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6532 flags = Modifiers.MethodAttr (ModFlags);
6533 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6539 public bool HasCustomAccessModifier
6542 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6546 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6548 return new EmitContext (method,
6549 ds, method.ds, method.Location, ig, ReturnType,
6550 method.ModFlags, false);
6553 public override ObsoleteAttribute GetObsoleteAttribute ()
6555 return method.GetObsoleteAttribute ();
6558 public override string GetSignatureForError()
6560 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6563 void CheckModifiers (int modflags)
6566 int mflags = method.ModFlags & Modifiers.Accessibility;
6568 if ((mflags & Modifiers.PUBLIC) != 0) {
6569 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6571 else if ((mflags & Modifiers.PROTECTED) != 0) {
6572 if ((mflags & Modifiers.INTERNAL) != 0)
6573 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6575 flags |= Modifiers.PRIVATE;
6577 else if ((mflags & Modifiers.INTERNAL) != 0)
6578 flags |= Modifiers.PRIVATE;
6580 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6581 Report.Error (273, Location,
6582 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6583 GetSignatureForError (), method.GetSignatureForError ());
6587 public override bool MarkForDuplicationCheck ()
6589 caching_flags |= Flags.TestMethodDuplication;
6594 public PropertyMethod Get, Set;
6595 public PropertyBuilder PropertyBuilder;
6596 public MethodBuilder GetBuilder, SetBuilder;
6598 protected EmitContext ec;
6600 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6601 int allowed_mod, bool is_iface, MemberName name,
6602 Parameters parameters, Attributes attrs)
6603 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6608 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6610 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6611 a.Error_InvalidSecurityParent ();
6615 PropertyBuilder.SetCustomAttribute (cb);
6618 public override AttributeTargets AttributeTargets {
6620 return AttributeTargets.Property;
6624 public override bool Define ()
6629 if (!IsTypePermitted ())
6635 protected override bool DoDefine ()
6637 if (!base.DoDefine ())
6641 // Accessors modifiers check
6643 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6644 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6645 GetSignatureForError ());
6649 if ((Get.IsDummy || Set.IsDummy)
6650 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6651 Report.Error (276, Location,
6652 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6653 GetSignatureForError ());
6657 if (MemberType.IsAbstract && MemberType.IsSealed) {
6658 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6662 ec = new EmitContext (this, Parent, Location, null, MemberType, ModFlags);
6666 protected override bool CheckForDuplications ()
6668 ArrayList ar = Parent.PartialContainer.Indexers;
6670 int arLen = ar.Count;
6672 for (int i = 0; i < arLen; i++) {
6673 Indexer m = (Indexer) ar [i];
6674 if (IsDuplicateImplementation (m))
6679 ar = Parent.PartialContainer.Properties;
6681 int arLen = ar.Count;
6683 for (int i = 0; i < arLen; i++) {
6684 Property m = (Property) ar [i];
6685 if (IsDuplicateImplementation (m))
6693 // TODO: rename to Resolve......
6694 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6696 PropertyInfo base_property = Parent.PartialContainer.BaseCache.FindMemberToOverride (
6697 Parent.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6699 if (base_property == null)
6702 base_ret_type = base_property.PropertyType;
6703 MethodInfo get_accessor = base_property.GetGetMethod (true);
6704 MethodInfo set_accessor = base_property.GetSetMethod (true);
6705 MethodAttributes get_accessor_access, set_accessor_access;
6707 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6708 if (Get != null && !Get.IsDummy && get_accessor == null) {
6709 Report.SymbolRelatedToPreviousError (base_property);
6710 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6713 if (Set != null && !Set.IsDummy && set_accessor == null) {
6714 Report.SymbolRelatedToPreviousError (base_property);
6715 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6720 // Check base class accessors access
6723 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6724 get_accessor_access = set_accessor_access = 0;
6725 if ((ModFlags & Modifiers.NEW) == 0) {
6726 if (get_accessor != null) {
6727 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6728 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6730 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6731 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6734 if (set_accessor != null) {
6735 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6736 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6738 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6739 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6744 // Get the less restrictive access
6746 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6749 public override void Emit ()
6752 // The PropertyBuilder can be null for explicit implementations, in that
6753 // case, we do not actually emit the ".property", so there is nowhere to
6754 // put the attribute
6756 if (PropertyBuilder != null && OptAttributes != null)
6757 OptAttributes.Emit ();
6769 /// Tests whether accessors are not in collision with some method (CS0111)
6771 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6773 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6776 public override bool IsUsed
6782 return Get.IsUsed | Set.IsUsed;
6786 protected override void SetMemberName (MemberName new_name)
6788 base.SetMemberName (new_name);
6790 Get.UpdateName (this);
6791 Set.UpdateName (this);
6794 public override string[] ValidAttributeTargets {
6796 return attribute_targets;
6801 // Represents header string for documentation comment.
6803 public override string DocCommentHeader {
6804 get { return "P:"; }
6808 public class Property : PropertyBase {
6809 const int AllowedModifiers =
6812 Modifiers.PROTECTED |
6813 Modifiers.INTERNAL |
6817 Modifiers.OVERRIDE |
6818 Modifiers.ABSTRACT |
6821 Modifiers.METHOD_YIELDS |
6824 const int AllowedInterfaceModifiers =
6827 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6828 MemberName name, Attributes attrs, Accessor get_block,
6830 : base (parent, type, mod,
6831 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6832 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6834 if (get_block == null)
6835 Get = new GetMethod (this);
6837 Get = new GetMethod (this, get_block);
6839 if (set_block == null)
6840 Set = new SetMethod (this);
6842 Set = new SetMethod (this, set_block);
6845 public override bool Define ()
6847 if (!DoDefineBase ())
6850 if (!base.Define ())
6856 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6859 GetBuilder = Get.Define (Parent);
6860 if (GetBuilder == null)
6864 SetBuilder = Set.Define (Parent);
6866 if (SetBuilder == null)
6870 // FIXME - PropertyAttributes.HasDefault ?
6872 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6873 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6876 PropertyBuilder.SetGetMethod (GetBuilder);
6879 PropertyBuilder.SetSetMethod (SetBuilder);
6881 TypeManager.RegisterProperty (PropertyBuilder, this);
6887 /// Gigantic workaround for lameness in SRE follows :
6888 /// This class derives from EventInfo and attempts to basically
6889 /// wrap around the EventBuilder so that FindMembers can quickly
6890 /// return this in it search for members
6892 public class MyEventBuilder : EventInfo {
6895 // We use this to "point" to our Builder which is
6896 // not really a MemberInfo
6898 EventBuilder MyBuilder;
6901 // We "catch" and wrap these methods
6903 MethodInfo raise, remove, add;
6905 EventAttributes attributes;
6906 Type declaring_type, reflected_type, event_type;
6911 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6913 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6915 // And now store the values in our own fields.
6917 declaring_type = type_builder;
6919 reflected_type = type_builder;
6921 attributes = event_attr;
6924 this.event_type = event_type;
6928 // Methods that you have to override. Note that you only need
6929 // to "implement" the variants that take the argument (those are
6930 // the "abstract" methods, the others (GetAddMethod()) are
6933 public override MethodInfo GetAddMethod (bool nonPublic)
6938 public override MethodInfo GetRemoveMethod (bool nonPublic)
6943 public override MethodInfo GetRaiseMethod (bool nonPublic)
6949 // These methods make "MyEventInfo" look like a Builder
6951 public void SetRaiseMethod (MethodBuilder raiseMethod)
6953 raise = raiseMethod;
6954 MyBuilder.SetRaiseMethod (raiseMethod);
6957 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6959 remove = removeMethod;
6960 MyBuilder.SetRemoveOnMethod (removeMethod);
6963 public void SetAddOnMethod (MethodBuilder addMethod)
6966 MyBuilder.SetAddOnMethod (addMethod);
6969 public void SetCustomAttribute (CustomAttributeBuilder cb)
6971 MyBuilder.SetCustomAttribute (cb);
6974 public override object [] GetCustomAttributes (bool inherit)
6976 // FIXME : There's nothing which can be seemingly done here because
6977 // we have no way of getting at the custom attribute objects of the
6982 public override object [] GetCustomAttributes (Type t, bool inherit)
6984 // FIXME : Same here !
6988 public override bool IsDefined (Type t, bool b)
6993 public override EventAttributes Attributes {
6999 public override string Name {
7005 public override Type DeclaringType {
7007 return declaring_type;
7011 public override Type ReflectedType {
7013 return reflected_type;
7017 public Type EventType {
7023 public void SetUsed ()
7025 if (my_event != null) {
7026 my_event.SetAssigned ();
7027 my_event.SetMemberIsUsed ();
7033 /// For case when event is declared like property (with add and remove accessors).
7035 public class EventProperty: Event {
7037 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7039 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
7040 bool is_iface, MemberName name,
7041 Attributes attrs, Accessor add, Accessor remove)
7042 : base (parent, type, mod_flags, is_iface, name, attrs)
7044 Add = new AddDelegateMethod (this, add);
7045 Remove = new RemoveDelegateMethod (this, remove);
7047 // For this event syntax we don't report error CS0067
7048 // because it is hard to do it.
7052 public override bool Define()
7054 if (!base.Define ())
7063 public override string[] ValidAttributeTargets {
7065 return attribute_targets;
7071 /// Event is declared like field.
7073 public class EventField : Event {
7075 static string[] attribute_targets = new string [] { "event", "field", "method" };
7076 static string[] attribute_targets_interface = new string[] { "event", "method" };
7078 public EventField (DeclSpace parent, Expression type, int mod_flags,
7079 bool is_iface, MemberName name,
7081 : base (parent, type, mod_flags, is_iface, name, attrs)
7083 Add = new AddDelegateMethod (this);
7084 Remove = new RemoveDelegateMethod (this);
7087 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7089 if (a.Target == AttributeTargets.Field) {
7090 FieldBuilder.SetCustomAttribute (cb);
7094 if (a.Target == AttributeTargets.Method) {
7095 int errors = Report.Errors;
7096 Add.ApplyAttributeBuilder (a, cb);
7097 if (errors == Report.Errors)
7098 Remove.ApplyAttributeBuilder (a, cb);
7102 base.ApplyAttributeBuilder (a, cb);
7105 public override bool Define()
7107 if (!base.Define ())
7110 if (initializer != null) {
7111 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7112 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7113 GetSignatureForError ());
7121 public override string[] ValidAttributeTargets {
7123 return IsInterface ? attribute_targets_interface : attribute_targets;
7128 public abstract class Event : FieldBase {
7130 protected sealed class AddDelegateMethod: DelegateMethod
7133 public AddDelegateMethod (Event method):
7134 base (method, "add_")
7138 public AddDelegateMethod (Event method, Accessor accessor):
7139 base (method, accessor, "add_")
7143 protected override MethodInfo DelegateMethodInfo {
7145 return TypeManager.delegate_combine_delegate_delegate;
7151 protected sealed class RemoveDelegateMethod: DelegateMethod
7153 public RemoveDelegateMethod (Event method):
7154 base (method, "remove_")
7158 public RemoveDelegateMethod (Event method, Accessor accessor):
7159 base (method, accessor, "remove_")
7163 protected override MethodInfo DelegateMethodInfo {
7165 return TypeManager.delegate_remove_delegate_delegate;
7171 public abstract class DelegateMethod : AbstractPropertyEventMethod
7173 protected readonly Event method;
7174 ImplicitParameter param_attr;
7176 static string[] attribute_targets = new string [] { "method", "param", "return" };
7178 public DelegateMethod (Event method, string prefix)
7179 : base (method, prefix)
7181 this.method = method;
7184 public DelegateMethod (Event method, Accessor accessor, string prefix)
7185 : base (method, accessor, prefix)
7187 this.method = method;
7190 public override Iterator Iterator {
7191 get { return null; }
7194 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7196 if (a.Target == AttributeTargets.Parameter) {
7197 if (param_attr == null)
7198 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7200 param_attr.ApplyAttributeBuilder (a, cb);
7204 base.ApplyAttributeBuilder (a, cb);
7207 public override AttributeTargets AttributeTargets {
7209 return AttributeTargets.Method;
7213 public override bool IsClsComplianceRequired ()
7215 return method.IsClsComplianceRequired ();
7218 public MethodBuilder Define (DeclSpace parent)
7220 method_data = new MethodData (method, method.ModFlags,
7221 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7223 if (!method_data.Define (parent))
7226 MethodBuilder mb = method_data.MethodBuilder;
7227 ParameterInfo.ApplyAttributes (mb);
7232 protected override void EmitMethod (DeclSpace parent)
7234 if (block != null) {
7235 base.EmitMethod (parent);
7239 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7242 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7243 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7245 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7246 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7247 ig.Emit (OpCodes.Ldsfld, field_info);
7248 ig.Emit (OpCodes.Ldarg_0);
7249 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7250 ig.Emit (OpCodes.Castclass, method.MemberType);
7251 ig.Emit (OpCodes.Stsfld, field_info);
7253 ig.Emit (OpCodes.Ldarg_0);
7254 ig.Emit (OpCodes.Ldarg_0);
7255 ig.Emit (OpCodes.Ldfld, field_info);
7256 ig.Emit (OpCodes.Ldarg_1);
7257 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7258 ig.Emit (OpCodes.Castclass, method.MemberType);
7259 ig.Emit (OpCodes.Stfld, field_info);
7261 ig.Emit (OpCodes.Ret);
7264 protected abstract MethodInfo DelegateMethodInfo { get; }
7266 public override Type ReturnType {
7268 return TypeManager.void_type;
7272 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7274 return new EmitContext (
7275 ds, method.Parent, Location, ig, ReturnType,
7276 method.ModFlags, false);
7279 public override ObsoleteAttribute GetObsoleteAttribute ()
7281 return method.GetObsoleteAttribute ();
7284 public override string[] ValidAttributeTargets {
7286 return attribute_targets;
7290 public override Parameters ParameterInfo {
7292 return method.parameters;
7299 const int AllowedModifiers =
7302 Modifiers.PROTECTED |
7303 Modifiers.INTERNAL |
7308 Modifiers.OVERRIDE |
7312 const int AllowedInterfaceModifiers =
7315 public DelegateMethod Add, Remove;
7316 public MyEventBuilder EventBuilder;
7317 public MethodBuilder AddBuilder, RemoveBuilder;
7318 Parameters parameters;
7320 protected Event (DeclSpace parent, Expression type, int mod_flags,
7321 bool is_iface, MemberName name, Attributes attrs)
7322 : base (parent, type, mod_flags,
7323 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7326 IsInterface = is_iface;
7329 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7331 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7332 a.Error_InvalidSecurityParent ();
7336 EventBuilder.SetCustomAttribute (cb);
7339 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7341 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7344 public override AttributeTargets AttributeTargets {
7346 return AttributeTargets.Event;
7350 public override bool Define ()
7352 EventAttributes e_attr;
7353 e_attr = EventAttributes.None;
7355 if (!DoDefineBase ())
7361 if (!TypeManager.IsDelegateType (MemberType)) {
7362 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7366 parameters = new Parameters (
7367 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
7368 new Type[] { MemberType } );
7374 // Now define the accessors
7377 AddBuilder = Add.Define (Parent);
7378 if (AddBuilder == null)
7381 RemoveBuilder = Remove.Define (Parent);
7382 if (RemoveBuilder == null)
7385 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7387 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7388 FieldBuilder = Parent.TypeBuilder.DefineField (
7390 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7391 TypeManager.RegisterPrivateFieldOfEvent (
7392 (EventInfo) EventBuilder, FieldBuilder);
7393 TypeManager.RegisterFieldBase (FieldBuilder, this);
7396 EventBuilder.SetAddOnMethod (AddBuilder);
7397 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7399 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7403 protected override bool CheckBase ()
7405 if (!base.CheckBase ())
7408 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7409 if (!(conflict_symbol is EventInfo)) {
7410 Report.SymbolRelatedToPreviousError (conflict_symbol);
7411 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7419 public override void Emit ()
7421 if (OptAttributes != null) {
7422 OptAttributes.Emit ();
7426 Remove.Emit (Parent);
7431 public override string GetSignatureForError ()
7433 return base.GetSignatureForError ();
7437 // Represents header string for documentation comment.
7439 public override string DocCommentHeader {
7440 get { return "E:"; }
7445 public class Indexer : PropertyBase {
7447 class GetIndexerMethod : GetMethod
7449 public GetIndexerMethod (MethodCore method):
7454 public GetIndexerMethod (MethodCore method, Accessor accessor):
7455 base (method, accessor)
7459 public override Parameters ParameterInfo {
7461 return method.ParameterInfo;
7466 class SetIndexerMethod: SetMethod
7468 public SetIndexerMethod (MethodCore method):
7473 public SetIndexerMethod (MethodCore method, Accessor accessor):
7474 base (method, accessor)
7478 protected override void DefineParameters ()
7480 parameters = Parameters.MergeGenerated (method.Parameters,
7481 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7485 const int AllowedModifiers =
7488 Modifiers.PROTECTED |
7489 Modifiers.INTERNAL |
7493 Modifiers.OVERRIDE |
7498 const int AllowedInterfaceModifiers =
7502 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7503 bool is_iface, Parameters parameters, Attributes attrs,
7504 Accessor get_block, Accessor set_block)
7505 : base (parent, type, mod,
7506 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7507 is_iface, name, parameters, attrs)
7509 if (get_block == null)
7510 Get = new GetIndexerMethod (this);
7512 Get = new GetIndexerMethod (this, get_block);
7514 if (set_block == null)
7515 Set = new SetIndexerMethod (this);
7517 Set = new SetIndexerMethod (this, set_block);
7520 public override bool Define ()
7522 if (!DoDefineBase ())
7525 if (!base.Define ())
7528 if (MemberType == TypeManager.void_type) {
7529 Report.Error (620, Location, "Indexers cannot have void type");
7533 if (OptAttributes != null) {
7534 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7535 if (indexer_attr != null) {
7536 // Remove the attribute from the list because it is not emitted
7537 OptAttributes.Attrs.Remove (indexer_attr);
7539 string name = indexer_attr.GetIndexerAttributeValue ();
7545 if (IsExplicitImpl) {
7546 Report.Error (415, indexer_attr.Location,
7547 "The `IndexerName' attribute is valid only on an " +
7548 "indexer that is not an explicit interface member declaration");
7552 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7553 Report.Error (609, indexer_attr.Location,
7554 "Cannot set the `IndexerName' attribute on an indexer marked override");
7560 if (InterfaceType != null) {
7561 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7562 if (base_IndexerName != Name)
7563 ShortName = base_IndexerName;
7566 if (!Parent.PartialContainer.AddMember (this) ||
7567 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7573 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7575 GetBuilder = Get.Define (Parent);
7576 if (GetBuilder == null)
7580 // Setup iterator if we are one
7582 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7583 Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
7584 if (iterator == null)
7589 SetBuilder = Set.Define (Parent);
7591 if (SetBuilder == null)
7596 // Now name the parameters
7598 Parameter [] p = Parameters.FixedParameters;
7600 // TODO: should be done in parser and it needs to do cycle
7601 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7602 CSharpParser.Error_ParameterModifierNotValid (Location);
7607 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7608 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7611 PropertyBuilder.SetGetMethod (GetBuilder);
7614 PropertyBuilder.SetSetMethod (SetBuilder);
7616 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7621 public override string GetSignatureForError ()
7623 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7624 if (MemberName.Left != null) {
7626 sb.Append (MemberName.Left);
7629 sb.Append (".this");
7630 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7631 return sb.ToString ();
7634 public override bool MarkForDuplicationCheck ()
7636 caching_flags |= Flags.TestMethodDuplication;
7641 public class Operator : MethodOrOperator, IAnonymousHost {
7643 const int AllowedModifiers =
7649 public enum OpType : byte {
7659 // Unary and Binary operators
7682 // Implicit and Explicit
7686 // Just because of enum
7690 public readonly OpType OperatorType;
7692 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7693 int mod_flags, Parameters parameters,
7694 ToplevelBlock block, Attributes attrs, Location loc)
7695 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7696 new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
7698 OperatorType = type;
7702 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7704 if (a.Type == TypeManager.conditional_attribute_type) {
7705 Error_ConditionalAttributeIsNotValid ();
7709 base.ApplyAttributeBuilder (a, cb);
7712 protected override bool CheckForDuplications ()
7714 ArrayList ar = Parent.PartialContainer.Operators;
7716 int arLen = ar.Count;
7718 for (int i = 0; i < arLen; i++) {
7719 Operator o = (Operator) ar [i];
7720 if (IsDuplicateImplementation (o))
7725 ar = Parent.PartialContainer.Methods;
7727 int arLen = ar.Count;
7729 for (int i = 0; i < arLen; i++) {
7730 Method m = (Method) ar [i];
7731 if (IsDuplicateImplementation (m))
7739 public override bool Define ()
7741 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7742 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7743 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7747 // imlicit and explicit operator of same types are not allowed
7748 if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
7749 MarkForDuplicationCheck ();
7751 if (!base.Define ())
7754 if (MemberType == TypeManager.void_type) {
7755 Report.Error (590, Location, "User-defined operators cannot return void");
7759 Type declaring_type = MethodData.DeclaringType;
7760 Type return_type = MemberType;
7761 Type first_arg_type = ParameterTypes [0];
7763 // Rules for conversion operators
7765 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7766 if (first_arg_type == return_type && first_arg_type == declaring_type){
7767 Report.Error (555, Location,
7768 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7772 if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
7773 !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
7774 !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
7777 "User-defined conversion must convert to or from the " +
7782 if (first_arg_type.IsInterface || return_type.IsInterface){
7783 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7784 GetSignatureForError ());
7788 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7789 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7790 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7791 GetSignatureForError ());
7794 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7795 GetSignatureForError ());
7798 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7799 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7800 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");
7803 } else if (Parameters.Count == 1) {
7804 // Checks for Unary operators
7806 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7807 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7808 Report.Error (448, Location,
7809 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7812 if (first_arg_type != declaring_type) {
7814 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7819 if (first_arg_type != declaring_type){
7822 "The parameter of a unary operator must be the " +
7827 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7828 if (return_type != TypeManager.bool_type){
7831 "The return type of operator True or False " +
7838 // Checks for Binary operators
7840 if (first_arg_type != declaring_type &&
7841 ParameterTypes [1] != declaring_type){
7844 "One of the parameters of a binary operator must " +
7845 "be the containing type");
7853 protected override bool DoDefine ()
7855 if (!base.DoDefine ())
7858 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7862 public override void Emit ()
7866 Parameters.ApplyAttributes (MethodBuilder);
7869 // abstract or extern methods have no bodies
7871 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7875 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7876 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7878 ec = CreateEmitContext (Parent, null);
7880 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7881 ec.EmitTopBlock (this, Block);
7884 source.CloseMethod ();
7889 // Operator cannot be override
7890 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7895 public static string GetName (OpType ot)
7898 case OpType.LogicalNot:
7900 case OpType.OnesComplement:
7902 case OpType.Increment:
7904 case OpType.Decrement:
7910 case OpType.Addition:
7912 case OpType.Subtraction:
7914 case OpType.UnaryPlus:
7916 case OpType.UnaryNegation:
7918 case OpType.Multiply:
7920 case OpType.Division:
7922 case OpType.Modulus:
7924 case OpType.BitwiseAnd:
7926 case OpType.BitwiseOr:
7928 case OpType.ExclusiveOr:
7930 case OpType.LeftShift:
7932 case OpType.RightShift:
7934 case OpType.Equality:
7936 case OpType.Inequality:
7938 case OpType.GreaterThan:
7940 case OpType.LessThan:
7942 case OpType.GreaterThanOrEqual:
7944 case OpType.LessThanOrEqual:
7946 case OpType.Implicit:
7948 case OpType.Explicit:
7954 public static OpType GetOperatorType (string name)
7956 if (name.StartsWith ("op_")){
7957 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7958 if (Unary.oper_names [i] == name)
7962 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7963 if (Binary.oper_names [i] == name)
7970 public override string GetSignatureForError ()
7972 StringBuilder sb = new StringBuilder ();
7973 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7974 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7977 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7980 sb.Append (Parameters.GetSignatureForError ());
7981 return sb.ToString ();
7986 // This is used to compare method signatures
7988 struct MethodSignature {
7990 public Type RetType;
7991 public Type [] Parameters;
7994 /// This delegate is used to extract methods which have the
7995 /// same signature as the argument
7997 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7999 public MethodSignature (string name, Type ret_type, Type [] parameters)
8004 if (parameters == null)
8005 Parameters = Type.EmptyTypes;
8007 Parameters = parameters;
8010 public override string ToString ()
8013 if (Parameters.Length != 0){
8014 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8015 for (int i = 0; i < Parameters.Length; i++){
8016 sb.Append (Parameters [i]);
8017 if (i+1 < Parameters.Length)
8020 pars = sb.ToString ();
8023 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8026 public override int GetHashCode ()
8028 return Name.GetHashCode ();
8031 public override bool Equals (Object o)
8033 MethodSignature other = (MethodSignature) o;
8035 if (other.Name != Name)
8038 if (other.RetType != RetType)
8041 if (Parameters == null){
8042 if (other.Parameters == null)
8047 if (other.Parameters == null)
8050 int c = Parameters.Length;
8051 if (other.Parameters.Length != c)
8054 for (int i = 0; i < c; i++)
8055 if (other.Parameters [i] != Parameters [i])
8061 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8063 MethodSignature sig = (MethodSignature) filter_criteria;
8065 if (m.Name != sig.Name)
8069 MethodInfo mi = m as MethodInfo;
8070 PropertyInfo pi = m as PropertyInfo;
8073 ReturnType = mi.ReturnType;
8074 else if (pi != null)
8075 ReturnType = pi.PropertyType;
8080 // we use sig.RetType == null to mean `do not check the
8081 // method return value.
8083 if (sig.RetType != null)
8084 if (ReturnType != sig.RetType)
8089 args = TypeManager.GetParameterData (mi).Types;
8091 args = TypeManager.GetArgumentTypes (pi);
8092 Type [] sigp = sig.Parameters;
8094 if (args.Length != sigp.Length)
8097 for (int i = args.Length; i > 0; ){
8099 if (args [i] != sigp [i])