2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
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)
13 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
15 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
16 // have fixed a remaining problem: not every AddXXXX was adding a
17 // fully qualified name.
19 // Now everyone registers a fully qualified name in the DeclSpace as
20 // being defined instead of the partial name.
22 // Downsides: we are slower than we need to be due to the excess
23 // copies and the names being registered this way.
25 // The reason for this is that we currently depend (on the corlib
26 // bootstrap for instance) that types are fully qualified, because
27 // we dump all the types in the namespace, and we should really have
28 // types inserted into the proper namespace, so we can only store the
29 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
41 using Mono.CompilerServices.SymbolWriter;
43 namespace Mono.CSharp {
53 /// This is the base class for structs and classes.
55 public abstract class TypeContainer : DeclSpace, IMemberContainer {
57 public class MemberCoreArrayList: ArrayList
60 /// Defines the MemberCore objects that are in this array
62 public virtual void DefineContainerMembers ()
64 foreach (MemberCore mc in this) {
69 public virtual void Emit ()
71 foreach (MemberCore mc in this)
76 public class MethodArrayList: MemberCoreArrayList
84 CachedMethods cached_method;
85 TypeContainer container;
87 public MethodArrayList (TypeContainer container)
89 this.container = container;
93 /// Method container contains Equals method
95 public bool HasEquals {
97 cached_method |= CachedMethods.Equals;
101 return (cached_method & CachedMethods.Equals) != 0;
106 /// Method container contains GetHashCode method
108 public bool HasGetHashCode {
110 cached_method |= CachedMethods.GetHashCode;
114 return (cached_method & CachedMethods.GetHashCode) != 0;
118 public override void DefineContainerMembers ()
120 base.DefineContainerMembers ();
122 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
123 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
129 public sealed class IndexerArrayList: MemberCoreArrayList
132 /// The indexer name for this container
134 public string IndexerName = DefaultIndexerName;
136 bool seen_normal_indexers = false;
138 TypeContainer container;
140 public IndexerArrayList (TypeContainer container)
142 this.container = container;
146 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
147 /// class is consistent. Either it is `Item' or it is the name defined by all the
148 /// indexers with the `IndexerName' attribute.
150 /// Turns out that the IndexerNameAttribute is applied to each indexer,
151 /// but it is never emitted, instead a DefaultMember attribute is attached
154 public override void DefineContainerMembers()
156 base.DefineContainerMembers ();
158 string class_indexer_name = null;
161 // If there's both an explicit and an implicit interface implementation, the
162 // explicit one actually implements the interface while the other one is just
163 // a normal indexer. See bug #37714.
166 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
167 foreach (Indexer i in this) {
168 if (i.InterfaceType != null) {
169 if (seen_normal_indexers)
170 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
174 seen_normal_indexers = true;
176 if (class_indexer_name == null) {
177 class_indexer_name = i.IndexerName;
181 if (i.IndexerName != class_indexer_name)
182 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");
185 if (class_indexer_name != null)
186 IndexerName = class_indexer_name;
189 public override void Emit ()
193 if (!seen_normal_indexers)
196 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
197 container.TypeBuilder.SetCustomAttribute (cb);
201 public class OperatorArrayList: MemberCoreArrayList
203 TypeContainer container;
205 public OperatorArrayList (TypeContainer container)
207 this.container = container;
211 // Operator pair checking
216 public Type ret_type;
217 public Type type1, type2;
219 public Operator.OpType ot;
221 public OperatorEntry (int f, Operator o)
225 ret_type = o.OperatorMethod.GetReturnType ();
226 Type [] pt = o.OperatorMethod.ParameterTypes;
233 public override int GetHashCode ()
235 return ret_type.GetHashCode ();
238 public override bool Equals (object o)
240 OperatorEntry other = (OperatorEntry) o;
242 if (other.ret_type != ret_type)
244 if (other.type1 != type1)
246 if (other.type2 != type2)
253 // Checks that some operators come in pairs:
259 // They are matched based on the return type and the argument types
261 void CheckPairedOperators ()
263 Hashtable pairs = new Hashtable (null, null);
264 Operator true_op = null;
265 Operator false_op = null;
266 bool has_equality_or_inequality = false;
268 // Register all the operators we care about.
269 foreach (Operator op in this){
272 switch (op.OperatorType){
273 case Operator.OpType.Equality:
275 has_equality_or_inequality = true;
277 case Operator.OpType.Inequality:
279 has_equality_or_inequality = true;
282 case Operator.OpType.True:
285 case Operator.OpType.False:
289 case Operator.OpType.GreaterThan:
291 case Operator.OpType.LessThan:
294 case Operator.OpType.GreaterThanOrEqual:
296 case Operator.OpType.LessThanOrEqual:
302 OperatorEntry oe = new OperatorEntry (reg, op);
304 object o = pairs [oe];
308 oe = (OperatorEntry) o;
313 if (true_op != null){
314 if (false_op == null)
315 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
316 } else if (false_op != null)
317 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
320 // Look for the mistakes.
322 foreach (DictionaryEntry de in pairs){
323 OperatorEntry oe = (OperatorEntry) de.Key;
330 case Operator.OpType.Equality:
333 case Operator.OpType.Inequality:
336 case Operator.OpType.GreaterThan:
339 case Operator.OpType.LessThan:
342 case Operator.OpType.GreaterThanOrEqual:
345 case Operator.OpType.LessThanOrEqual:
349 Report.Error (216, oe.op.Location,
350 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
353 if (has_equality_or_inequality && container.Methods != null && (RootContext.WarningLevel > 2)) {
354 if (!container.Methods.HasEquals)
355 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
357 if (!container.Methods.HasGetHashCode)
358 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
362 public override void DefineContainerMembers ()
364 base.DefineContainerMembers ();
365 CheckPairedOperators ();
370 // Whether this is a struct, class or interface
371 public readonly Kind Kind;
373 // Holds a list of classes and structures
376 // Holds the list of properties
377 MemberCoreArrayList properties;
379 // Holds the list of enumerations
380 MemberCoreArrayList enums;
382 // Holds the list of delegates
383 MemberCoreArrayList delegates;
385 // Holds the list of constructors
386 MemberCoreArrayList instance_constructors;
388 // Holds the list of fields
389 MemberCoreArrayList fields;
391 // Holds a list of fields that have initializers
392 ArrayList initialized_fields;
394 // Holds a list of static fields that have initializers
395 ArrayList initialized_static_fields;
397 // Holds the list of constants
398 MemberCoreArrayList constants;
401 MemberCoreArrayList interfaces;
403 // Holds the methods.
404 MethodArrayList methods;
407 MemberCoreArrayList events;
409 // Holds the indexers
410 IndexerArrayList indexers;
412 // Holds the operators
413 MemberCoreArrayList operators;
415 // Holds the iterators
418 // Holds the parts of a partial class;
421 // The emit context for toplevel objects.
425 // Pointers to the default constructor and the default static constructor
427 Constructor default_constructor;
428 Constructor default_static_constructor;
431 // Whether we have seen a static constructor for this class or not
433 public bool UserDefinedStaticConstructor = false;
436 // Whether we have at least one non-static field
438 bool have_nonstatic_fields = false;
441 // This one is computed after we can distinguish interfaces
442 // from classes from the arraylist `type_bases'
444 string base_class_name;
445 TypeExpr parent_type;
447 ArrayList type_bases;
449 bool members_defined;
450 bool members_defined_ok;
452 // The interfaces we implement.
455 // The parent member container and our member cache
456 IMemberContainer parent_container;
457 MemberCache member_cache;
459 public const string DefaultIndexerName = "Item";
463 public TypeContainer (NamespaceEntry ns, TypeContainer parent,
464 MemberName name, Attributes attrs, Kind kind, Location l)
465 : base (ns, parent, name, attrs, l)
469 types = new ArrayList ();
471 base_class_name = null;
475 // Used to report back to the user the result of a declaration
476 // in the current declaration space
478 public void CheckDef (AdditionResult result, string name, Location loc)
480 if (result == AdditionResult.Success)
484 case AdditionResult.NameExists:
485 Report.Error (102, loc, "The container `{0}' already " +
486 "contains a definition for `{1}'",
491 // This is handled only for static Constructors, because
492 // in reality we handle these by the semantic analysis later
494 case AdditionResult.MethodExists:
495 Report.Error (111, loc, "Class `{0}' already defines a " +
496 "member called '{1}' with the same parameter " +
497 "types (more than one default constructor)",
501 case AdditionResult.EnclosingClash:
502 Report.Error (542, loc, "Member names cannot be the same " +
503 "as their enclosing type");
506 case AdditionResult.NotAConstructor:
507 Report.Error (1520, loc, "Class, struct, or interface method " +
508 "must have a return type");
511 case AdditionResult.Error:
512 // Error has already been reported.
517 public AdditionResult AddConstant (Const constant)
520 string basename = constant.Name;
521 string fullname = Name + "." + basename;
523 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
526 if (constants == null)
527 constants = new MemberCoreArrayList ();
529 constants.Add (constant);
530 DefineName (fullname, constant);
532 return AdditionResult.Success;
535 public AdditionResult AddEnum (Mono.CSharp.Enum e)
539 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
543 enums = new MemberCoreArrayList ();
546 DefineName (e.Name, e);
548 return AdditionResult.Success;
551 public AdditionResult AddClass (TypeContainer c)
554 string name = c.Basename;
556 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
559 DefineName (c.Name, c);
562 return AdditionResult.Success;
565 public AdditionResult AddStruct (TypeContainer s)
568 string name = s.Basename;
570 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
573 DefineName (s.Name, s);
576 return AdditionResult.Success;
579 public AdditionResult AddDelegate (Delegate d)
582 string name = d.Basename;
584 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
587 if (delegates == null)
588 delegates = new MemberCoreArrayList ();
590 DefineName (d.Name, d);
593 return AdditionResult.Success;
596 public AdditionResult AddMethod (Method method)
598 string basename = method.Name;
599 string fullname = Name + "." + basename;
601 Object value = defined_names [fullname];
603 if (value != null && (!(value is Method)))
604 return AdditionResult.NameExists;
606 if (basename == Basename)
607 return AdditionResult.EnclosingClash;
610 methods = new MethodArrayList (this);
612 if (method.Name.IndexOf ('.') != -1)
613 methods.Insert (0, method);
615 methods.Add (method);
618 DefineName (fullname, method);
620 return AdditionResult.Success;
623 public AdditionResult AddConstructor (Constructor c)
625 if (c.Name != Basename)
626 return AdditionResult.NotAConstructor;
628 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
631 UserDefinedStaticConstructor = true;
632 if (default_static_constructor != null)
633 return AdditionResult.MethodExists;
635 default_static_constructor = c;
638 if (default_constructor != null)
639 return AdditionResult.MethodExists;
640 default_constructor = c;
643 if (instance_constructors == null)
644 instance_constructors = new MemberCoreArrayList ();
646 instance_constructors.Add (c);
649 return AdditionResult.Success;
652 public AdditionResult AddInterface (TypeContainer iface)
655 string name = iface.Basename;
657 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
660 if (interfaces == null)
661 interfaces = new MemberCoreArrayList ();
662 interfaces.Add (iface);
663 DefineName (iface.Name, iface);
665 return AdditionResult.Success;
668 public AdditionResult AddField (Field field)
671 string basename = field.Name;
672 string fullname = Name + "." + basename;
674 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
678 fields = new MemberCoreArrayList ();
682 if (field.HasInitializer){
683 if ((field.ModFlags & Modifiers.STATIC) != 0){
684 if (initialized_static_fields == null)
685 initialized_static_fields = new ArrayList ();
687 initialized_static_fields.Add (field);
690 if (initialized_fields == null)
691 initialized_fields = new ArrayList ();
693 initialized_fields.Add (field);
697 if ((field.ModFlags & Modifiers.STATIC) == 0)
698 have_nonstatic_fields = true;
700 DefineName (fullname, field);
701 return AdditionResult.Success;
704 public AdditionResult AddProperty (Property prop)
708 if ((res = AddProperty (prop, prop.Name)) != AdditionResult.Success)
711 if (prop.Get != null) {
712 if ((res = AddProperty (prop, "get_" + prop.Name)) != AdditionResult.Success)
716 if (prop.Set != null) {
717 if ((res = AddProperty (prop, "set_" + prop.Name)) != AdditionResult.Success)
721 if (properties == null)
722 properties = new MemberCoreArrayList ();
724 if (prop.Name.IndexOf ('.') != -1)
725 properties.Insert (0, prop);
727 properties.Add (prop);
729 return AdditionResult.Success;
732 AdditionResult AddProperty (Property prop, string basename)
735 string fullname = Name + "." + basename;
737 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
740 DefineName (fullname, prop);
742 return AdditionResult.Success;
745 public AdditionResult AddEvent (Event e)
748 string basename = e.Name;
749 string fullname = Name + "." + basename;
751 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
755 events = new MemberCoreArrayList ();
758 DefineName (fullname, e);
760 return AdditionResult.Success;
763 public void AddIndexer (Indexer i)
765 if (indexers == null)
766 indexers = new IndexerArrayList (this);
768 if (i.MemberName.Left != null)
769 indexers.Insert (0, i);
774 public AdditionResult AddOperator (Operator op)
776 if (operators == null)
777 operators = new OperatorArrayList (this);
781 string basename = op.Name;
782 string fullname = Name + "." + basename;
783 if (!defined_names.Contains (fullname))
785 DefineName (fullname, op);
787 return AdditionResult.Success;
790 public void AddIterator (Iterator i)
792 if (iterators == null)
793 iterators = new ArrayList ();
798 public void AddType (TypeContainer tc)
803 public void AddPart (ClassPart part)
806 parts = new ArrayList ();
811 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
813 if (a.Type == TypeManager.default_member_type) {
814 if (Indexers != null) {
815 Report.Error (646, a.Location,
816 "Cannot specify the DefaultMember attribute on" +
817 " a type containing an indexer");
822 base.ApplyAttributeBuilder (a, cb);
825 public override AttributeTargets AttributeTargets {
827 throw new NotSupportedException ();
831 public ArrayList Types {
837 public MethodArrayList Methods {
843 public ArrayList Constants {
849 public ArrayList Interfaces {
855 public ArrayList Iterators {
863 return base_class_name;
867 public ArrayList Bases {
877 public ArrayList Fields {
883 public ArrayList InstanceConstructors {
885 return instance_constructors;
889 public ArrayList Properties {
895 public ArrayList Events {
901 public ArrayList Enums {
907 public ArrayList Indexers {
913 public ArrayList Operators {
919 public ArrayList Delegates {
925 public ArrayList Parts {
931 public virtual TypeAttributes TypeAttr {
933 return Modifiers.TypeAttr (ModFlags, this);
937 public string IndexerName {
939 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
944 // Emits the instance field initializers
946 public bool EmitFieldInitializers (EmitContext ec)
949 Expression instance_expr;
952 fields = initialized_static_fields;
953 instance_expr = null;
955 fields = initialized_fields;
956 instance_expr = new This (Location.Null).Resolve (ec);
962 foreach (Field f in fields){
963 Expression e = f.GetInitializerExpression (ec);
967 Location l = f.Location;
968 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
969 fe.InstanceExpression = instance_expr;
970 fe.IsFieldInitializer = true;
972 ExpressionStatement a = new Assign (fe, e, l);
974 a = a.ResolveStatement (ec);
978 a.EmitStatement (ec);
985 // Defines the default constructors
987 void DefineDefaultConstructor (bool is_static)
991 // The default constructor is public
992 // If the class is abstract, the default constructor is protected
993 // The default static constructor is private
995 int mods = Modifiers.PUBLIC;
997 mods = Modifiers.STATIC | Modifiers.PRIVATE;
998 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
999 mods = Modifiers.PROTECTED;
1001 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
1002 new ConstructorBaseInitializer (
1003 null, Parameters.EmptyReadOnlyParameters,
1009 c.Block = new ToplevelBlock (null, Location);
1013 public void ReportStructInitializedInstanceError ()
1015 string n = TypeBuilder.FullName;
1017 foreach (Field f in initialized_fields){
1020 "`" + n + "." + f.Name + "': can not have " +
1021 "instance field initializers in structs");
1026 /// The pending methods that need to be implemented
1027 // (interfaces or abstract methods)
1029 public PendingImplementation Pending;
1031 public abstract void Register ();
1033 public abstract PendingImplementation GetPendingImplementations ();
1035 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
1037 ArrayList ifaces = new ArrayList ();
1040 Location parent_loc = Location.Null;
1042 foreach (ClassPart part in parts) {
1043 TypeExpr new_parent;
1044 TypeExpr[] new_ifaces;
1046 new_ifaces = part.GetClassBases (out new_parent, out error);
1050 if ((parent != null) && (new_parent != null) &&
1051 !parent.Equals (new_parent)) {
1052 Report.Error (263, part.Location,
1053 "Partial declarations of `{0}' must " +
1054 "not specify different base classes",
1057 if (!Location.IsNull (parent_loc))
1058 Report.LocationOfPreviousError (parent_loc);
1064 if ((parent == null) && (new_parent != null)) {
1065 parent = new_parent;
1066 parent_loc = part.Location;
1069 if (new_ifaces == null)
1072 foreach (TypeExpr iface in new_ifaces) {
1074 foreach (TypeExpr old_iface in ifaces) {
1075 if (old_iface.Equals (iface)) {
1088 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1089 ifaces.CopyTo (retval, 0);
1093 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
1097 int count = Bases.Count;
1100 if (Kind == Kind.Class){
1101 TypeExpr name = ResolveTypeExpr (
1102 (Expression) Bases [0], false, Location);
1119 TypeExpr [] ifaces = new TypeExpr [count-start];
1121 for (i = start, j = 0; i < count; i++, j++){
1122 Expression name = (Expression) Bases [i];
1123 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
1124 if (resolved == null) {
1129 ifaces [j] = resolved;
1137 /// This function computes the Base class and also the
1138 /// list of interfaces that the class or struct @c implements.
1140 /// The return value is an array (might be null) of
1141 /// interfaces implemented (as Types).
1143 /// The @parent argument is set to the parent object or null
1144 /// if this is `System.Object'.
1146 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1148 ArrayList bases = Bases;
1156 ifaces = GetPartialBases (out parent, out error);
1157 else if (Bases == null){
1161 ifaces = GetNormalBases (out parent, out error);
1166 if ((parent != null) && (Kind == Kind.Class)){
1167 if (parent is TypeParameterExpr){
1169 689, parent.Location,
1170 "Type parameter `{0}' can not be used as a " +
1171 "base class or interface", parent.Name);
1176 if (IsGeneric && parent.IsAttribute){
1178 698, parent.Location,
1179 "A generic type cannot derive from `{0}' " +
1180 "because it is an attribute class",
1186 if (parent.IsSealed){
1189 if (parent.IsValueType)
1190 detail = " (a class can not inherit from a struct/enum)";
1192 Report.Error (509, "class `"+ Name +
1193 "': Cannot inherit from sealed class `"+
1194 parent.Name + "'" + detail);
1199 if (!parent.CanInheritFrom ()){
1200 Report.Error (644, Location,
1201 "`{0}' cannot inherit from special class `{1}'",
1202 Name, parent_type.Name);
1207 if (!parent.AsAccessible (this, ModFlags))
1208 Report.Error (60, Location,
1209 "Inconsistent accessibility: base class `" +
1210 parent.Name + "' is less accessible than class `" +
1215 base_class_name = parent.Name;
1220 int count = ifaces != null ? ifaces.Length : 0;
1222 for (i = 0; i < count; i++) {
1223 TypeExpr iface = (TypeExpr) ifaces [i];
1225 if ((Kind != Kind.Class) && !iface.IsInterface){
1226 string what = Kind == Kind.Struct ?
1227 "Struct" : "Interface";
1229 Report.Error (527, Location,
1230 "In {0} `{1}', type `{2}' is not "+
1231 "an interface", what, Name, iface.Name);
1236 if (iface.IsClass) {
1237 if (parent != null){
1238 Report.Error (527, Location,
1239 "In Class `{0}', `{1}' is not " +
1240 "an interface", Name, iface.Name);
1246 for (int x = 0; x < i; x++) {
1247 if (iface.Equals (ifaces [x])) {
1248 Report.Error (528, Location,
1249 "`{0}' is already listed in " +
1250 "interface list", iface.Name);
1256 if ((Kind == Kind.Interface) &&
1257 !iface.AsAccessible (Parent, ModFlags))
1258 Report.Error (61, Location,
1259 "Inconsistent accessibility: base " +
1260 "interface `{0}' is less accessible " +
1261 "than interface `{1}'", iface.Name,
1268 bool CheckGenericInterfaces (Type[] ifaces)
1270 ArrayList already_checked = new ArrayList ();
1272 for (int i = 0; i < ifaces.Length; i++) {
1273 Type iface = ifaces [i];
1274 foreach (Type t in already_checked) {
1278 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t))
1283 "`{0}' cannot implement both `{1}' and `{2}' " +
1284 "because they may unify for some type " +
1285 "parameter substitutions",
1286 TypeManager.GetFullName (TypeBuilder),
1291 already_checked.Add (iface);
1300 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1302 public override TypeBuilder DefineType ()
1306 if (TypeBuilder != null)
1313 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1320 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1322 TypeAttributes type_attributes = TypeAttr;
1325 if (TypeManager.NamespaceClash (Name, Location)) {
1330 ModuleBuilder builder = CodeGen.Module.Builder;
1331 TypeBuilder = builder.DefineType (
1332 Name, type_attributes, null, null);
1334 TypeBuilder builder = Parent.DefineType ();
1335 if (builder == null) {
1340 TypeBuilder = builder.DefineNestedType (
1341 MemberName.Basename, type_attributes, null, null);
1344 TypeManager.AddUserType (Name, TypeBuilder, this);
1347 foreach (TypeParameter type_param in TypeParameters) {
1348 if (!type_param.Resolve (this)) {
1354 CurrentType = new ConstructedType (
1355 Name, TypeParameters, Location);
1357 string[] param_names = new string [TypeParameters.Length];
1358 for (int i = 0; i < TypeParameters.Length; i++)
1359 param_names [i] = TypeParameters [i].Name;
1361 GenericTypeParameterBuilder[] gen_params;
1363 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1365 for (int i = 0; i < gen_params.Length; i++)
1366 TypeParameters [i].Define (gen_params [i]);
1370 foreach (TypeParameter type_param in TypeParameters)
1371 if (!type_param.DefineType (ec)) {
1377 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1378 throw new Exception ();
1380 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1384 if (parent_type == null) {
1385 if (Kind == Kind.Class){
1386 if (RootContext.StdLib)
1387 parent_type = TypeManager.system_object_expr;
1388 else if (Name != "System.Object")
1389 parent_type = TypeManager.system_object_expr;
1390 } else if (Kind == Kind.Struct){
1392 // If we are compiling our runtime,
1393 // and we are defining ValueType, then our
1394 // parent is `System.Object'.
1396 if (!RootContext.StdLib && Name == "System.ValueType")
1397 parent_type = TypeManager.system_object_expr;
1398 else if (Kind == Kind.Struct)
1399 parent_type = TypeManager.system_valuetype_expr;
1404 ConstructedType constructed = parent_type as ConstructedType;
1405 if ((constructed == null) && (parent_type != null))
1406 ptype = parent_type.ResolveType (ec);
1410 if (constructed != null) {
1411 ptype = constructed.ResolveType (ec);
1412 if (ptype == null) {
1419 TypeBuilder.SetParent (ptype);
1422 // Structs with no fields need to have at least one byte.
1423 // The right thing would be to set the PackingSize in a DefineType
1424 // but there are no functions that allow interfaces *and* the size to
1428 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1429 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1430 FieldAttributes.Private);
1433 // add interfaces that were not added at type creation
1434 if (iface_exprs != null) {
1435 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1436 if (ifaces == null) {
1441 foreach (Type itype in ifaces)
1442 TypeBuilder.AddInterfaceImplementation (itype);
1444 if (!CheckGenericInterfaces (ifaces)) {
1449 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1453 foreach (TypeParameter type_param in TypeParameters)
1454 if (!type_param.CheckDependencies (ec)) {
1461 // Finish the setup for the EmitContext
1463 ec.ContainerType = TypeBuilder;
1465 if ((parent_type != null) && parent_type.IsAttribute) {
1466 RootContext.RegisterAttribute (this);
1467 } else if (!(this is Iterator))
1468 RootContext.RegisterOrder (this);
1470 if (!DefineNestedTypes ()) {
1479 protected virtual bool DefineNestedTypes ()
1481 if (Interfaces != null) {
1482 foreach (TypeContainer iface in Interfaces)
1483 if (iface.DefineType () == null)
1487 if (Types != null) {
1488 foreach (TypeContainer tc in Types)
1489 if (tc.DefineType () == null)
1493 if (Delegates != null) {
1494 foreach (Delegate d in Delegates)
1495 if (d.DefineType () == null)
1499 if (Enums != null) {
1500 foreach (Enum en in Enums)
1501 if (en.DefineType () == null)
1505 if (Parts != null) {
1506 foreach (ClassPart part in Parts) {
1507 part.TypeBuilder = TypeBuilder;
1508 part.parent_type = parent_type;
1515 static void Error_KeywordNotAllowed (Location loc)
1517 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1521 /// Populates our TypeBuilder with fields and methods
1523 public override bool DefineMembers (TypeContainer container)
1525 if (members_defined)
1526 return members_defined_ok;
1528 members_defined_ok = DoDefineMembers ();
1529 members_defined = true;
1531 return members_defined_ok;
1534 bool DoDefineMembers ()
1537 // We need to be able to use the member cache while we are checking/defining
1539 if (TypeBuilder.BaseType != null)
1540 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1543 //if (TypeBuilder.IsInterface) {
1544 // parent_container = TypeManager.LookupInterfaceContainer (base_inteface_types);
1548 if ((ModFlags & Modifiers.NEW) != 0)
1549 Error_KeywordNotAllowed (Location);
1551 // HACK: missing implemenation
1552 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1553 // instead of flat as we have now.
1554 // Now we are not able to check inner attribute class because its parent had not been defined.
1556 // TODO: remove this if
1557 if (Parent.MemberCache != null) {
1558 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1559 if (conflict_symbol == null) {
1560 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1561 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1563 if ((ModFlags & Modifiers.NEW) == 0) {
1564 Report.SymbolRelatedToPreviousError (conflict_symbol);
1565 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1571 if (constants != null)
1572 constants.DefineContainerMembers ();
1575 fields.DefineContainerMembers ();
1577 if ((Kind == Kind.Class) && !(this is ClassPart)){
1578 if (instance_constructors == null){
1579 if (default_constructor == null)
1580 DefineDefaultConstructor (false);
1583 if (initialized_static_fields != null &&
1584 default_static_constructor == null)
1585 DefineDefaultConstructor (true);
1588 if (Kind == Kind.Struct){
1590 // Structs can not have initialized instance
1593 if (initialized_static_fields != null &&
1594 default_static_constructor == null)
1595 DefineDefaultConstructor (true);
1597 if (initialized_fields != null)
1598 ReportStructInitializedInstanceError ();
1601 Pending = GetPendingImplementations ();
1603 if (parts != null) {
1604 foreach (ClassPart part in parts) {
1605 if (!part.DefineMembers (this))
1611 // Constructors are not in the defined_names array
1613 if (instance_constructors != null)
1614 instance_constructors.DefineContainerMembers ();
1616 if (default_static_constructor != null)
1617 default_static_constructor.Define ();
1619 if (methods != null)
1620 methods.DefineContainerMembers ();
1622 if (properties != null)
1623 properties.DefineContainerMembers ();
1626 events.DefineContainerMembers ();
1628 if (indexers != null)
1629 indexers.DefineContainerMembers ();
1631 if (operators != null)
1632 operators.DefineContainerMembers ();
1635 enums.DefineContainerMembers ();
1637 if (delegates != null)
1638 delegates.DefineContainerMembers ();
1640 if (CurrentType != null) {
1641 GenericType = CurrentType.ResolveType (ec);
1643 ec.ContainerType = GenericType;
1648 if (!(this is ClassPart))
1649 member_cache = new MemberCache (this);
1652 if (parts != null) {
1653 foreach (ClassPart part in parts)
1654 part.member_cache = member_cache;
1657 if (iterators != null) {
1658 foreach (Iterator iterator in iterators) {
1659 if (iterator.DefineType () == null)
1663 foreach (Iterator iterator in iterators) {
1664 if (!iterator.DefineMembers (this))
1672 public override bool Define ()
1674 if (parts != null) {
1675 foreach (ClassPart part in parts) {
1676 if (!part.Define ())
1684 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1686 return ParentContainer.MemberCache.FindMemberWithSameName (name, ignore_methods, null);
1690 /// This function is based by a delegate to the FindMembers routine
1692 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1698 /// This filter is used by FindMembers, and we just keep
1699 /// a global for the filter to `AlwaysAccept'
1701 static MemberFilter accepting_filter;
1704 static TypeContainer ()
1706 accepting_filter = new MemberFilter (AlwaysAccept);
1709 public MethodInfo[] GetMethods ()
1711 ArrayList members = new ArrayList ();
1713 DefineMembers (null);
1715 if (methods != null) {
1716 int len = methods.Count;
1717 for (int i = 0; i < len; i++) {
1718 Method m = (Method) methods [i];
1720 members.Add (m.MethodBuilder);
1724 if (operators != null) {
1725 int len = operators.Count;
1726 for (int i = 0; i < len; i++) {
1727 Operator o = (Operator) operators [i];
1729 members.Add (o.OperatorMethodBuilder);
1733 if (properties != null) {
1734 int len = properties.Count;
1735 for (int i = 0; i < len; i++) {
1736 Property p = (Property) properties [i];
1738 if (p.GetBuilder != null)
1739 members.Add (p.GetBuilder);
1740 if (p.SetBuilder != null)
1741 members.Add (p.SetBuilder);
1745 if (indexers != null) {
1746 int len = indexers.Count;
1747 for (int i = 0; i < len; i++) {
1748 Indexer ix = (Indexer) indexers [i];
1750 if (ix.GetBuilder != null)
1751 members.Add (ix.GetBuilder);
1752 if (ix.SetBuilder != null)
1753 members.Add (ix.SetBuilder);
1757 if (events != null) {
1758 int len = events.Count;
1759 for (int i = 0; i < len; i++) {
1760 Event e = (Event) events [i];
1762 if (e.AddBuilder != null)
1763 members.Add (e.AddBuilder);
1764 if (e.RemoveBuilder != null)
1765 members.Add (e.RemoveBuilder);
1769 MethodInfo[] retMethods = new MethodInfo [members.Count];
1770 members.CopyTo (retMethods, 0);
1775 /// This method returns the members of this type just like Type.FindMembers would
1776 /// Only, we need to use this for types which are _being_ defined because MS'
1777 /// implementation can't take care of that.
1780 // FIXME: return an empty static array instead of null, that cleans up
1781 // some code and is consistent with some coding conventions I just found
1785 // Notice that in various cases we check if our field is non-null,
1786 // something that would normally mean that there was a bug elsewhere.
1788 // The problem happens while we are defining p-invoke methods, as those
1789 // will trigger a FindMembers, but this happens before things are defined
1791 // Since the whole process is a no-op, it is fine to check for null here.
1793 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1794 MemberFilter filter, object criteria)
1796 ArrayList members = null;
1799 if ((bf & BindingFlags.Public) != 0)
1800 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1802 if ((bf & BindingFlags.NonPublic) != 0)
1803 modflags |= Modifiers.PRIVATE;
1805 int static_mask = 0, static_flags = 0;
1806 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1807 case BindingFlags.Static:
1808 static_mask = static_flags = Modifiers.STATIC;
1811 case BindingFlags.Instance:
1812 static_mask = Modifiers.STATIC;
1817 static_mask = static_flags = 0;
1821 Timer.StartTimer (TimerType.TcFindMembers);
1824 filter = accepting_filter;
1826 if ((mt & MemberTypes.Field) != 0) {
1827 if (fields != null) {
1828 int len = fields.Count;
1829 for (int i = 0; i < len; i++) {
1830 Field f = (Field) fields [i];
1832 if ((f.ModFlags & modflags) == 0)
1834 if ((f.ModFlags & static_mask) != static_flags)
1837 FieldBuilder fb = f.FieldBuilder;
1838 if (fb != null && filter (fb, criteria) == true) {
1839 if (members == null)
1840 members = new ArrayList ();
1847 if (constants != null) {
1848 int len = constants.Count;
1849 for (int i = 0; i < len; i++) {
1850 Const con = (Const) constants [i];
1852 if ((con.ModFlags & modflags) == 0)
1854 if ((con.ModFlags & static_mask) != static_flags)
1857 FieldBuilder fb = con.FieldBuilder;
1858 if (fb != null && filter (fb, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1868 if ((mt & MemberTypes.Method) != 0) {
1869 if (methods != null) {
1870 int len = methods.Count;
1871 for (int i = 0; i < len; i++) {
1872 Method m = (Method) methods [i];
1874 if ((m.ModFlags & modflags) == 0)
1876 if ((m.ModFlags & static_mask) != static_flags)
1879 MethodBuilder mb = m.MethodBuilder;
1881 if (mb != null && filter (mb, criteria) == true) {
1882 if (members == null)
1883 members = new ArrayList ();
1890 if (operators != null) {
1891 int len = operators.Count;
1892 for (int i = 0; i < len; i++) {
1893 Operator o = (Operator) operators [i];
1895 if ((o.ModFlags & modflags) == 0)
1897 if ((o.ModFlags & static_mask) != static_flags)
1900 MethodBuilder ob = o.OperatorMethodBuilder;
1901 if (ob != null && filter (ob, criteria) == true) {
1902 if (members == null)
1903 members = new ArrayList ();
1910 if (properties != null) {
1911 int len = properties.Count;
1912 for (int i = 0; i < len; i++) {
1913 Property p = (Property) properties [i];
1915 if ((p.ModFlags & modflags) == 0)
1917 if ((p.ModFlags & static_mask) != static_flags)
1923 if (b != null && filter (b, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1931 if (b != null && filter (b, criteria) == true) {
1932 if (members == null)
1933 members = new ArrayList ();
1940 if (indexers != null) {
1941 int len = indexers.Count;
1942 for (int i = 0; i < len; i++) {
1943 Indexer ix = (Indexer) indexers [i];
1945 if ((ix.ModFlags & modflags) == 0)
1947 if ((ix.ModFlags & static_mask) != static_flags)
1953 if (b != null && filter (b, criteria) == true) {
1954 if (members == null)
1955 members = new ArrayList ();
1961 if (b != null && filter (b, criteria) == true) {
1962 if (members == null)
1963 members = new ArrayList ();
1971 if ((mt & MemberTypes.Event) != 0) {
1972 if (events != null) {
1973 int len = events.Count;
1974 for (int i = 0; i < len; i++) {
1975 Event e = (Event) events [i];
1977 if ((e.ModFlags & modflags) == 0)
1979 if ((e.ModFlags & static_mask) != static_flags)
1982 MemberInfo eb = e.EventBuilder;
1983 if (eb != null && filter (eb, criteria) == true) {
1984 if (members == null)
1985 members = new ArrayList ();
1987 members.Add (e.EventBuilder);
1993 if ((mt & MemberTypes.Property) != 0){
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)
2004 MemberInfo pb = p.PropertyBuilder;
2005 if (pb != null && filter (pb, criteria) == true) {
2006 if (members == null)
2007 members = new ArrayList ();
2009 members.Add (p.PropertyBuilder);
2014 if (indexers != null) {
2015 int len = indexers.Count;
2016 for (int i = 0; i < len; i++) {
2017 Indexer ix = (Indexer) indexers [i];
2019 if ((ix.ModFlags & modflags) == 0)
2021 if ((ix.ModFlags & static_mask) != static_flags)
2024 MemberInfo ib = ix.PropertyBuilder;
2025 if (ib != null && filter (ib, criteria) == true) {
2026 if (members == null)
2027 members = new ArrayList ();
2029 members.Add (ix.PropertyBuilder);
2035 if ((mt & MemberTypes.NestedType) != 0) {
2036 if (types != null) {
2037 int len = types.Count;
2038 for (int i = 0; i < len; i++) {
2039 TypeContainer t = (TypeContainer) types [i];
2041 if ((t.ModFlags & modflags) == 0)
2044 TypeBuilder tb = t.TypeBuilder;
2045 if (tb != null && (filter (tb, criteria) == true)) {
2046 if (members == null)
2047 members = new ArrayList ();
2054 if (enums != null) {
2055 int len = enums.Count;
2056 for (int i = 0; i < len; i++) {
2057 Enum en = (Enum) enums [i];
2059 if ((en.ModFlags & modflags) == 0)
2062 TypeBuilder tb = en.TypeBuilder;
2063 if (tb != null && (filter (tb, criteria) == true)) {
2064 if (members == null)
2065 members = new ArrayList ();
2072 if (delegates != null) {
2073 int len = delegates.Count;
2074 for (int i = 0; i < len; i++) {
2075 Delegate d = (Delegate) delegates [i];
2077 if ((d.ModFlags & modflags) == 0)
2080 TypeBuilder tb = d.TypeBuilder;
2081 if (tb != null && (filter (tb, criteria) == true)) {
2082 if (members == null)
2083 members = new ArrayList ();
2090 if (interfaces != null) {
2091 int len = interfaces.Count;
2092 for (int i = 0; i < len; i++) {
2093 TypeContainer iface = (TypeContainer) interfaces [i];
2095 if ((iface.ModFlags & modflags) == 0)
2098 TypeBuilder tb = iface.TypeBuilder;
2099 if (tb != null && (filter (tb, criteria) == true)) {
2100 if (members == null)
2101 members = new ArrayList ();
2109 if ((mt & MemberTypes.Constructor) != 0){
2110 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2111 int len = instance_constructors.Count;
2112 for (int i = 0; i < len; i++) {
2113 Constructor c = (Constructor) instance_constructors [i];
2115 ConstructorBuilder cb = c.ConstructorBuilder;
2116 if (cb != null && filter (cb, criteria) == true) {
2117 if (members == null)
2118 members = new ArrayList ();
2125 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2126 ConstructorBuilder cb =
2127 default_static_constructor.ConstructorBuilder;
2129 if (cb != null && filter (cb, criteria) == true) {
2130 if (members == null)
2131 members = new ArrayList ();
2139 // Lookup members in parent if requested.
2141 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2142 if (TypeBuilder.BaseType != null) {
2143 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2144 if (list.Count > 0) {
2145 if (members == null)
2146 members = new ArrayList ();
2148 members.AddRange (list);
2154 Timer.StopTimer (TimerType.TcFindMembers);
2156 if (members == null)
2157 return MemberList.Empty;
2159 return new MemberList (members);
2162 public override MemberCache MemberCache {
2164 return member_cache;
2168 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2169 MemberFilter filter, object criteria)
2171 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2174 return ds.FindMembers (mt, bf, filter, criteria);
2176 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2180 // FindMethods will look for methods not only in the type `t', but in
2181 // any interfaces implemented by the type.
2183 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2184 MemberFilter filter, object criteria)
2190 /// Emits the values for the constants
2192 public void EmitConstants ()
2194 if (constants != null)
2195 foreach (Const con in constants)
2200 protected virtual void VerifyMembers (EmitContext ec)
2203 // Check for internal or private fields that were never assigned
2205 if (RootContext.WarningLevel >= 3) {
2206 if (fields != null){
2207 foreach (Field f in fields) {
2208 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2211 if ((f.status & Field.Status.USED) == 0){
2212 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2217 // Only report 649 on level 4
2219 if (RootContext.WarningLevel < 4)
2222 if ((f.status & Field.Status.ASSIGNED) != 0)
2225 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2229 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2230 foreach (Event e in events){
2232 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2239 /// Emits the code, this step is performed after all
2240 /// the types, enumerations, constructors
2242 public void EmitType ()
2244 if (OptAttributes != null)
2245 OptAttributes.Emit (ec, this);
2249 if (instance_constructors != null) {
2250 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2251 bool has_compliant_args = false;
2253 foreach (Constructor c in instance_constructors) {
2256 if (has_compliant_args)
2259 has_compliant_args = c.HasCompliantArgs;
2261 if (!has_compliant_args)
2262 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2264 foreach (Constructor c in instance_constructors)
2269 if (default_static_constructor != null)
2270 default_static_constructor.Emit ();
2272 if (methods != null)
2273 foreach (Method m in methods)
2276 if (operators != null)
2277 foreach (Operator o in operators)
2280 if (properties != null)
2281 foreach (Property p in properties)
2284 if (indexers != null){
2289 foreach (Field f in fields)
2292 if (events != null){
2293 foreach (Event e in Events)
2297 if (delegates != null) {
2298 foreach (Delegate d in Delegates) {
2303 if (enums != null) {
2304 foreach (Enum e in enums) {
2309 if (parts != null) {
2310 foreach (ClassPart part in parts)
2314 if ((Pending != null) && !(this is ClassPart))
2315 if (Pending.VerifyPendingMethods ())
2320 if (iterators != null)
2321 foreach (Iterator iterator in iterators)
2322 iterator.EmitType ();
2324 // if (types != null)
2325 // foreach (TypeContainer tc in types)
2329 public override void CloseType ()
2331 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2335 caching_flags |= Flags.CloseTypeCreated;
2336 TypeBuilder.CreateType ();
2337 } catch (TypeLoadException){
2339 // This is fine, the code still created the type
2341 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2342 // Console.WriteLine (e.Message);
2344 Console.WriteLine ("In type: " + Name);
2349 foreach (Enum en in Enums)
2353 foreach (TypeContainer tc in Types)
2354 if (tc.Kind == Kind.Struct)
2357 foreach (TypeContainer tc in Types)
2358 if (tc.Kind != Kind.Struct)
2362 if (Delegates != null)
2363 foreach (Delegate d in Delegates)
2366 if (Iterators != null)
2367 foreach (Iterator i in Iterators)
2375 initialized_fields = null;
2376 initialized_static_fields = null;
2385 default_constructor = null;
2386 default_static_constructor = null;
2388 OptAttributes = null;
2390 parent_container = null;
2391 member_cache = null;
2394 // TODO: make it obsolete and use GetSignatureForError
2395 public string MakeName (string n)
2397 return "`" + Name + "." + n + "'";
2401 // Performs the validation on a Method's modifiers (properties have
2402 // the same properties).
2404 public bool MethodModifiersValid (int flags, string n, Location loc)
2406 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2407 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2408 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2412 // At most one of static, virtual or override
2414 if ((flags & Modifiers.STATIC) != 0){
2415 if ((flags & vao) != 0){
2417 112, loc, "static method " + MakeName (n) + "can not be marked " +
2418 "as virtual, abstract or override");
2423 if (Kind == Kind.Struct){
2424 if ((flags & va) != 0){
2425 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2430 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2432 113, loc, MakeName (n) +
2433 " marked as override cannot be marked as new or virtual");
2438 // If the declaration includes the abstract modifier, then the
2439 // declaration does not include static, virtual or extern
2441 if ((flags & Modifiers.ABSTRACT) != 0){
2442 if ((flags & Modifiers.EXTERN) != 0){
2444 180, loc, MakeName (n) + " can not be both abstract and extern");
2448 if ((flags & Modifiers.VIRTUAL) != 0){
2450 503, loc, MakeName (n) + " can not be both abstract and virtual");
2454 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2456 513, loc, MakeName (n) +
2457 " is abstract but its container class is not");
2463 if ((flags & Modifiers.PRIVATE) != 0){
2464 if ((flags & vao) != 0){
2466 621, loc, MakeName (n) +
2467 " virtual or abstract members can not be private");
2472 if ((flags & Modifiers.SEALED) != 0){
2473 if ((flags & Modifiers.OVERRIDE) == 0){
2475 238, loc, MakeName (n) +
2476 " cannot be sealed because it is not an override");
2484 Hashtable builder_and_args;
2486 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
2488 if (builder_and_args == null)
2489 builder_and_args = new Hashtable ();
2493 protected override bool VerifyClsCompliance (DeclSpace ds)
2495 if (!base.VerifyClsCompliance (ds))
2500 // parent_container is null for System.Object
2501 if (parent_container != null && !AttributeTester.IsClsCompliant (parent_container.Type)) {
2502 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (parent_container.Type));
2509 /// Checks whether container name is CLS Compliant
2511 void VerifyClsName ()
2513 Hashtable parent_members = parent_container == null ?
2515 parent_container.MemberCache.GetPublicMembers ();
2516 Hashtable this_members = new Hashtable ();
2518 foreach (DictionaryEntry entry in defined_names) {
2519 MemberCore mc = (MemberCore)entry.Value;
2520 if (!mc.IsClsCompliaceRequired (this))
2523 string name = (string)entry.Key;
2524 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2526 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2527 object found = parent_members [lcase];
2528 if (found == null) {
2529 found = this_members [lcase];
2530 if (found == null) {
2531 this_members.Add (lcase, mc);
2536 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2539 if (found is MemberInfo) {
2540 if (basename == ((MemberInfo)found).Name)
2542 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2544 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2546 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2552 /// Performs checks for an explicit interface implementation. First it
2553 /// checks whether the `interface_type' is a base inteface implementation.
2554 /// Then it checks whether `name' exists in the interface type.
2556 public virtual bool VerifyImplements (Type interface_type, string full,
2557 string name, Location loc)
2561 if (ifaces != null){
2562 foreach (Type t in ifaces){
2563 if (t == interface_type){
2571 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2578 protected override void VerifyObsoleteAttribute()
2580 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2585 foreach (Type iface in ifaces) {
2586 CheckUsageOfObsoleteAttribute (iface);
2594 string IMemberContainer.Name {
2600 Type IMemberContainer.Type {
2606 MemberCache IMemberContainer.MemberCache {
2608 return member_cache;
2612 bool IMemberContainer.IsInterface {
2614 return Kind == Kind.Interface;
2618 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2620 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2622 if (GenericType != null)
2623 return TypeManager.FindMembers (GenericType, mt, new_bf,
2626 return FindMembers (mt, new_bf, null, null);
2629 public virtual IMemberContainer ParentContainer {
2631 return parent_container;
2637 public class PartialContainer : TypeContainer {
2639 public readonly Namespace Namespace;
2640 public readonly int OriginalModFlags;
2641 public readonly int AllowedModifiers;
2642 public readonly TypeAttributes DefaultTypeAttributes;
2644 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2645 MemberName name, int mod_flags, Kind kind,
2648 PartialContainer pc;
2649 string full_name = name.GetName (true);
2650 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2652 pc = ds as PartialContainer;
2656 260, ds.Location, "Missing partial modifier " +
2657 "on declaration of type `{0}'; another " +
2658 "partial implementation of this type exists",
2661 Report.LocationOfPreviousError (loc);
2665 if (pc.Kind != kind) {
2667 261, loc, "Partial declarations of `{0}' " +
2668 "must be all classes, all structs or " +
2669 "all interfaces", name);
2673 if (pc.OriginalModFlags != mod_flags) {
2675 262, loc, "Partial declarations of `{0}' " +
2676 "have conflicting accessibility modifiers",
2684 pc = new PartialContainer (ns, parent, name, mod_flags, kind, loc);
2685 RootContext.Tree.RecordDecl (full_name, pc);
2686 parent.AddType (pc);
2691 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2692 MemberName name, int mod, Attributes attrs,
2693 Kind kind, Location loc)
2695 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2697 // An error occured; create a dummy container, but don't
2699 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2702 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2707 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2708 MemberName name, int mod, Kind kind, Location l)
2709 : base (ns, parent, name, null, kind, l)
2711 this.Namespace = ns.NS;
2715 AllowedModifiers = Class.AllowedModifiers;
2716 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2720 AllowedModifiers = Struct.AllowedModifiers;
2721 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2724 case Kind.Interface:
2725 AllowedModifiers = Interface.AllowedModifiers;
2726 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2730 throw new InvalidOperationException ();
2734 if (parent.Parent == null)
2735 accmods = Modifiers.INTERNAL;
2737 accmods = Modifiers.PRIVATE;
2739 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2740 this.OriginalModFlags = mod;
2743 public override void Register ()
2745 if (Kind == Kind.Interface)
2746 Parent.AddInterface (this);
2747 else if (Kind == Kind.Class)
2748 Parent.AddClass (this);
2749 else if (Kind == Kind.Struct)
2750 Parent.AddStruct (this);
2752 throw new InvalidOperationException ();
2755 public override PendingImplementation GetPendingImplementations ()
2757 return PendingImplementation.GetPendingImplementations (this);
2760 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2763 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2768 public override TypeAttributes TypeAttr {
2770 return base.TypeAttr | DefaultTypeAttributes;
2775 public class ClassPart : TypeContainer, IMemberContainer {
2776 public readonly PartialContainer PartialContainer;
2777 public readonly bool IsPartial;
2779 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2780 int mod, Attributes attrs, Kind kind, Location l)
2781 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2783 this.PartialContainer = parent;
2784 this.IsPartial = true;
2787 if (parent.Parent == null)
2788 accmods = Modifiers.INTERNAL;
2790 accmods = Modifiers.PRIVATE;
2792 this.ModFlags = Modifiers.Check (
2793 parent.AllowedModifiers, mod, accmods, l);
2796 public override void Register ()
2800 public override PendingImplementation GetPendingImplementations ()
2802 return PartialContainer.Pending;
2805 public override bool VerifyImplements (Type interface_type, string full,
2806 string name, Location loc)
2808 return PartialContainer.VerifyImplements (
2809 interface_type, full, name, loc);
2812 public override IMemberContainer ParentContainer {
2814 return PartialContainer.ParentContainer;
2819 public abstract class ClassOrStruct : TypeContainer {
2820 bool hasExplicitLayout = false;
2822 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2823 MemberName name, Attributes attrs, Kind kind,
2825 : base (ns, parent, name, attrs, kind, l)
2829 public override PendingImplementation GetPendingImplementations ()
2831 return PendingImplementation.GetPendingImplementations (this);
2834 protected override void VerifyMembers (EmitContext ec)
2836 if (Fields != null) {
2837 foreach (Field f in Fields) {
2838 if ((f.ModFlags & Modifiers.STATIC) != 0)
2840 if (hasExplicitLayout) {
2841 if (f.OptAttributes == null
2842 || !f.OptAttributes.Contains (TypeManager.field_offset_attribute_type, ec)) {
2843 Report.Error (625, f.Location,
2844 "Instance field of type marked with"
2845 + " StructLayout(LayoutKind.Explicit) must have a"
2846 + " FieldOffset attribute.");
2850 if (f.OptAttributes != null
2851 && f.OptAttributes.Contains (TypeManager.field_offset_attribute_type, ec)) {
2852 Report.Error (636, f.Location,
2853 "The FieldOffset attribute can only be placed on members of "
2854 + "types marked with the StructLayout(LayoutKind.Explicit)");
2859 base.VerifyMembers (ec);
2862 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2864 if (a.Type == TypeManager.struct_layout_attribute_type
2865 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2866 hasExplicitLayout = true;
2868 base.ApplyAttributeBuilder (a, cb);
2872 public class Class : ClassOrStruct {
2874 // Modifiers allowed in a class declaration
2876 public const int AllowedModifiers =
2879 Modifiers.PROTECTED |
2880 Modifiers.INTERNAL |
2882 Modifiers.ABSTRACT |
2886 // Information in the case we are an attribute type
2887 AttributeUsageAttribute attribute_usage;
2889 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name,
2890 int mod, Attributes attrs, Location l)
2891 : base (ns, parent, name, attrs, Kind.Class, l)
2895 if (parent.Parent == null)
2896 accmods = Modifiers.INTERNAL;
2898 accmods = Modifiers.PRIVATE;
2900 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2901 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2902 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2905 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2908 public override AttributeTargets AttributeTargets {
2910 return AttributeTargets.Class;
2914 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2916 if (a.UsageAttribute != null)
2917 attribute_usage = a.UsageAttribute;
2919 base.ApplyAttributeBuilder (a, cb);
2922 public AttributeUsageAttribute AttributeUsage {
2924 return attribute_usage;
2928 public override void Register ()
2930 CheckDef (Parent.AddClass (this), Name, Location);
2933 public const TypeAttributes DefaultTypeAttributes =
2934 TypeAttributes.AutoLayout | TypeAttributes.Class;
2937 // FIXME: How do we deal with the user specifying a different
2940 public override TypeAttributes TypeAttr {
2942 return base.TypeAttr | DefaultTypeAttributes;
2947 public class Struct : ClassOrStruct {
2949 // Modifiers allowed in a struct declaration
2951 public const int AllowedModifiers =
2954 Modifiers.PROTECTED |
2955 Modifiers.INTERNAL |
2959 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2960 int mod, Attributes attrs, Location l)
2961 : base (ns, parent, name, attrs, Kind.Struct, l)
2965 if (parent.Parent == null)
2966 accmods = Modifiers.INTERNAL;
2968 accmods = Modifiers.PRIVATE;
2970 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2972 this.ModFlags |= Modifiers.SEALED;
2975 public override AttributeTargets AttributeTargets {
2977 return AttributeTargets.Struct;
2981 public override void Register ()
2983 CheckDef (Parent.AddStruct (this), Name, Location);
2986 public const TypeAttributes DefaultTypeAttributes =
2987 TypeAttributes.SequentialLayout |
2988 TypeAttributes.Sealed |
2989 TypeAttributes.BeforeFieldInit;
2992 // FIXME: Allow the user to specify a different set of attributes
2993 // in some cases (Sealed for example is mandatory for a class,
2994 // but what SequentialLayout can be changed
2996 public override TypeAttributes TypeAttr {
2998 return base.TypeAttr | DefaultTypeAttributes;
3006 public class Interface : TypeContainer, IMemberContainer {
3008 /// Modifiers allowed in a class declaration
3010 public const int AllowedModifiers =
3013 Modifiers.PROTECTED |
3014 Modifiers.INTERNAL |
3018 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3019 int mod, Attributes attrs, Location l)
3020 : base (ns, parent, name, attrs, Kind.Interface, l)
3024 if (parent.Parent == null)
3025 accmods = Modifiers.INTERNAL;
3027 accmods = Modifiers.PRIVATE;
3029 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3032 public override void Register ()
3034 CheckDef (Parent.AddInterface (this), Name, Location);
3037 public override PendingImplementation GetPendingImplementations ()
3042 public override AttributeTargets AttributeTargets {
3044 return AttributeTargets.Interface;
3048 public const TypeAttributes DefaultTypeAttributes =
3049 TypeAttributes.AutoLayout |
3050 TypeAttributes.Abstract |
3051 TypeAttributes.Interface;
3053 public override TypeAttributes TypeAttr {
3055 return base.TypeAttr | DefaultTypeAttributes;
3060 public abstract class MethodCore : MemberBase {
3061 public readonly Parameters Parameters;
3062 public readonly GenericMethod GenericMethod;
3063 public readonly DeclSpace ds;
3064 protected Block block;
3067 // Parameters, cached for semantic analysis.
3069 protected InternalParameters parameter_info;
3070 protected Type [] parameter_types;
3072 // Whether this is an operator method.
3073 public bool IsOperator;
3076 // The method we're overriding if this is an override method.
3078 protected MethodInfo parent_method = null;
3080 static string[] attribute_targets = new string [] { "method", "return" };
3082 public MethodCore (TypeContainer parent, GenericMethod generic,
3083 Expression type, int mod, int allowed_mod, bool is_iface,
3084 MemberName name, Attributes attrs, Parameters parameters,
3086 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3089 Parameters = parameters;
3090 IsInterface = is_iface;
3091 this.GenericMethod = generic;
3093 if (generic != null)
3100 // Returns the System.Type array for the parameters of this method
3102 public Type [] ParameterTypes {
3104 return parameter_types;
3108 public InternalParameters ParameterInfo
3111 return parameter_info;
3115 public Block Block {
3125 protected override bool CheckBase ()
3127 if (!base.CheckBase ())
3130 // Check whether arguments were correct.
3131 if (!DoDefineParameters ())
3137 // TODO: Is it correct ?
3139 if (!CheckForDuplications ())
3143 // Is null for System.Object while compiling corlib and base interfaces
3144 if (Parent.ParentContainer == null) {
3145 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3146 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3151 Type parent_ret_type = null;
3152 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3154 // method is override
3155 if (parent_method != null) {
3157 if (!CheckMethodAgainstBase ())
3160 if ((ModFlags & Modifiers.NEW) == 0) {
3161 if (!MemberType.Equals (TypeManager.TypeToCoreType (parent_ret_type))) {
3162 Report.SymbolRelatedToPreviousError (parent_method);
3163 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3164 "change return type when overriding inherited member");
3169 if (RootContext.WarningLevel > 2) {
3170 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3171 Parent.Methods.HasEquals = true;
3172 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3173 Parent.Methods.HasGetHashCode = true;
3176 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3178 Report.SymbolRelatedToPreviousError (parent_method);
3179 Report.Warning (672, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3184 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3185 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3189 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3190 if (conflict_symbol == null) {
3191 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3192 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3197 if ((ModFlags & Modifiers.NEW) == 0) {
3198 if (this is Method && conflict_symbol is MethodBase)
3201 Report.SymbolRelatedToPreviousError (conflict_symbol);
3202 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3210 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3211 // that have been defined.
3213 // `name' is the user visible name for reporting errors (this is used to
3214 // provide the right name regarding method names and properties)
3216 bool CheckMethodAgainstBase ()
3220 // TODO: replace with GetSignatureForError
3221 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3223 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3224 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3226 506, Location, Parent.MakeName (Name) +
3227 ": cannot override inherited member `" +
3228 name + "' because it is not " +
3229 "virtual, abstract or override");
3233 // Now we check that the overriden method is not final
3235 if (parent_method.IsFinal) {
3236 // This happens when implementing interface methods.
3237 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3239 506, Location, Parent.MakeName (Name) +
3240 ": cannot override inherited member `" +
3241 name + "' because it is not " +
3242 "virtual, abstract or override");
3244 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3245 "override inherited member `" + name +
3246 "' because it is sealed.");
3250 // Check that the permissions are not being changed
3252 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3253 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3256 // special case for "protected internal"
3259 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3261 // when overriding protected internal, the method can be declared
3262 // protected internal only within the same assembly
3265 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3266 if (Parent.TypeBuilder.Assembly != parent_method.DeclaringType.Assembly){
3268 // assemblies differ - report an error
3271 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3273 } else if (thisp != parentp) {
3275 // same assembly, but other attributes differ - report an error
3278 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3281 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3283 // if it's not "protected internal", it must be "protected"
3286 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3288 } else if (Parent.TypeBuilder.Assembly == parent_method.DeclaringType.Assembly) {
3290 // protected within the same assembly - an error
3292 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3294 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3295 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3297 // protected ok, but other attributes differ - report an error
3299 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3303 if (thisp != parentp){
3304 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3310 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3311 ModFlags |= Modifiers.NEW;
3312 Report.SymbolRelatedToPreviousError (parent_method);
3313 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3314 if (RootContext.WarningLevel >= 2)
3315 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), parent_method);
3317 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member `{1}'", GetSignatureForError (Parent), parent_method);
3323 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3326 // FIXME: report the old/new permissions?
3329 507, Location, parent.MakeName (Name) +
3330 ": can't change the access modifiers when overriding inherited " +
3331 "member `" + name + "'");
3335 /// For custom member duplication search in a container
3337 protected abstract bool CheckForDuplications ();
3340 /// Gets parent method and its return type
3342 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3344 protected virtual bool DoDefineParameters ()
3346 // Check if arguments were correct
3347 parameter_types = Parameters.GetParameterInfo (ds);
3348 if ((parameter_types == null) ||
3349 !CheckParameters (ds, parameter_types))
3352 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3353 parameter_info = new InternalParameters (ds, Parameters, tparam);
3355 Parameter array_param = Parameters.ArrayParameter;
3356 if ((array_param != null) &&
3357 (!array_param.ParameterType.IsArray ||
3358 (array_param.ParameterType.GetArrayRank () != 1))) {
3359 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3366 void error_425 (Type old, Type t, string name)
3368 Report.Error (425, Location,
3369 "The constraints of type parameter `{0}' " +
3370 "of method `{1}' must match the constraints for " +
3371 "type parameter `{2}' of method `{3}'",
3372 TypeManager.CSharpName (old), Name,
3373 TypeManager.CSharpName (t), name);
3376 protected override bool CheckGenericOverride (MethodInfo method, string name)
3378 ParameterData pd = Invocation.GetParameterData (method);
3380 for (int i = 0; i < ParameterTypes.Length; i++) {
3381 GenericConstraints ogc = pd.GenericConstraints (i);
3382 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3384 if ((gc == null) && (ogc == null))
3387 Type ot = pd.ParameterType (i);
3388 Type t = ParameterTypes [i];
3390 if (!((gc != null) && (ogc != null))) {
3391 error_425 (ot, t, name);
3395 if (gc.HasConstructor != ogc.HasConstructor) {
3396 error_425 (ot, t, name);
3400 if (ogc.HasClassConstraint != gc.HasClassConstraint) {
3401 error_425 (ot, t, name);
3405 if (ogc.HasClassConstraint &&
3406 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3407 error_425 (ot, t, name);
3411 Type[] oct = ogc.InterfaceConstraints;
3412 Type[] ct = gc.InterfaceConstraints;
3414 if (oct.Length != ct.Length) {
3415 error_425 (ot, t, name);
3419 for (int j = 0; j < oct.Length; j++)
3420 if (!oct [j].Equals (ct [j])) {
3421 error_425 (ot, t, name);
3429 public override string[] ValidAttributeTargets {
3431 return attribute_targets;
3435 protected override bool VerifyClsCompliance (DeclSpace ds)
3437 if (!base.VerifyClsCompliance (ds)) {
3438 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3439 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3444 if (Parameters.HasArglist) {
3445 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3448 if (!AttributeTester.IsClsCompliant (MemberType)) {
3449 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
3452 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3457 protected bool IsDuplicateImplementation (MethodCore method)
3459 if ((method == this) || (method.Name != Name))
3462 Type[] param_types = method.ParameterTypes;
3463 if (param_types == null)
3466 if (param_types.Length != ParameterTypes.Length)
3469 int type_params = 0;
3470 if (GenericMethod != null)
3471 type_params = GenericMethod.CountTypeParameters;
3473 int m_type_params = 0;
3474 if (method.GenericMethod != null)
3475 m_type_params = method.GenericMethod.CountTypeParameters;
3477 if (type_params != m_type_params)
3483 Type[] infered_types;
3484 if (type_params > 0)
3485 infered_types = new Type [type_params];
3487 infered_types = null;
3489 may_unify = Invocation.InferTypeArguments (
3490 param_types, ParameterTypes, ref infered_types);
3493 if (type_params > 0)
3494 infered_types = new Type [type_params];
3496 infered_types = null;
3498 may_unify = Invocation.InferTypeArguments (
3499 ParameterTypes, param_types, ref infered_types);
3502 for (int i = 0; i < param_types.Length; i++) {
3503 Type a = param_types [i];
3504 Type b = ParameterTypes [i];
3512 // Try to report 663: method only differs on out/ref
3514 ParameterData info = ParameterInfo;
3515 ParameterData other_info = method.ParameterInfo;
3516 for (int i = 0; i < info.Count; i++){
3517 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3518 Report.Error (663, Location,
3519 "Overload method only differs " +
3520 "in parameter modifier");
3525 Report.SymbolRelatedToPreviousError (method);
3526 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with the same parameter types", Parent.Name, Name);
3528 } else if (may_unify) {
3529 Report.Error (408, Location,
3530 "`{0}' cannot define overload members that " +
3531 "may unify for some type parameter substitutions",
3539 protected override void VerifyObsoleteAttribute()
3541 base.VerifyObsoleteAttribute ();
3543 if (parameter_types == null)
3546 foreach (Type type in parameter_types) {
3547 CheckUsageOfObsoleteAttribute (type);
3552 public class SourceMethod : ISourceMethod
3554 TypeContainer container;
3557 protected SourceMethod (TypeContainer container, MethodBase builder,
3558 ISourceFile file, Location start, Location end)
3560 this.container = container;
3561 this.builder = builder;
3563 CodeGen.SymbolWriter.OpenMethod (
3564 file, this, start.Row, 0, end.Row, 0);
3567 public string Name {
3568 get { return builder.Name; }
3571 public int NamespaceID {
3572 get { return container.NamespaceEntry.SymbolFileID; }
3577 if (builder is MethodBuilder)
3578 return ((MethodBuilder) builder).GetToken ().Token;
3579 else if (builder is ConstructorBuilder)
3580 return ((ConstructorBuilder) builder).GetToken ().Token;
3582 throw new NotSupportedException ();
3586 public void CloseMethod ()
3588 if (CodeGen.SymbolWriter != null)
3589 CodeGen.SymbolWriter.CloseMethod ();
3592 public static SourceMethod Create (TypeContainer parent,
3593 MethodBase builder, Block block)
3595 if (CodeGen.SymbolWriter == null)
3600 Location start_loc = block.StartLocation;
3601 if (Location.IsNull (start_loc))
3604 Location end_loc = block.EndLocation;
3605 if (Location.IsNull (end_loc))
3608 ISourceFile file = start_loc.SourceFile;
3612 return new SourceMethod (
3613 parent, builder, file, start_loc, end_loc);
3617 public class Method : MethodCore, IIteratorContainer, IMethodData {
3618 public MethodBuilder MethodBuilder;
3619 public MethodData MethodData;
3620 ReturnParameter return_attributes;
3623 /// Modifiers allowed in a class declaration
3625 const int AllowedModifiers =
3628 Modifiers.PROTECTED |
3629 Modifiers.INTERNAL |
3634 Modifiers.OVERRIDE |
3635 Modifiers.ABSTRACT |
3637 Modifiers.METHOD_YIELDS |
3640 const int AllowedInterfaceModifiers =
3641 Modifiers.NEW | Modifiers.UNSAFE;
3644 // return_type can be "null" for VOID values.
3646 public Method (TypeContainer parent, GenericMethod generic,
3647 Expression return_type, int mod, bool is_iface,
3648 MemberName name, Parameters parameters, Attributes attrs,
3650 : base (parent, generic, return_type, mod,
3651 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3652 is_iface, name, attrs, parameters, l)
3656 public override AttributeTargets AttributeTargets {
3658 return AttributeTargets.Method;
3663 // Returns the `System.Type' for the ReturnType of this
3664 // function. Provides a nice cache. (used between semantic analysis
3665 // and actual code generation
3667 public Type GetReturnType ()
3672 public override string GetSignatureForError()
3674 return TypeManager.CSharpSignature (MethodBuilder);
3678 /// Use this method when MethodBuilder is null
3680 public override string GetSignatureForError (TypeContainer tc)
3682 // TODO: move to parameters
3683 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3684 if (parameter_info.Parameters.FixedParameters != null) {
3685 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3686 Parameter p = parameter_info.Parameters.FixedParameters [i];
3687 args.Append (p.GetSignatureForError ());
3689 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3694 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3697 void DuplicateEntryPoint (MethodInfo b, Location location)
3701 "Program `" + CodeGen.FileName +
3702 "' has more than one entry point defined: `" +
3703 TypeManager.CSharpSignature(b) + "'");
3706 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3708 if (b.ReturnType != TypeManager.void_type &&
3709 b.ReturnType != TypeManager.int32_type)
3712 if (pinfo.Count == 0)
3715 if (pinfo.Count > 1)
3718 Type t = pinfo.ParameterType(0);
3720 (t.GetArrayRank() == 1) &&
3721 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3722 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3728 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3730 if (a.Target == AttributeTargets.ReturnValue) {
3731 if (return_attributes == null)
3732 return_attributes = new ReturnParameter (MethodBuilder, Location);
3734 return_attributes.ApplyAttributeBuilder (a, cb);
3738 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3739 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3742 if (a.Type == TypeManager.dllimport_type) {
3743 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3744 if ((ModFlags & extern_static) != extern_static) {
3745 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3751 if (a.Type == TypeManager.conditional_attribute_type) {
3752 if (IsOperator || IsExplicitImpl) {
3753 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3757 if (ReturnType != TypeManager.void_type) {
3758 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3762 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3763 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3768 Report.Error (582, Location, "Conditional not valid on interface members");
3772 if (MethodData.IsImplementing) {
3773 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3778 MethodBuilder.SetCustomAttribute (cb);
3781 protected override bool CheckForDuplications ()
3783 ArrayList ar = Parent.Methods;
3785 int arLen = ar.Count;
3787 for (int i = 0; i < arLen; i++) {
3788 Method m = (Method) ar [i];
3789 if (IsDuplicateImplementation (m))
3800 public override bool Define ()
3802 if (!DoDefineBase ())
3805 MethodBuilder mb = null;
3806 if (GenericMethod != null) {
3807 string mname = MemberName.GetMethodName ();
3808 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
3809 if (!GenericMethod.Define (mb))
3820 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3822 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
3823 this, mb, GenericMethod);
3825 if (!MethodData.Define (Parent))
3829 // Setup iterator if we are one
3831 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3832 Iterator iterator = new Iterator (
3833 Parent, Name, MemberType, ParameterTypes,
3834 ParameterInfo, ModFlags, block, Location);
3836 if (!iterator.DefineIterator ())
3839 block = iterator.Block;
3842 MethodBuilder = MethodData.MethodBuilder;
3845 // This is used to track the Entry Point,
3847 if (Name == "Main" &&
3848 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3849 (RootContext.MainClass == null ||
3850 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3851 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3852 if (RootContext.EntryPoint == null) {
3853 if (Parent.IsGeneric){
3854 Report.Error (-201, Location,
3855 "Entry point can not be defined in a generic class");
3858 RootContext.EntryPoint = MethodBuilder;
3859 RootContext.EntryPointLocation = Location;
3861 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3862 DuplicateEntryPoint (MethodBuilder, Location);
3865 if (RootContext.WarningLevel >= 4)
3866 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
3876 public override void Emit ()
3878 MethodData.Emit (Parent, this);
3884 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3886 MethodInfo mi = (MethodInfo) container.ParentContainer.MemberCache.FindMemberToOverride (
3887 container.TypeBuilder, Name, ParameterTypes, false);
3892 parent_ret_type = mi.ReturnType;
3896 protected override bool VerifyClsCompliance(DeclSpace ds)
3898 if (!base.VerifyClsCompliance (ds))
3901 if (parameter_types.Length > 0) {
3902 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3904 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3911 void IIteratorContainer.SetYields ()
3913 ModFlags |= Modifiers.METHOD_YIELDS;
3916 #region IMethodData Members
3918 public CallingConventions CallingConventions {
3920 CallingConventions cc = Parameters.GetCallingConvention ();
3921 if (Parameters.HasArglist)
3922 block.HasVarargs = true;
3925 if ((ModFlags & Modifiers.STATIC) == 0)
3926 cc |= CallingConventions.HasThis;
3928 // FIXME: How is `ExplicitThis' used in C#?
3934 public Type ReturnType {
3940 public string MethodName {
3946 public new Location Location {
3948 return base.Location;
3952 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3954 return new EmitContext (
3955 tc, ds, Location, ig, ReturnType, ModFlags, false);
3958 public ObsoleteAttribute GetObsoleteAttribute ()
3960 return GetObsoleteAttribute (ds);
3964 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3966 public bool IsExcluded (EmitContext ec)
3968 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3969 return (caching_flags & Flags.Excluded) != 0;
3971 caching_flags &= ~Flags.Excluded_Undetected;
3973 if (parent_method == null) {
3974 if (OptAttributes == null)
3977 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3982 foreach (Attribute a in attrs) {
3983 string condition = a.GetConditionalAttributeValue (ds);
3984 if (RootContext.AllDefines.Contains (condition))
3988 caching_flags |= Flags.Excluded;
3992 IMethodData md = TypeManager.GetMethod (parent_method);
3994 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
3995 caching_flags |= Flags.Excluded;
4001 if (md.IsExcluded (ec)) {
4002 caching_flags |= Flags.Excluded;
4008 GenericMethod IMethodData.GenericMethod {
4010 return GenericMethod;
4016 public abstract class ConstructorInitializer {
4017 ArrayList argument_list;
4018 protected ConstructorInfo parent_constructor;
4019 Parameters parameters;
4022 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4025 this.argument_list = argument_list;
4026 this.parameters = parameters;
4030 public ArrayList Arguments {
4032 return argument_list;
4036 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4038 Expression parent_constructor_group;
4041 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4043 if (argument_list != null){
4044 foreach (Argument a in argument_list){
4045 if (!a.Resolve (ec, loc))
4049 ec.CurrentBlock = null;
4051 if (this is ConstructorBaseInitializer) {
4052 if (ec.ContainerType.BaseType == null)
4055 t = ec.ContainerType.BaseType;
4056 if (ec.ContainerType.IsValueType) {
4057 Report.Error (522, loc,
4058 "structs cannot call base class constructors");
4062 t = ec.ContainerType;
4064 parent_constructor_group = Expression.MemberLookup (
4065 ec, t, ".ctor", MemberTypes.Constructor,
4066 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4069 if (parent_constructor_group == null){
4070 parent_constructor_group = Expression.MemberLookup (
4071 ec, t, ".ctor", MemberTypes.Constructor,
4072 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4075 if (parent_constructor_group != null)
4077 112, loc, "`{0}.{1}' is inaccessible due to " +
4078 "its protection level", t.FullName, t.Name);
4081 1501, loc, "Can not find a constructor for " +
4082 "this argument list");
4086 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4087 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
4090 if (parent_constructor == null){
4091 Report.Error (1501, loc,
4092 "Can not find a constructor for this argument list");
4096 if (parent_constructor == caller_builder){
4097 Report.Error (515, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
4104 public void Emit (EmitContext ec)
4106 if (parent_constructor != null){
4107 ec.Mark (loc, false);
4109 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
4111 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
4116 /// Method search for base ctor. (We do not cache it).
4118 Constructor GetOverloadedConstructor (TypeContainer tc)
4120 if (tc.InstanceConstructors == null)
4123 foreach (Constructor c in tc.InstanceConstructors) {
4124 if (Arguments == null) {
4125 if (c.ParameterTypes.Length == 0)
4133 int count = c.ParameterInfo.Count;
4135 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4136 for (int i = 0; i < count-1; i++)
4137 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4142 if (c.ParameterTypes.Length != Arguments.Count)
4145 for (int i = 0; i < Arguments.Count; ++i)
4146 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4161 //TODO: implement caching when it will be necessary
4162 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4164 Constructor ctor = GetOverloadedConstructor (tc);
4168 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4172 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4176 public class ConstructorBaseInitializer : ConstructorInitializer {
4177 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4178 base (argument_list, pars, l)
4182 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4183 if (parent_constructor == null)
4186 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4187 if (type_ds == null) {
4188 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4191 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4196 base.CheckObsoleteAttribute (type_ds, loc);
4201 public class ConstructorThisInitializer : ConstructorInitializer {
4202 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4203 base (argument_list, pars, l)
4208 public class Constructor : MethodCore, IMethodData {
4209 public ConstructorBuilder ConstructorBuilder;
4210 public ConstructorInitializer Initializer;
4213 // Modifiers allowed for a constructor.
4215 public const int AllowedModifiers =
4217 Modifiers.PROTECTED |
4218 Modifiers.INTERNAL |
4224 bool has_compliant_args = false;
4226 // The spec claims that static is not permitted, but
4227 // my very own code has static constructors.
4229 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4230 ConstructorInitializer init, Location l)
4231 : base (ds, null, null, mod, AllowedModifiers, false,
4232 new MemberName (name), null, args, l)
4237 public override string GetSignatureForError()
4239 return TypeManager.CSharpSignature (ConstructorBuilder);
4242 public bool HasCompliantArgs {
4244 return has_compliant_args;
4248 public override AttributeTargets AttributeTargets {
4250 return AttributeTargets.Constructor;
4256 // Returns true if this is a default constructor
4258 public bool IsDefault ()
4260 if ((ModFlags & Modifiers.STATIC) != 0)
4261 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4262 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4265 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4266 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4267 (Initializer is ConstructorBaseInitializer) &&
4268 (Initializer.Arguments == null);
4271 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4273 ConstructorBuilder.SetCustomAttribute (cb);
4276 protected override bool CheckForDuplications ()
4278 ArrayList ar = Parent.InstanceConstructors;
4280 int arLen = ar.Count;
4282 for (int i = 0; i < arLen; i++) {
4283 Constructor m = (Constructor) ar [i];
4284 if (IsDuplicateImplementation (m))
4291 protected override bool CheckBase ()
4293 // Check whether arguments were correct.
4294 if (!DoDefineParameters ())
4297 // TODO: skip the rest for generated ctor
4298 if ((ModFlags & Modifiers.STATIC) != 0)
4301 if (!CheckForDuplications ())
4304 if (Parent.Kind == Kind.Struct) {
4305 if (ParameterTypes.Length == 0) {
4306 Report.Error (568, Location,
4307 "Structs can not contain explicit parameterless " +
4312 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4313 Report.Error (666, Location, "Protected member in struct declaration");
4318 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4319 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4326 // Creates the ConstructorBuilder
4328 public override bool Define ()
4330 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4331 MethodAttributes.SpecialName);
4333 if ((ModFlags & Modifiers.STATIC) != 0){
4334 ca |= MethodAttributes.Static | MethodAttributes.Private;
4336 ca |= MethodAttributes.HideBySig;
4338 if ((ModFlags & Modifiers.PUBLIC) != 0)
4339 ca |= MethodAttributes.Public;
4340 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4341 if ((ModFlags & Modifiers.INTERNAL) != 0)
4342 ca |= MethodAttributes.FamORAssem;
4344 ca |= MethodAttributes.Family;
4345 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4346 ca |= MethodAttributes.Assembly;
4347 else if (IsDefault ())
4348 ca |= MethodAttributes.Public;
4350 ca |= MethodAttributes.Private;
4353 // Check if arguments were correct.
4357 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4358 ca, CallingConventions,
4361 if ((ModFlags & Modifiers.UNSAFE) != 0)
4362 ConstructorBuilder.InitLocals = false;
4364 TypeManager.AddMethod (ConstructorBuilder, this);
4367 // HACK because System.Reflection.Emit is lame
4369 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4377 public override void Emit ()
4379 EmitContext ec = CreateEmitContext (null, null);
4382 // extern methods have no bodies
4384 if ((ModFlags & Modifiers.EXTERN) != 0) {
4385 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4387 179, Location, "External constructor `" +
4388 TypeManager.CSharpSignature (ConstructorBuilder) +
4389 "' can not have a body");
4392 } else if (block == null) {
4394 501, Location, "Constructor `" +
4395 TypeManager.CSharpSignature (ConstructorBuilder) +
4396 "' must declare a body since it is not marked extern");
4400 if ((ModFlags & Modifiers.STATIC) == 0){
4401 if (Parent.Kind == Kind.Class && Initializer == null)
4402 Initializer = new ConstructorBaseInitializer (
4403 null, Parameters.EmptyReadOnlyParameters, Location);
4407 // Spec mandates that Initializers will not have
4411 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4413 ec.IsStatic = false;
4416 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4418 SourceMethod source = SourceMethod.Create (
4419 Parent, ConstructorBuilder, block);
4422 // Classes can have base initializers and instance field initializers.
4424 if (Parent.Kind == Kind.Class){
4425 if ((ModFlags & Modifiers.STATIC) == 0){
4428 // If we use a "this (...)" constructor initializer, then
4429 // do not emit field initializers, they are initialized in the other constructor
4431 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4432 Parent.EmitFieldInitializers (ec);
4435 if (Initializer != null) {
4436 Initializer.CheckObsoleteAttribute (Parent, Location);
4437 Initializer.Emit (ec);
4440 if ((ModFlags & Modifiers.STATIC) != 0)
4441 Parent.EmitFieldInitializers (ec);
4443 if (OptAttributes != null)
4444 OptAttributes.Emit (ec, this);
4446 // If this is a non-static `struct' constructor and doesn't have any
4447 // initializer, it must initialize all of the struct's fields.
4448 if ((Parent.Kind == Kind.Struct) &&
4449 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4450 Block.AddThisVariable (Parent, Location);
4452 ec.EmitTopBlock (block, ParameterInfo, Location);
4455 source.CloseMethod ();
4462 // Is never override
4463 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4468 protected override bool VerifyClsCompliance (DeclSpace ds)
4470 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4474 if (parameter_types.Length > 0) {
4475 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4477 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4479 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4480 foreach (Type param in parameter_types) {
4481 if (param.IsArray) {
4487 has_compliant_args = true;
4491 #region IMethodData Members
4493 public System.Reflection.CallingConventions CallingConventions {
4495 CallingConventions cc = Parameters.GetCallingConvention ();
4497 if (Parent.Kind == Kind.Class)
4498 if ((ModFlags & Modifiers.STATIC) == 0)
4499 cc |= CallingConventions.HasThis;
4501 // FIXME: How is `ExplicitThis' used in C#?
4507 public new Location Location {
4509 return base.Location;
4513 public string MethodName {
4519 public Type ReturnType {
4525 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4527 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4528 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4531 public ObsoleteAttribute GetObsoleteAttribute ()
4536 public bool IsExcluded(EmitContext ec)
4541 GenericMethod IMethodData.GenericMethod {
4551 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4553 public interface IMethodData
4555 CallingConventions CallingConventions { get; }
4556 Location Location { get; }
4557 string MethodName { get; }
4558 Type[] ParameterTypes { get; }
4559 Type ReturnType { get; }
4560 GenericMethod GenericMethod { get; }
4562 Attributes OptAttributes { get; }
4563 Block Block { get; }
4565 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4566 ObsoleteAttribute GetObsoleteAttribute ();
4567 string GetSignatureForError (TypeContainer tc);
4568 bool IsExcluded (EmitContext ec);
4569 bool IsClsCompliaceRequired (DeclSpace ds);
4573 // Encapsulates most of the Method's state
4575 public class MethodData {
4577 readonly IMethodData method;
4580 // The return type of this method
4582 public readonly GenericMethod GenericMethod;
4583 public readonly InternalParameters ParameterInfo;
4586 // Are we implementing an interface ?
4588 public bool IsImplementing = false;
4593 protected MemberBase member;
4594 protected int modifiers;
4595 protected MethodAttributes flags;
4596 protected Type declaring_type;
4600 MethodBuilder builder = null;
4601 public MethodBuilder MethodBuilder {
4607 public Type DeclaringType {
4609 return declaring_type;
4613 public MethodData (MemberBase member, InternalParameters parameters,
4614 int modifiers, MethodAttributes flags, IMethodData method)
4616 this.member = member;
4617 this.ParameterInfo = parameters;
4618 this.modifiers = modifiers;
4621 this.method = method;
4624 public MethodData (MemberBase member, InternalParameters parameters,
4625 int modifiers, MethodAttributes flags,
4626 IMethodData method, MethodBuilder builder,
4627 GenericMethod generic)
4628 : this (member, parameters, modifiers, flags, method)
4630 this.builder = builder;
4631 this.GenericMethod = generic;
4634 static string RemoveArity (string name)
4637 StringBuilder sb = new StringBuilder ();
4638 while (start < name.Length) {
4639 int pos = name.IndexOf ('`', start);
4641 sb.Append (name.Substring (start));
4645 sb.Append (name.Substring (start, pos-start));
4648 while ((pos < name.Length) && Char.IsNumber (name [pos]))
4654 return sb.ToString ();
4657 public bool Define (TypeContainer container)
4659 MethodInfo implementing = null;
4662 if (member.IsExplicitImpl)
4663 prefix = RemoveArity (member.InterfaceType.FullName) + ".";
4667 string name = method.MethodName;
4668 string method_name = prefix + name;
4669 Type[] ParameterTypes = method.ParameterTypes;
4671 if (container.Pending != null){
4672 if (member is Indexer)
4673 implementing = container.Pending.IsInterfaceIndexer (
4674 member.InterfaceType, method.ReturnType, ParameterTypes);
4676 implementing = container.Pending.IsInterfaceMethod (
4677 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4679 if (member.InterfaceType != null && implementing == null){
4680 Report.Error (539, method.Location, "'{0}' in explicit interface declaration is not an interface", method_name);
4686 // For implicit implementations, make sure we are public, for
4687 // explicit implementations, make sure we are private.
4689 if (implementing != null){
4691 // Setting null inside this block will trigger a more
4692 // verbose error reporting for missing interface implementations
4694 // The "candidate" function has been flagged already
4695 // but it wont get cleared
4697 if (member.IsExplicitImpl){
4698 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4699 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4700 implementing = null;
4702 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4703 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4705 // If this is an interface method implementation,
4706 // check for public accessibility
4708 implementing = null;
4709 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4710 // We may never be private.
4711 implementing = null;
4712 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4714 // We may be protected if we're overriding something.
4716 implementing = null;
4721 // Static is not allowed
4723 if ((modifiers & Modifiers.STATIC) != 0){
4724 implementing = null;
4725 Modifiers.Error_InvalidModifier (method.Location, "static");
4730 // If implementing is still valid, set flags
4732 if (implementing != null){
4734 // When implementing interface methods, set NewSlot
4735 // unless, we are overwriting a method.
4737 if (implementing.DeclaringType.IsInterface){
4738 if ((modifiers & Modifiers.OVERRIDE) == 0)
4739 flags |= MethodAttributes.NewSlot;
4742 MethodAttributes.Virtual |
4743 MethodAttributes.HideBySig;
4745 // Set Final unless we're virtual, abstract or already overriding a method.
4746 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4747 flags |= MethodAttributes.Final;
4749 // Get the method name from the explicit interface.
4750 if (member.InterfaceType != null) {
4751 name = implementing.Name;
4752 method_name = prefix + name;
4755 IsImplementing = true;
4758 EmitContext ec = method.CreateEmitContext (container, null);
4760 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4762 if (builder == null)
4765 if (container.CurrentType != null)
4766 declaring_type = container.CurrentType.ResolveType (ec);
4768 declaring_type = container.TypeBuilder;
4770 if ((modifiers & Modifiers.UNSAFE) != 0)
4771 builder.InitLocals = false;
4773 if (IsImplementing){
4775 // clear the pending implemntation flag
4777 if (member is Indexer) {
4778 container.Pending.ImplementIndexer (
4779 member.InterfaceType, builder, method.ReturnType,
4780 ParameterTypes, true);
4782 container.Pending.ImplementMethod (
4783 member.InterfaceType, name, method.ReturnType,
4784 ParameterTypes, member.IsExplicitImpl);
4786 if (member.IsExplicitImpl)
4787 container.TypeBuilder.DefineMethodOverride (
4788 builder, implementing);
4792 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
4793 Report.Error (111, method.Location,
4794 "Class `" + container.Name +
4795 "' already contains a definition with the " +
4796 "same return value and parameter types as the " +
4797 "'get' method of property `" + member.Name + "'");
4801 TypeManager.AddMethod (builder, method);
4803 if (GenericMethod != null) {
4804 bool is_override = member.IsExplicitImpl |
4805 ((modifiers & Modifiers.OVERRIDE) != 0);
4807 is_override &= IsImplementing;
4809 if (!GenericMethod.DefineType (
4810 ec, builder, implementing, is_override))
4818 /// Create the MethodBuilder for the method
4820 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4822 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4824 if ((modifiers & extern_static) == extern_static) {
4826 if (method.OptAttributes != null) {
4827 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4828 if (dllimport_attribute != null) {
4829 flags |= MethodAttributes.PinvokeImpl;
4830 builder = dllimport_attribute.DefinePInvokeMethod (
4831 ec, container.TypeBuilder, method_name, flags,
4832 method.ReturnType, ParameterTypes);
4838 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4839 // We are more strict than Microsoft and report CS0626 like error
4840 if (method.OptAttributes == null ||
4841 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4842 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", method.GetSignatureForError (container));
4847 if (builder == null)
4848 builder = container.TypeBuilder.DefineMethod (
4849 method_name, flags, method.CallingConventions,
4850 method.ReturnType, ParameterTypes);
4852 builder.SetGenericMethodSignature (
4853 flags, method.CallingConventions,
4854 method.ReturnType, ParameterTypes);
4860 public void Emit (TypeContainer container, Attributable kind)
4863 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4864 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4866 ec = method.CreateEmitContext (container, null);
4868 Location loc = method.Location;
4869 Attributes OptAttributes = method.OptAttributes;
4871 if (OptAttributes != null)
4872 OptAttributes.Emit (ec, kind);
4874 if (member is MethodCore)
4875 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4877 Block block = method.Block;
4880 // abstract or extern methods have no bodies
4882 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4887 // abstract or extern methods have no bodies.
4889 if ((modifiers & Modifiers.ABSTRACT) != 0)
4891 500, method.Location, "Abstract method `" +
4892 TypeManager.CSharpSignature (builder) +
4893 "' can not have a body");
4895 if ((modifiers & Modifiers.EXTERN) != 0)
4897 179, method.Location, "External method `" +
4898 TypeManager.CSharpSignature (builder) +
4899 "' can not have a body");
4905 // Methods must have a body unless they're extern or abstract
4907 if (block == null) {
4909 501, method.Location, "Method `" +
4910 TypeManager.CSharpSignature (builder) +
4911 "' must declare a body since it is not marked " +
4912 "abstract or extern");
4916 SourceMethod source = SourceMethod.Create (
4917 container, MethodBuilder, method.Block);
4920 // Handle destructors specially
4922 // FIXME: This code generates buggy code
4924 if (member is Destructor)
4925 EmitDestructor (ec, block);
4927 ec.EmitTopBlock (block, ParameterInfo, loc);
4930 source.CloseMethod ();
4933 void EmitDestructor (EmitContext ec, Block block)
4935 ILGenerator ig = ec.ig;
4937 Label finish = ig.DefineLabel ();
4939 block.SetDestructor ();
4941 ig.BeginExceptionBlock ();
4942 ec.ReturnLabel = finish;
4943 ec.HasReturnLabel = true;
4944 ec.EmitTopBlock (block, null, method.Location);
4946 // ig.MarkLabel (finish);
4947 ig.BeginFinallyBlock ();
4949 if (ec.ContainerType.BaseType != null) {
4950 Expression member_lookup = Expression.MemberLookup (
4951 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4952 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4954 if (member_lookup != null){
4955 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
4957 ig.Emit (OpCodes.Ldarg_0);
4958 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
4962 ig.EndExceptionBlock ();
4963 //ig.MarkLabel (ec.ReturnLabel);
4964 ig.Emit (OpCodes.Ret);
4968 public class Destructor : Method {
4970 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
4971 Parameters parameters, Attributes attrs, Location l)
4972 : base (ds, null, return_type, mod, false, new MemberName (name),
4973 parameters, attrs, l)
4976 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4978 if (a.Type == TypeManager.conditional_attribute_type) {
4979 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4983 base.ApplyAttributeBuilder (a, cb);
4987 abstract public class MemberBase : MemberCore {
4988 public Expression Type;
4990 public MethodAttributes flags;
4992 protected readonly int explicit_mod_flags;
4995 // The "short" name of this property / indexer / event. This is the
4996 // name without the explicit interface.
4998 public string ShortName;
5001 // The type of this property / indexer / event
5003 public Type MemberType;
5006 // If true, this is an explicit interface implementation
5008 public bool IsExplicitImpl = false;
5011 // The name of the interface we are explicitly implementing
5013 public Expression ExplicitInterfaceName = null;
5016 // Whether this is an interface member.
5018 public bool IsInterface;
5021 // If true, the interface type we are explicitly implementing
5023 public Type InterfaceType = null;
5026 // The constructor is only exposed to our children
5028 protected MemberBase (TypeContainer parent, Expression type, int mod,
5029 int allowed_mod, int def_mod, MemberName name,
5030 Attributes attrs, Location loc)
5031 : base (parent, name, attrs, loc)
5033 explicit_mod_flags = mod;
5035 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5038 protected virtual bool CheckBase ()
5040 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5041 Report.Error (666, Location, "Protected member in struct declaration");
5045 if ((RootContext.WarningLevel >= 4) &&
5046 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5047 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5048 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5049 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5055 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5057 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5061 foreach (Type partype in parameters){
5062 if (partype == TypeManager.void_type) {
5064 1547, Location, "Keyword 'void' cannot " +
5065 "be used in this context");
5069 if (partype.IsPointer){
5072 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5076 if (ds.AsAccessible (partype, ModFlags))
5079 if (this is Indexer)
5080 Report.Error (55, Location,
5081 "Inconsistent accessibility: parameter type `" +
5082 TypeManager.CSharpName (partype) + "' is less " +
5083 "accessible than indexer `" + Name + "'");
5084 else if ((this is Method) && ((Method) this).IsOperator)
5085 Report.Error (57, Location,
5086 "Inconsistent accessibility: parameter type `" +
5087 TypeManager.CSharpName (partype) + "' is less " +
5088 "accessible than operator `" + Name + "'");
5090 Report.Error (51, Location,
5091 "Inconsistent accessibility: parameter type `" +
5092 TypeManager.CSharpName (partype) + "' is less " +
5093 "accessible than method `" + Name + "'");
5100 protected virtual bool DoDefineBase ()
5106 ModFlags = Modifiers.PUBLIC |
5107 Modifiers.ABSTRACT |
5108 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5110 flags = MethodAttributes.Public |
5111 MethodAttributes.Abstract |
5112 MethodAttributes.HideBySig |
5113 MethodAttributes.NewSlot |
5114 MethodAttributes.Virtual;
5116 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
5119 flags = Modifiers.MethodAttr (ModFlags);
5125 protected virtual bool DoDefine (DeclSpace decl)
5127 // Lookup Type, verify validity
5128 MemberType = decl.ResolveType (Type, false, Location);
5129 if (MemberType == null)
5132 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5133 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5134 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5139 // verify accessibility
5140 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5141 if (this is Property)
5142 Report.Error (53, Location,
5143 "Inconsistent accessibility: property type `" +
5144 TypeManager.CSharpName (MemberType) + "' is less " +
5145 "accessible than property `" + Name + "'");
5146 else if (this is Indexer)
5147 Report.Error (54, Location,
5148 "Inconsistent accessibility: indexer return type `" +
5149 TypeManager.CSharpName (MemberType) + "' is less " +
5150 "accessible than indexer `" + Name + "'");
5151 else if (this is Method) {
5152 if (((Method) this).IsOperator)
5153 Report.Error (56, Location,
5154 "Inconsistent accessibility: return type `" +
5155 TypeManager.CSharpName (MemberType) + "' is less " +
5156 "accessible than operator `" + Name + "'");
5158 Report.Error (50, Location,
5159 "Inconsistent accessibility: return type `" +
5160 TypeManager.CSharpName (MemberType) + "' is less " +
5161 "accessible than method `" + Name + "'");
5163 Report.Error (52, Location,
5164 "Inconsistent accessibility: field type `" +
5165 TypeManager.CSharpName (MemberType) + "' is less " +
5166 "accessible than field `" + Name + "'");
5170 if (MemberType.IsPointer && !UnsafeOK (Parent))
5174 // Check for explicit interface implementation
5176 if (MemberName.Left != null) {
5177 ExplicitInterfaceName = MemberName.Left.GetTypeExpression (Location);
5178 ShortName = MemberName.Name;
5182 if (ExplicitInterfaceName != null) {
5183 InterfaceType = Parent.ResolveType (
5184 ExplicitInterfaceName, false, Location);
5185 if (InterfaceType == null)
5188 if (InterfaceType.IsClass) {
5189 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
5193 // Compute the full name that we need to export.
5194 Name = InterfaceType.FullName + "." + ShortName;
5196 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5199 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5201 IsExplicitImpl = true;
5203 IsExplicitImpl = false;
5209 /// Use this method when MethodBuilder is null
5211 public virtual string GetSignatureForError (TypeContainer tc)
5213 return String.Concat (tc.Name, '.', Name);
5216 protected override bool VerifyClsCompliance(DeclSpace ds)
5218 if (base.VerifyClsCompliance (ds)) {
5222 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5223 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5228 protected override void VerifyObsoleteAttribute()
5230 CheckUsageOfObsoleteAttribute (MemberType);
5235 // Fields and Events both generate FieldBuilders, we use this to share
5236 // their common bits. This is also used to flag usage of the field
5238 abstract public class FieldBase : MemberBase {
5239 public FieldBuilder FieldBuilder;
5240 public Status status;
5243 public enum Status : byte { ASSIGNED = 1, USED = 2 }
5245 static string[] attribute_targets = new string [] { "field" };
5248 /// Symbol with same name in parent class/struct
5250 public MemberInfo conflict_symbol;
5253 // The constructor is only exposed to our children
5255 protected FieldBase (TypeContainer parent, Expression type, int mod,
5256 int allowed_mod, MemberName name, object init,
5257 Attributes attrs, Location loc)
5258 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5264 public override AttributeTargets AttributeTargets {
5266 return AttributeTargets.Field;
5270 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5272 if (a.Type == TypeManager.marshal_as_attr_type) {
5273 UnmanagedMarshal marshal = a.GetMarshal ();
5274 if (marshal != null) {
5275 FieldBuilder.SetMarshal (marshal);
5278 Report.Warning (-24, a.Location, "The Microsoft Runtime cannot set this marshal info. Please use the Mono runtime instead.");
5283 FieldBuilder.SetCustomAttribute (cb);
5287 // Whether this field has an initializer.
5289 public bool HasInitializer {
5291 return init != null;
5295 protected readonly Object init;
5297 Expression init_expr;
5298 bool init_expr_initialized = false;
5300 protected override bool CheckGenericOverride (MethodInfo method, string name)
5306 // Resolves and returns the field initializer.
5308 public Expression GetInitializerExpression (EmitContext ec)
5310 if (init_expr_initialized)
5314 if (init is Expression)
5315 e = (Expression) init;
5317 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5319 ec.IsFieldInitializer = true;
5320 e = e.DoResolve (ec);
5321 ec.IsFieldInitializer = false;
5324 init_expr_initialized = true;
5329 protected override bool CheckBase ()
5331 if (!base.CheckBase ())
5338 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5339 if (conflict_symbol == null) {
5340 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5341 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5346 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5347 Report.SymbolRelatedToPreviousError (conflict_symbol);
5348 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5354 protected override bool DoDefine (DeclSpace ds)
5356 if (!base.DoDefine (ds))
5359 if (MemberType == TypeManager.void_type) {
5360 Report.Error (1547, Location,
5361 "Keyword 'void' cannot be used in this context");
5365 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5366 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5373 public override string GetSignatureForError ()
5375 return TypeManager.GetFullNameSignature (FieldBuilder);
5378 public override string[] ValidAttributeTargets {
5380 return attribute_targets;
5384 protected override bool VerifyClsCompliance (DeclSpace ds)
5386 if (!base.VerifyClsCompliance (ds))
5389 if (FieldBuilder == null) {
5393 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5394 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5400 public void SetAssigned ()
5402 status |= Status.ASSIGNED;
5407 // The Field class is used to represents class/struct fields during parsing.
5409 public class Field : FieldBase {
5411 // Modifiers allowed in a class declaration
5413 const int AllowedModifiers =
5416 Modifiers.PROTECTED |
5417 Modifiers.INTERNAL |
5420 Modifiers.VOLATILE |
5424 public Field (TypeContainer parent, Expression type, int mod, string name,
5425 Object expr_or_array_init, Attributes attrs, Location loc)
5426 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5427 expr_or_array_init, attrs, loc)
5431 public override bool Define ()
5433 MemberType = Parent.ResolveType (Type, false, Location);
5435 if (MemberType == null)
5440 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5441 Report.Error (52, Location,
5442 "Inconsistent accessibility: field type `" +
5443 TypeManager.CSharpName (MemberType) + "' is less " +
5444 "accessible than field `" + Name + "'");
5448 if (MemberType.IsPointer && !UnsafeOK (Parent))
5451 if (RootContext.WarningLevel > 1){
5452 Type ptype = Parent.TypeBuilder.BaseType;
5454 // ptype is only null for System.Object while compiling corlib.
5456 TypeContainer.FindMembers (
5457 ptype, MemberTypes.Method,
5458 BindingFlags.Public |
5459 BindingFlags.Static | BindingFlags.Instance,
5460 System.Type.FilterName, Name);
5464 if ((ModFlags & Modifiers.VOLATILE) != 0){
5465 if (!MemberType.IsClass){
5466 Type vt = MemberType;
5468 if (TypeManager.IsEnumType (vt))
5469 vt = TypeManager.EnumToUnderlying (MemberType);
5471 if (!((vt == TypeManager.bool_type) ||
5472 (vt == TypeManager.sbyte_type) ||
5473 (vt == TypeManager.byte_type) ||
5474 (vt == TypeManager.short_type) ||
5475 (vt == TypeManager.ushort_type) ||
5476 (vt == TypeManager.int32_type) ||
5477 (vt == TypeManager.uint32_type) ||
5478 (vt == TypeManager.char_type) ||
5479 (vt == TypeManager.float_type) ||
5480 (!vt.IsValueType))){
5482 677, Location, Parent.MakeName (Name) +
5483 " A volatile field can not be of type `" +
5484 TypeManager.CSharpName (vt) + "'");
5489 if ((ModFlags & Modifiers.READONLY) != 0){
5492 "A field can not be both volatile and readonly");
5497 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5499 if (Parent.Kind == Kind.Struct &&
5500 ((fa & FieldAttributes.Static) == 0) &&
5501 MemberType == Parent.TypeBuilder &&
5502 !TypeManager.IsBuiltinType (MemberType)){
5503 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5504 "' causes a cycle in the structure layout");
5509 FieldBuilder = Parent.TypeBuilder.DefineField (
5510 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5512 TypeManager.RegisterFieldBase (FieldBuilder, this);
5514 catch (ArgumentException) {
5515 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5522 public override void Emit ()
5524 if (OptAttributes != null) {
5525 EmitContext ec = new EmitContext (
5526 Parent, Location, null, FieldBuilder.FieldType,
5528 OptAttributes.Emit (ec, this);
5536 // `set' and `get' accessors are represented with an Accessor.
5538 public class Accessor {
5540 // Null if the accessor is empty, or a Block if not
5543 public Attributes Attributes;
5545 public Accessor (Block b, Attributes attrs)
5553 // Ooouh Martin, templates are missing here.
5554 // When it will be possible move here a lot of child code and template method type.
5555 public abstract class AbstractPropertyEventMethod: Attributable, IMethodData
5557 protected MethodData method_data;
5558 protected Block block;
5560 ReturnParameter return_attributes;
5562 public AbstractPropertyEventMethod ():
5567 public AbstractPropertyEventMethod (Accessor accessor):
5568 base (accessor.Attributes)
5570 this.block = accessor.Block;
5573 #region IMethodData Members
5575 public Block Block {
5585 public CallingConventions CallingConventions {
5587 return CallingConventions.Standard;
5591 public bool IsExcluded (EmitContext ec)
5596 GenericMethod IMethodData.GenericMethod {
5602 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5603 public abstract string GetSignatureForError (TypeContainer tc);
5604 public abstract Location Location { get; }
5605 public abstract string MethodName { get; }
5606 public abstract Type[] ParameterTypes { get; }
5607 public abstract Type ReturnType { get; }
5608 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5612 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5614 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5615 a.Type == TypeManager.conditional_attribute_type) {
5616 Report.Error (1667, a.Location, "'{0}' is not valid on property or event accessors. It is valid on '{1}' declarations only", TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5620 if (a.Target == AttributeTargets.Method) {
5621 method_data.MethodBuilder.SetCustomAttribute (cb);
5625 if (a.Target == AttributeTargets.ReturnValue) {
5626 if (return_attributes == null)
5627 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5629 return_attributes.ApplyAttributeBuilder (a, cb);
5633 ApplyToExtraTarget (a, cb);
5636 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5638 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5641 public virtual void Emit (TypeContainer container)
5643 method_data.Emit (container, this);
5649 // Properties and Indexers both generate PropertyBuilders, we use this to share
5650 // their common bits.
5652 abstract public class PropertyBase : MethodCore {
5654 public class GetMethod: PropertyMethod
5656 static string[] attribute_targets = new string [] { "method", "return" };
5658 public GetMethod (MethodCore method, Accessor accessor):
5659 base (method, accessor)
5663 public override MethodBuilder Define(TypeContainer container)
5665 method_data = new MethodData (method, method.ParameterInfo, method.ModFlags, method.flags, this);
5667 if (!method_data.Define (container))
5670 return method_data.MethodBuilder;
5673 public override string GetSignatureForError (TypeContainer tc)
5675 return String.Concat (base.GetSignatureForError (tc), ".get");
5678 public override string MethodName
5681 return "get_" + method.ShortName;
5685 public override Type ReturnType {
5687 return method.MemberType;
5691 public override string[] ValidAttributeTargets {
5693 return attribute_targets;
5698 public class SetMethod: PropertyMethod {
5700 static string[] attribute_targets = new string [] { "method", "param", "return" };
5701 ImplicitParameter param_attr;
5703 public SetMethod (MethodCore method, Accessor accessor):
5704 base (method, accessor)
5708 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5710 if (a.Target == AttributeTargets.Parameter) {
5711 if (param_attr == null)
5712 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5714 param_attr.ApplyAttributeBuilder (a, cb);
5718 base.ApplyAttributeBuilder (a, cb);
5721 protected virtual InternalParameters GetParameterInfo (TypeContainer container)
5723 Parameter [] parms = new Parameter [1];
5724 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5725 return new InternalParameters (
5726 container, new Parameters (parms, null, method.Location));
5729 public override MethodBuilder Define(TypeContainer container)
5731 method_data = new MethodData (method, GetParameterInfo (container), method.ModFlags, method.flags, this);
5733 if (!method_data.Define (container))
5736 return method_data.MethodBuilder;
5739 public override string GetSignatureForError (TypeContainer tc)
5741 return String.Concat (base.GetSignatureForError (tc), ".set");
5744 public override string MethodName {
5746 return "set_" + method.ShortName;
5750 public override Type[] ParameterTypes {
5752 return new Type[] { method.MemberType };
5756 public override Type ReturnType {
5758 return TypeManager.void_type;
5762 public override string[] ValidAttributeTargets {
5764 return attribute_targets;
5769 static string[] attribute_targets = new string [] { "property" };
5771 public abstract class PropertyMethod: AbstractPropertyEventMethod {
5772 protected readonly MethodCore method;
5774 public PropertyMethod (MethodCore method, Accessor accessor):
5777 this.method = method;
5780 public override AttributeTargets AttributeTargets {
5782 return AttributeTargets.Method;
5786 public override bool IsClsCompliaceRequired(DeclSpace ds)
5788 return method.IsClsCompliaceRequired (ds);
5791 public InternalParameters ParameterInfo
5794 return method_data.ParameterInfo;
5798 public abstract MethodBuilder Define (TypeContainer container);
5800 public override Type[] ParameterTypes {
5802 return TypeManager.NoTypes;
5806 public override Location Location {
5808 return method.Location;
5812 public override EmitContext CreateEmitContext (TypeContainer tc,
5815 return new EmitContext (
5816 tc, method.ds, method.Location, ig, ReturnType,
5817 method.ModFlags, false);
5820 public override ObsoleteAttribute GetObsoleteAttribute ()
5822 return method.GetObsoleteAttribute (method.ds);
5825 public override string GetSignatureForError (TypeContainer tc)
5827 return String.Concat (tc.Name, '.', method.Name);
5831 public PropertyMethod Get, Set;
5832 public PropertyBuilder PropertyBuilder;
5833 public MethodBuilder GetBuilder, SetBuilder;
5835 protected EmitContext ec;
5837 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
5838 int allowed_mod, bool is_iface, MemberName name,
5839 Parameters parameters, Attributes attrs,
5841 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
5842 attrs, parameters, loc)
5846 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5848 PropertyBuilder.SetCustomAttribute (cb);
5851 public override AttributeTargets AttributeTargets {
5853 return AttributeTargets.Property;
5857 protected override bool DoDefine (DeclSpace decl)
5859 if (!base.DoDefine (decl))
5862 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5863 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5867 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5872 public override string GetSignatureForError()
5874 return TypeManager.CSharpSignature (PropertyBuilder, false);
5878 protected override bool CheckForDuplications ()
5880 ArrayList ar = Parent.Properties;
5882 int arLen = ar.Count;
5884 for (int i = 0; i < arLen; i++) {
5885 Property m = (Property) ar [i];
5886 if (IsDuplicateImplementation (m))
5893 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
5895 PropertyInfo parent_property = container.ParentContainer.MemberCache.FindMemberToOverride (
5896 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5898 if (parent_property == null)
5901 parent_ret_type = parent_property.PropertyType;
5904 temp_m = parent_property.GetGetMethod (true);
5908 System.Diagnostics.Debug.Assert (parent_property.GetSetMethod (true) != null, "Internal error property without get/set");
5909 return parent_property.GetSetMethod (true);
5912 public override void Emit ()
5915 // The PropertyBuilder can be null for explicit implementations, in that
5916 // case, we do not actually emit the ".property", so there is nowhere to
5917 // put the attribute
5919 if (PropertyBuilder != null && OptAttributes != null)
5920 OptAttributes.Emit (ec, this);
5931 public override string[] ValidAttributeTargets {
5933 return attribute_targets;
5938 public class Property : PropertyBase, IIteratorContainer {
5939 const int AllowedModifiers =
5942 Modifiers.PROTECTED |
5943 Modifiers.INTERNAL |
5947 Modifiers.OVERRIDE |
5948 Modifiers.ABSTRACT |
5951 Modifiers.METHOD_YIELDS |
5954 const int AllowedInterfaceModifiers =
5957 public Property (TypeContainer parent, Expression type, int mod_flags,
5958 bool is_iface, MemberName name, Attributes attrs,
5959 Accessor get_block, Accessor set_block, Location loc)
5960 : base (parent, type, mod_flags,
5961 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
5962 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
5965 if (get_block != null)
5966 Get = new GetMethod (this, get_block);
5968 if (set_block != null)
5969 Set = new SetMethod (this, set_block);
5972 public override bool Define ()
5974 if (!DoDefineBase ())
5977 if (!DoDefine (Parent))
5983 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
5987 GetBuilder = Get.Define (Parent);
5988 if (GetBuilder == null)
5992 // Setup iterator if we are one
5994 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
5995 Iterator iterator = new Iterator (
5996 Parent, "get", MemberType,
5997 TypeManager.NoTypes, Get.ParameterInfo,
5998 ModFlags, Get.Block, Location);
6000 if (!iterator.DefineIterator ())
6002 Get.Block = iterator.Block;
6007 SetBuilder = Set.Define (Parent);
6008 if (SetBuilder == null)
6011 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6014 // FIXME - PropertyAttributes.HasDefault ?
6016 PropertyAttributes prop_attr = PropertyAttributes.None;
6018 prop_attr |= PropertyAttributes.RTSpecialName |
6019 PropertyAttributes.SpecialName;
6021 if (!IsExplicitImpl){
6022 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6023 Name, prop_attr, MemberType, null);
6026 PropertyBuilder.SetGetMethod (GetBuilder);
6029 PropertyBuilder.SetSetMethod (SetBuilder);
6032 // HACK for the reasons exposed above
6034 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
6037 "Class `" + Parent.Name +
6038 "' already contains a definition for the property `" +
6046 public void SetYields ()
6048 ModFlags |= Modifiers.METHOD_YIELDS;
6053 /// Gigantic workaround for lameness in SRE follows :
6054 /// This class derives from EventInfo and attempts to basically
6055 /// wrap around the EventBuilder so that FindMembers can quickly
6056 /// return this in it search for members
6058 public class MyEventBuilder : EventInfo {
6061 // We use this to "point" to our Builder which is
6062 // not really a MemberInfo
6064 EventBuilder MyBuilder;
6067 // We "catch" and wrap these methods
6069 MethodInfo raise, remove, add;
6071 EventAttributes attributes;
6072 Type declaring_type, reflected_type, event_type;
6077 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6079 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6081 // And now store the values in our own fields.
6083 declaring_type = type_builder;
6085 reflected_type = type_builder;
6087 attributes = event_attr;
6090 this.event_type = event_type;
6094 // Methods that you have to override. Note that you only need
6095 // to "implement" the variants that take the argument (those are
6096 // the "abstract" methods, the others (GetAddMethod()) are
6099 public override MethodInfo GetAddMethod (bool nonPublic)
6104 public override MethodInfo GetRemoveMethod (bool nonPublic)
6109 public override MethodInfo GetRaiseMethod (bool nonPublic)
6115 // These methods make "MyEventInfo" look like a Builder
6117 public void SetRaiseMethod (MethodBuilder raiseMethod)
6119 raise = raiseMethod;
6120 MyBuilder.SetRaiseMethod (raiseMethod);
6123 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6125 remove = removeMethod;
6126 MyBuilder.SetRemoveOnMethod (removeMethod);
6129 public void SetAddOnMethod (MethodBuilder addMethod)
6132 MyBuilder.SetAddOnMethod (addMethod);
6135 public void SetCustomAttribute (CustomAttributeBuilder cb)
6137 MyBuilder.SetCustomAttribute (cb);
6140 public override object [] GetCustomAttributes (bool inherit)
6142 // FIXME : There's nothing which can be seemingly done here because
6143 // we have no way of getting at the custom attribute objects of the
6148 public override object [] GetCustomAttributes (Type t, bool inherit)
6150 // FIXME : Same here !
6154 public override bool IsDefined (Type t, bool b)
6159 public override EventAttributes Attributes {
6165 public override string Name {
6171 public override Type DeclaringType {
6173 return declaring_type;
6177 public override Type ReflectedType {
6179 return reflected_type;
6183 public Type EventType {
6189 public void SetUsed ()
6191 if (my_event != null)
6192 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6197 /// For case when event is declared like property (with add and remove accessors).
6199 public class EventProperty: Event {
6201 static string[] attribute_targets = new string [] { "event", "property" };
6203 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6204 bool is_iface, MemberName name, Object init,
6205 Attributes attrs, Accessor add, Accessor remove,
6207 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6209 Add = new AddDelegateMethod (this, add);
6210 Remove = new RemoveDelegateMethod (this, remove);
6213 public override string[] ValidAttributeTargets {
6215 return attribute_targets;
6221 /// Event is declared like field.
6223 public class EventField: Event {
6225 static string[] attribute_targets = new string [] { "event", "field", "method" };
6227 public EventField (TypeContainer parent, Expression type, int mod_flags,
6228 bool is_iface, MemberName name, Object init,
6229 Attributes attrs, Location loc)
6230 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6232 Add = new AddDelegateMethod (this);
6233 Remove = new RemoveDelegateMethod (this);
6236 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6238 if (a.Target == AttributeTargets.Field) {
6239 FieldBuilder.SetCustomAttribute (cb);
6243 if (a.Target == AttributeTargets.Method) {
6244 AddBuilder.SetCustomAttribute (cb);
6245 RemoveBuilder.SetCustomAttribute (cb);
6249 base.ApplyAttributeBuilder (a, cb);
6252 public override string[] ValidAttributeTargets {
6254 return attribute_targets;
6259 public abstract class Event : FieldBase {
6261 protected sealed class AddDelegateMethod: DelegateMethod
6263 public AddDelegateMethod (Event method):
6268 public AddDelegateMethod (Event method, Accessor accessor):
6269 base (method, accessor)
6273 public override string MethodName {
6275 return "add_" + method.ShortName;
6279 protected override MethodInfo DelegateMethodInfo {
6281 return TypeManager.delegate_combine_delegate_delegate;
6287 protected sealed class RemoveDelegateMethod: DelegateMethod
6289 public RemoveDelegateMethod (Event method):
6294 public RemoveDelegateMethod (Event method, Accessor accessor):
6295 base (method, accessor)
6299 public override string MethodName {
6301 return "remove_" + method.ShortName;
6305 protected override MethodInfo DelegateMethodInfo {
6307 return TypeManager.delegate_remove_delegate_delegate;
6313 public abstract class DelegateMethod: AbstractPropertyEventMethod
6315 protected readonly Event method;
6316 ImplicitParameter param_attr;
6318 static string[] attribute_targets = new string [] { "method", "param", "return" };
6320 public DelegateMethod (Event method)
6322 this.method = method;
6325 public DelegateMethod (Event method, Accessor accessor):
6328 this.method = method;
6331 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6333 if (a.Target == AttributeTargets.Parameter) {
6334 if (param_attr == null)
6335 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6337 param_attr.ApplyAttributeBuilder (a, cb);
6341 base.ApplyAttributeBuilder (a, cb);
6344 public override AttributeTargets AttributeTargets {
6346 return AttributeTargets.Method;
6350 public override bool IsClsCompliaceRequired(DeclSpace ds)
6352 return method.IsClsCompliaceRequired (ds);
6355 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6357 method_data = new MethodData (method, ip, method.ModFlags,
6358 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6360 if (!method_data.Define (container))
6363 MethodBuilder mb = method_data.MethodBuilder;
6364 mb.DefineParameter (1, ParameterAttributes.None, "value");
6369 public override void Emit (TypeContainer tc)
6371 if (block != null) {
6376 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6377 EmitContext ec = CreateEmitContext (tc, ig);
6378 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6380 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6381 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6382 ig.Emit (OpCodes.Ldsfld, field_info);
6383 ig.Emit (OpCodes.Ldarg_0);
6384 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6385 ig.Emit (OpCodes.Castclass, method.MemberType);
6386 ig.Emit (OpCodes.Stsfld, field_info);
6388 ig.Emit (OpCodes.Ldarg_0);
6389 ig.Emit (OpCodes.Ldarg_0);
6390 ig.Emit (OpCodes.Ldfld, field_info);
6391 ig.Emit (OpCodes.Ldarg_1);
6392 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6393 ig.Emit (OpCodes.Castclass, method.MemberType);
6394 ig.Emit (OpCodes.Stfld, field_info);
6396 ig.Emit (OpCodes.Ret);
6399 protected abstract MethodInfo DelegateMethodInfo { get; }
6401 public override Type[] ParameterTypes {
6403 return new Type[] { method.MemberType };
6407 public override Type ReturnType {
6409 return TypeManager.void_type;
6413 public override Location Location {
6415 return method.Location;
6419 public override EmitContext CreateEmitContext (TypeContainer tc,
6422 return new EmitContext (
6423 tc, method.Parent, Location, ig, ReturnType,
6424 method.ModFlags, false);
6427 public override string GetSignatureForError (TypeContainer tc)
6429 return String.Concat (tc.Name, '.', method.Name);
6432 public override ObsoleteAttribute GetObsoleteAttribute ()
6434 return method.GetObsoleteAttribute (method.Parent);
6437 public override string[] ValidAttributeTargets {
6439 return attribute_targets;
6445 const int AllowedModifiers =
6448 Modifiers.PROTECTED |
6449 Modifiers.INTERNAL |
6454 Modifiers.OVERRIDE |
6458 const int AllowedInterfaceModifiers =
6461 protected DelegateMethod Add, Remove;
6462 public MyEventBuilder EventBuilder;
6463 public MethodBuilder AddBuilder, RemoveBuilder;
6465 MethodData AddData, RemoveData;
6467 public Event (TypeContainer parent, Expression type, int mod_flags,
6468 bool is_iface, MemberName name, Object init, Attributes attrs,
6470 : base (parent, type, mod_flags,
6471 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6472 name, init, attrs, loc)
6474 IsInterface = is_iface;
6477 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6479 EventBuilder.SetCustomAttribute (cb);
6482 public override AttributeTargets AttributeTargets {
6484 return AttributeTargets.Event;
6488 public override bool Define ()
6490 EventAttributes e_attr;
6491 e_attr = EventAttributes.None;
6493 if (!DoDefineBase ())
6496 if (!DoDefine (Parent))
6499 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6500 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6501 "': abstract event can not have an initializer");
6505 if (!TypeManager.IsDelegateType (MemberType)) {
6506 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6507 "' : event must be of a delegate type");
6511 Parameter [] parms = new Parameter [1];
6512 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6513 InternalParameters ip = new InternalParameters (
6514 Parent, new Parameters (parms, null, Location));
6520 // Now define the accessors
6523 AddBuilder = Add.Define (Parent, ip);
6524 if (AddBuilder == null)
6527 RemoveBuilder = Remove.Define (Parent, ip);
6528 if (RemoveBuilder == null)
6531 if (!IsExplicitImpl){
6532 EventBuilder = new MyEventBuilder (this,
6533 Parent.TypeBuilder, Name, e_attr, MemberType);
6535 if (Add.Block == null && Remove.Block == null &&
6537 FieldBuilder = Parent.TypeBuilder.DefineField (
6539 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6540 TypeManager.RegisterPrivateFieldOfEvent (
6541 (EventInfo) EventBuilder, FieldBuilder);
6542 TypeManager.RegisterFieldBase (FieldBuilder, this);
6545 EventBuilder.SetAddOnMethod (AddBuilder);
6546 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6548 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
6549 Report.Error (111, Location,
6550 "Class `" + Parent.Name +
6551 "' already contains a definition for the event `" +
6560 protected override bool CheckBase ()
6562 if (!base.CheckBase ())
6565 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6566 if (!(conflict_symbol is EventInfo)) {
6567 Report.SymbolRelatedToPreviousError (conflict_symbol);
6568 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6576 public override void Emit ()
6578 if (OptAttributes != null) {
6579 EmitContext ec = new EmitContext (
6580 Parent, Location, null, MemberType, ModFlags);
6581 OptAttributes.Emit (ec, this);
6586 Remove.Emit (Parent);
6592 public override string GetSignatureForError ()
6594 return TypeManager.GetFullNameSignature (EventBuilder);
6599 // FIXME: This does not handle:
6601 // int INTERFACENAME [ args ]
6606 // int this [ args ]
6608 public class Indexer : PropertyBase {
6610 class GetIndexerMethod: GetMethod
6612 public GetIndexerMethod (MethodCore method, Accessor accessor):
6613 base (method, accessor)
6617 public override Type[] ParameterTypes {
6619 return method.ParameterTypes;
6624 class SetIndexerMethod: SetMethod
6626 readonly Parameters parameters;
6628 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6629 base (method, accessor)
6631 this.parameters = parameters;
6634 public override Type[] ParameterTypes {
6636 int top = method.ParameterTypes.Length;
6637 Type [] set_pars = new Type [top + 1];
6638 method.ParameterTypes.CopyTo (set_pars, 0);
6639 set_pars [top] = method.MemberType;
6644 protected override InternalParameters GetParameterInfo (TypeContainer container)
6646 Parameter [] fixed_parms = parameters.FixedParameters;
6648 if (fixed_parms == null){
6649 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6650 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6651 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6653 // Here is the problem: the `value' parameter has
6654 // to come *after* the array parameter in the declaration
6656 // X (object [] x, Type value)
6659 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6660 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6664 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6666 fixed_parms.CopyTo (tmp, 0);
6667 tmp [fixed_parms.Length] = new Parameter (
6668 method.Type, "value", Parameter.Modifier.NONE, null);
6670 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6672 return new InternalParameters (container, set_formal_params);
6678 const int AllowedModifiers =
6681 Modifiers.PROTECTED |
6682 Modifiers.INTERNAL |
6686 Modifiers.OVERRIDE |
6691 const int AllowedInterfaceModifiers =
6694 public string IndexerName = TypeContainer.DefaultIndexerName;
6695 public string InterfaceIndexerName;
6698 // Are we implementing an interface ?
6700 public Indexer (TypeContainer parent, Expression type, int mod_flags,
6701 bool is_iface, MemberName name, Parameters parameters,
6702 Attributes attrs, Accessor get_block, Accessor set_block,
6704 : base (parent, type, mod_flags,
6705 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6706 is_iface, name, parameters, attrs, loc)
6708 if (get_block != null)
6709 Get = new GetIndexerMethod (this, get_block);
6711 if (set_block != null)
6712 Set = new SetIndexerMethod (this, parameters, set_block);
6715 public override bool Define ()
6717 PropertyAttributes prop_attr =
6718 PropertyAttributes.RTSpecialName |
6719 PropertyAttributes.SpecialName;
6721 if (!DoDefineBase ())
6724 if (!DoDefine (Parent))
6727 if (OptAttributes != null) {
6728 Attribute indexer_attr = OptAttributes.GetIndexerNameAttribute (ec);
6729 if (indexer_attr != null) {
6730 IndexerName = indexer_attr.GetIndexerAttributeValue (ec);
6731 if (IsExplicitImpl) {
6732 // The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration
6733 Report.Error (415, indexer_attr.Location, "The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration");
6737 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6738 Report.Error (609, indexer_attr.Location, "Cannot set the 'IndexerName' attribute on an indexer marked override");
6742 if (!Tokenizer.IsValidIdentifier (IndexerName)) {
6743 // The argument to the 'IndexerName' attribute must be a valid identifier
6744 Report.Error (633, indexer_attr.Location, "The argument to the 'IndexerName' attribute must be a valid identifier");
6750 ShortName = IndexerName;
6751 if (IsExplicitImpl) {
6752 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6753 Name = InterfaceType.FullName + "." + IndexerName;
6755 InterfaceIndexerName = IndexerName;
6759 if (!CheckNameCollision (Parent))
6765 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6767 GetBuilder = Get.Define (Parent);
6768 if (GetBuilder == null)
6773 SetBuilder = Set.Define (Parent);
6774 if (SetBuilder == null)
6779 // Now name the parameters
6781 Parameter [] p = Parameters.FixedParameters;
6785 for (i = 0; i < p.Length; ++i) {
6787 GetBuilder.DefineParameter (
6788 i + 1, p [i].Attributes, p [i].Name);
6791 SetBuilder.DefineParameter (
6792 i + 1, p [i].Attributes, p [i].Name);
6796 SetBuilder.DefineParameter (
6797 i + 1, ParameterAttributes.None, "value");
6799 if (i != ParameterTypes.Length) {
6800 Parameter array_param = Parameters.ArrayParameter;
6802 SetBuilder.DefineParameter (
6803 i + 1, array_param.Attributes, array_param.Name);
6808 // Define the PropertyBuilder if one of the following conditions are met:
6809 // a) we're not implementing an interface indexer.
6810 // b) the indexer has a different IndexerName and this is no
6811 // explicit interface implementation.
6813 if (!IsExplicitImpl) {
6814 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6815 IndexerName, prop_attr, MemberType, ParameterTypes);
6818 PropertyBuilder.SetGetMethod (GetBuilder);
6821 PropertyBuilder.SetSetMethod (SetBuilder);
6823 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
6830 bool CheckNameCollision (TypeContainer container) {
6831 switch (VerifyName (container)){
6832 case DeclSpace.AdditionResult.NameExists:
6833 Report.Error (102, Location, "The container '{0}' already contains a definition for '{1}'", container.GetSignatureForError (), Name);
6836 case DeclSpace.AdditionResult.Success:
6839 throw new NotImplementedException ();
6842 DeclSpace.AdditionResult VerifyName (TypeContainer container) {
6843 if (!AddIndexer (container, container.Name + "." + Name))
6844 return DeclSpace.AdditionResult.NameExists;
6847 if (!AddIndexer (container, container.Name + ".get_" + Name))
6848 return DeclSpace.AdditionResult.NameExists;
6852 if (!AddIndexer (container, container.Name + ".set_" + Name))
6853 return DeclSpace.AdditionResult.NameExists;
6855 return DeclSpace.AdditionResult.Success;
6858 bool AddIndexer (TypeContainer container, string fullname)
6860 object value = container.GetDefinition (fullname);
6862 if (value != null) {
6863 return value.GetType () != GetType () ? false : true;
6866 container.DefineName (fullname, this);
6870 public override string GetSignatureForError ()
6872 return TypeManager.CSharpSignature (PropertyBuilder, true);
6875 public override string GetSignatureForError(TypeContainer tc)
6877 return String.Concat (tc.Name, ".this[", TypeManager.CSharpName (ParameterTypes [0]), ']');
6881 public class Operator : MemberBase, IIteratorContainer {
6883 const int AllowedModifiers =
6889 const int RequiredModifiers =
6893 public enum OpType : byte {
6903 // Unary and Binary operators
6926 // Implicit and Explicit
6931 public readonly OpType OperatorType;
6932 public readonly Expression ReturnType;
6933 public readonly Expression FirstArgType, SecondArgType;
6934 public readonly string FirstArgName, SecondArgName;
6936 public MethodBuilder OperatorMethodBuilder;
6938 public string MethodName;
6939 public Method OperatorMethod;
6941 static string[] attribute_targets = new string [] { "method", "return" };
6943 public Operator (TypeContainer parent, OpType type, Expression ret_type,
6944 int mod_flags, Expression arg1type, string arg1name,
6945 Expression arg2type, string arg2name,
6946 Block block, Attributes attrs, Location loc)
6947 : base (parent, ret_type, mod_flags, AllowedModifiers,
6948 Modifiers.PUBLIC, MemberName.Null, attrs, loc)
6950 OperatorType = type;
6951 Name = "op_" + OperatorType;
6952 ReturnType = ret_type;
6953 FirstArgType = arg1type;
6954 FirstArgName = arg1name;
6955 SecondArgType = arg2type;
6956 SecondArgName = arg2name;
6960 string Prototype (TypeContainer container)
6962 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
6963 SecondArgType + ")";
6966 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6968 OperatorMethod.ApplyAttributeBuilder (a, cb);
6971 public override AttributeTargets AttributeTargets {
6973 return AttributeTargets.Method;
6977 protected override bool CheckGenericOverride (MethodInfo method, string name)
6982 public override bool Define ()
6985 MethodName = "op_" + OperatorType;
6987 if (SecondArgType != null)
6990 Parameter [] param_list = new Parameter [length];
6992 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
6995 "User defined operators `" +
6996 Prototype (Parent) +
6997 "' must be declared static and public");
7001 param_list[0] = new Parameter (FirstArgType, FirstArgName,
7002 Parameter.Modifier.NONE, null);
7003 if (SecondArgType != null)
7004 param_list[1] = new Parameter (SecondArgType, SecondArgName,
7005 Parameter.Modifier.NONE, null);
7007 OperatorMethod = new Method (
7008 Parent, null, ReturnType, ModFlags, false,
7009 new MemberName (MethodName),
7010 new Parameters (param_list, null, Location),
7011 OptAttributes, Location);
7013 OperatorMethod.Block = Block;
7014 OperatorMethod.IsOperator = true;
7015 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7016 OperatorMethod.Define ();
7018 if (OperatorMethod.MethodBuilder == null)
7021 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7023 Type [] param_types = OperatorMethod.ParameterTypes;
7024 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7025 Type return_type = OperatorMethod.GetReturnType ();
7026 Type first_arg_type = param_types [0];
7028 // Rules for conversion operators
7030 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7031 if (first_arg_type == return_type && first_arg_type == declaring_type){
7034 "User-defined conversion cannot take an object of the " +
7035 "enclosing type and convert to an object of the enclosing" +
7040 if (first_arg_type != declaring_type && return_type != declaring_type){
7043 "User-defined conversion must convert to or from the " +
7048 if (first_arg_type == TypeManager.object_type ||
7049 return_type == TypeManager.object_type){
7052 "User-defined conversion cannot convert to or from " +
7057 if (first_arg_type.IsInterface || return_type.IsInterface){
7060 "User-defined conversion cannot convert to or from an " +
7065 if (first_arg_type.IsSubclassOf (return_type)
7066 || return_type.IsSubclassOf (first_arg_type)){
7067 if (declaring_type.IsSubclassOf (return_type)) {
7068 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7071 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7074 } else if (SecondArgType == null) {
7075 // Checks for Unary operators
7077 if (first_arg_type != declaring_type){
7080 "The parameter of a unary operator must be the " +
7085 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7086 if (return_type != declaring_type){
7089 "The parameter and return type for ++ and -- " +
7090 "must be the containing type");
7096 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7097 if (return_type != TypeManager.bool_type){
7100 "The return type of operator True or False " +
7107 // Checks for Binary operators
7109 if (first_arg_type != declaring_type &&
7110 param_types [1] != declaring_type){
7113 "One of the parameters of a binary operator must " +
7114 "be the containing type");
7122 public override void Emit ()
7125 // abstract or extern methods have no bodies
7127 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7130 OperatorMethod.Emit ();
7134 public static string GetName (OpType ot)
7137 case OpType.LogicalNot:
7139 case OpType.OnesComplement:
7141 case OpType.Increment:
7143 case OpType.Decrement:
7149 case OpType.Addition:
7151 case OpType.Subtraction:
7153 case OpType.UnaryPlus:
7155 case OpType.UnaryNegation:
7157 case OpType.Multiply:
7159 case OpType.Division:
7161 case OpType.Modulus:
7163 case OpType.BitwiseAnd:
7165 case OpType.BitwiseOr:
7167 case OpType.ExclusiveOr:
7169 case OpType.LeftShift:
7171 case OpType.RightShift:
7173 case OpType.Equality:
7175 case OpType.Inequality:
7177 case OpType.GreaterThan:
7179 case OpType.LessThan:
7181 case OpType.GreaterThanOrEqual:
7183 case OpType.LessThanOrEqual:
7185 case OpType.Implicit:
7187 case OpType.Explicit:
7193 public override string GetSignatureForError(TypeContainer tc)
7198 public override string GetSignatureForError()
7203 public override string ToString ()
7205 Type return_type = OperatorMethod.GetReturnType();
7206 Type [] param_types = OperatorMethod.ParameterTypes;
7208 if (SecondArgType == null)
7209 return String.Format (
7210 "{0} operator {1}({2})",
7211 TypeManager.CSharpName (return_type),
7212 GetName (OperatorType),
7215 return String.Format (
7216 "{0} operator {1}({2}, {3})",
7217 TypeManager.CSharpName (return_type),
7218 GetName (OperatorType),
7219 param_types [0], param_types [1]);
7222 public override string[] ValidAttributeTargets {
7224 return attribute_targets;
7228 public void SetYields ()
7230 ModFlags |= Modifiers.METHOD_YIELDS;
7235 // This is used to compare method signatures
7237 struct MethodSignature {
7239 public Type RetType;
7240 public Type [] Parameters;
7243 /// This delegate is used to extract methods which have the
7244 /// same signature as the argument
7246 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7248 public MethodSignature (string name, Type ret_type, Type [] parameters)
7253 if (parameters == null)
7254 Parameters = TypeManager.NoTypes;
7256 Parameters = parameters;
7259 public override string ToString ()
7262 if (Parameters.Length != 0){
7263 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7264 for (int i = 0; i < Parameters.Length; i++){
7265 sb.Append (Parameters [i]);
7266 if (i+1 < Parameters.Length)
7269 pars = sb.ToString ();
7272 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7275 public override int GetHashCode ()
7277 return Name.GetHashCode ();
7280 public override bool Equals (Object o)
7282 MethodSignature other = (MethodSignature) o;
7284 if (other.Name != Name)
7287 if (other.RetType != RetType)
7290 if (Parameters == null){
7291 if (other.Parameters == null)
7296 if (other.Parameters == null)
7299 int c = Parameters.Length;
7300 if (other.Parameters.Length != c)
7303 for (int i = 0; i < c; i++)
7304 if (other.Parameters [i] != Parameters [i])
7310 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7312 MethodSignature sig = (MethodSignature) filter_criteria;
7314 if (m.Name != sig.Name)
7318 MethodInfo mi = m as MethodInfo;
7319 PropertyInfo pi = m as PropertyInfo;
7322 ReturnType = mi.ReturnType;
7323 else if (pi != null)
7324 ReturnType = pi.PropertyType;
7329 // we use sig.RetType == null to mean `do not check the
7330 // method return value.
7332 if (sig.RetType != null)
7333 if (ReturnType != sig.RetType)
7338 args = TypeManager.GetArgumentTypes (mi);
7340 args = TypeManager.GetArgumentTypes (pi);
7341 Type [] sigp = sig.Parameters;
7343 if (args.Length != sigp.Length)
7346 for (int i = args.Length; i > 0; ){
7348 if (args [i] != sigp [i])