Revert my patch to constants, they broke corlib and System
[mono.git] / mcs / mcs / pending.cs
1 //
2 // pending.cs: Pending method implementation
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@gnu.org)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
10 //
11 //
12
13 using System;
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
17
18 namespace Mono.CSharp {
19
20         struct TypeAndMethods {
21                 public Type          type;
22                 public MethodInfo [] methods;
23
24                 // 
25                 // Whether it is optional, this is used to allow the explicit/implicit
26                 // implementation when a parent class already implements an interface. 
27                 //
28                 // For example:
29                 //
30                 // class X : IA { }  class Y : X, IA { IA.Explicit (); }
31                 //
32                 public bool          optional;
33                 
34                 // Far from ideal, but we want to avoid creating a copy
35                 // of methods above.
36                 public Type [][]     args;
37
38                 //
39                 // This flag on the method says `We found a match, but
40                 // because it was private, we could not use the match
41                 //
42                 public bool []       found;
43
44                 // If a method is defined here, then we always need to
45                 // create a proxy for it.  This is used when implementing
46                 // an interface's indexer with a different IndexerName.
47                 public MethodInfo [] need_proxy;
48
49                 //
50                 // The name of the indexer (if it exists), precompute set/get, because
51                 // they would be recomputed many times inside a loop later on.
52                 //
53                 public string set_indexer_name;
54                 public string get_indexer_name;
55         }
56
57         public class PendingImplementation {
58                 /// <summary>
59                 ///   The container for this PendingImplementation
60                 /// </summary>
61                 TypeContainer container;
62                 
63                 /// <summary>
64                 ///   This filter is used by FindMembers, and it is used to
65                 ///   extract only virtual/abstract fields
66                 /// </summary>
67                 static MemberFilter virtual_method_filter;
68
69                 /// <summary>
70                 ///   This is the array of TypeAndMethods that describes the pending implementations
71                 ///   (both interfaces and abstract methods in parent class)
72                 /// </summary>
73                 TypeAndMethods [] pending_implementations;
74
75                 static bool IsVirtualFilter (MemberInfo m, object filterCriteria)
76                 {
77                         MethodInfo mi = m as MethodInfo;
78                         return (mi == null) ? false : mi.IsVirtual;
79                 }
80
81                 /// <summary>
82                 ///   Inits the virtual_method_filter
83                 /// </summary>
84                 static PendingImplementation ()
85                 {
86                         virtual_method_filter = new MemberFilter (IsVirtualFilter);
87                 }
88
89                 // <remarks>
90                 //   Returns a list of the abstract methods that are exposed by all of our
91                 //   parents that we must implement.  Notice that this `flattens' the
92                 //   method search space, and takes into account overrides.  
93                 // </remarks>
94                 static ArrayList GetAbstractMethods (Type t)
95                 {
96                         ArrayList list = null;
97                         bool searching = true;
98                         Type current_type = t;
99                         
100                         do {
101                                 MemberList mi;
102                                 
103                                 mi = TypeContainer.FindMembers (
104                                         current_type, MemberTypes.Method,
105                                         BindingFlags.Public | BindingFlags.Instance |
106                                         BindingFlags.DeclaredOnly,
107                                         virtual_method_filter, null);
108
109                                 if (current_type == TypeManager.object_type)
110                                         searching = false;
111                                 else {
112                                         current_type = current_type.BaseType;
113                                         if (!current_type.IsAbstract)
114                                                 searching = false;
115                                 }
116
117                                 if (mi.Count == 0)
118                                         continue;
119
120                                 if (mi.Count == 1 && !(mi [0] is MethodBase))
121                                         searching = false;
122                                 else 
123                                         list = TypeManager.CopyNewMethods (list, mi);
124                         } while (searching);
125
126                         if (list == null)
127                                 return null;
128                         
129                         for (int i = 0; i < list.Count; i++){
130                                 while (list.Count > i && !((MethodInfo) list [i]).IsAbstract)
131                                         list.RemoveAt (i);
132                         }
133
134                         if (list.Count == 0)
135                                 return null;
136
137                         return list;
138                 }
139
140                 PendingImplementation (TypeContainer container, MissingInterfacesInfo [] missing_ifaces, ArrayList abstract_methods, int total)
141                 {
142                         TypeBuilder type_builder = container.TypeBuilder;
143                         
144                         this.container = container;
145                         pending_implementations = new TypeAndMethods [total];
146
147                         int i = 0;
148                         foreach (MissingInterfacesInfo missing in missing_ifaces){
149                                 MethodInfo [] mi;
150                                 Type t = missing.Type;
151
152                                 if (t is TypeBuilder){
153                                         TypeContainer iface;
154
155                                         iface = TypeManager.LookupInterface (t);
156
157                                         mi = iface.GetMethods ();
158                                 } else 
159                                         mi = t.GetMethods ();
160
161                                 int count = mi.Length;
162                                 pending_implementations [i].type = t;
163                                 pending_implementations [i].optional = missing.Optional;
164                                 pending_implementations [i].methods = mi;
165                                 pending_implementations [i].args = new Type [count][];
166                                 pending_implementations [i].found = new bool [count];
167                                 pending_implementations [i].need_proxy = new MethodInfo [count];
168                                 string indexer_name = TypeManager.IndexerPropertyName (t);
169
170                                 pending_implementations [i].set_indexer_name = "set_" + indexer_name;
171                                 pending_implementations [i].get_indexer_name = "get_" + indexer_name;
172                                 
173                                 int j = 0;
174                                 foreach (MethodInfo m in mi){
175                                         Type [] types = TypeManager.GetArgumentTypes (m);
176                                         
177                                         pending_implementations [i].args [j] = types;
178                                         j++;
179                                 }
180                                 i++;
181                         }
182
183                         if (abstract_methods != null){
184                                 int count = abstract_methods.Count;
185                                 pending_implementations [i].methods = new MethodInfo [count];
186                                 pending_implementations [i].need_proxy = new MethodInfo [count];
187                                 
188                                 abstract_methods.CopyTo (pending_implementations [i].methods, 0);
189                                 pending_implementations [i].found = new bool [count];
190                                 pending_implementations [i].args = new Type [count][];
191                                 pending_implementations [i].type = type_builder;
192
193                                 string indexer_name = TypeManager.IndexerPropertyName (type_builder);
194                                 pending_implementations [i].set_indexer_name = "set_" + indexer_name;
195                                 pending_implementations [i].get_indexer_name = "get_" + indexer_name;
196                                 
197                                 int j = 0;
198                                 foreach (MemberInfo m in abstract_methods){
199                                         MethodInfo mi = (MethodInfo) m;
200                                         
201                                         Type [] types = TypeManager.GetArgumentTypes (mi);
202                                         
203                                         pending_implementations [i].args [j] = types;
204                                         j++;
205                                 }
206                         }
207                 }
208
209                 struct MissingInterfacesInfo {
210                         public Type Type;
211                         public bool Optional;
212
213                         public MissingInterfacesInfo (Type t)
214                         {
215                                 Type = t;
216                                 Optional = false;
217                         }
218                 }
219
220                 static MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
221                 
222                 static MissingInterfacesInfo [] GetMissingInterfaces (TypeBuilder type_builder)
223                 {
224                         //
225                         // Notice that TypeBuilders will only return the interfaces that the Type
226                         // is supposed to implement, not all the interfaces that the type implements.
227                         //
228                         // Even better -- on MS it returns an empty array, no matter what.
229                         //
230                         // Completely broken.  So we do it ourselves!
231                         //
232                         TypeExpr [] impl = TypeManager.GetExplicitInterfaces (type_builder);
233
234                         if (impl == null || impl.Length == 0)
235                                 return EmptyMissingInterfacesInfo;
236
237                         MissingInterfacesInfo [] ret = new MissingInterfacesInfo [impl.Length];
238
239                         for (int i = 0; i < impl.Length; i++)
240                                 ret [i] = new MissingInterfacesInfo (impl [i].Type);
241                         
242                         // we really should not get here because Object doesnt implement any
243                         // interfaces. But it could implement something internal, so we have
244                         // to handle that case.
245                         if (type_builder.BaseType == null)
246                                 return ret;
247                         
248                         TypeExpr [] parent_impls = TypeManager.GetInterfaces (type_builder.BaseType);
249                         
250                         foreach (TypeExpr te in parent_impls) {
251                                 Type t = te.Type;
252                                 
253                                 for (int i = 0; i < ret.Length; i ++) {
254                                         if (t == ret [i].Type) {
255                                                 ret [i].Optional = true;
256                                                 break;
257                                         }
258                                 }
259                         }
260                         return ret;
261                 }
262                 
263                 //
264                 // Factory method: if there are pending implementation methods, we return a PendingImplementation
265                 // object, otherwise we return null.
266                 //
267                 // Register method implementations are either abstract methods
268                 // flagged as such on the base class or interface methods
269                 //
270                 static public PendingImplementation GetPendingImplementations (TypeContainer container)
271                 {
272                         TypeBuilder type_builder = container.TypeBuilder;
273                         MissingInterfacesInfo [] missing_interfaces;
274                         Type b = type_builder.BaseType;
275
276                         missing_interfaces = GetMissingInterfaces (type_builder);
277
278                         //
279                         // If we are implementing an abstract class, and we are not
280                         // ourselves abstract, and there are abstract methods (C# allows
281                         // abstract classes that have no abstract methods), then allocate
282                         // one slot.
283                         //
284                         // We also pre-compute the methods.
285                         //
286                         bool implementing_abstract = ((b != null) && b.IsAbstract && !type_builder.IsAbstract);
287                         ArrayList abstract_methods = null;
288
289                         if (implementing_abstract){
290                                 abstract_methods = GetAbstractMethods (b);
291                                 
292                                 if (abstract_methods == null)
293                                         implementing_abstract = false;
294                         }
295                         
296                         int total = missing_interfaces.Length +  (implementing_abstract ? 1 : 0);
297                         if (total == 0)
298                                 return null;
299
300                         return new PendingImplementation (container, missing_interfaces, abstract_methods, total);
301                 }
302
303                 public enum Operation {
304                         //
305                         // If you change this, review the whole InterfaceMethod routine as there
306                         // are a couple of assumptions on these three states
307                         //
308                         Lookup, ClearOne, ClearAll
309                 }
310
311                 /// <summary>
312                 ///   Whether the specified method is an interface method implementation
313                 /// </summary>
314                 public MethodInfo IsInterfaceMethod (Type t, string name, Type ret_type, Type [] args)
315                 {
316                         return InterfaceMethod (t, name, ret_type, args, Operation.Lookup, null);
317                 }
318
319                 public MethodInfo IsInterfaceIndexer (Type t, Type ret_type, Type [] args)
320                 {
321                         return InterfaceMethod (t, null, ret_type, args, Operation.Lookup, null);
322                 }
323
324                 public void ImplementMethod (Type t, string name, Type ret_type, Type [] args, bool clear_one) 
325                 {
326                         InterfaceMethod (t, name, ret_type, args,
327                                          clear_one ? Operation.ClearOne : Operation.ClearAll, null);
328                 }
329
330                 public void ImplementIndexer (Type t, MethodInfo mi, Type ret_type, Type [] args, bool clear_one) 
331                 {
332                         InterfaceMethod (t, null, ret_type, args,
333                                          clear_one ? Operation.ClearOne : Operation.ClearAll, mi);
334                 }
335                 
336                 /// <remarks>
337                 ///   If a method in Type `t' (or null to look in all interfaces
338                 ///   and the base abstract class) with name `Name', return type `ret_type' and
339                 ///   arguments `args' implements an interface, this method will
340                 ///   return the MethodInfo that this method implements.
341                 ///
342                 ///   If `name' is null, we operate solely on the method's signature.  This is for
343                 ///   instance used when implementing indexers.
344                 ///
345                 ///   The `Operation op' controls whether to lookup, clear the pending bit, or clear
346                 ///   all the methods with the given signature.
347                 ///
348                 ///   The `MethodInfo need_proxy' is used when we're implementing an interface's
349                 ///   indexer in a class.  If the new indexer's IndexerName does not match the one
350                 ///   that was used in the interface, then we always need to create a proxy for it.
351                 ///
352                 /// </remarks>
353                 public MethodInfo InterfaceMethod (Type t, string name, Type ret_type, Type [] args,
354                                                    Operation op, MethodInfo need_proxy)
355                 {
356                         int arg_len = args.Length;
357
358                         if (pending_implementations == null)
359                                 return null;
360
361                         foreach (TypeAndMethods tm in pending_implementations){
362                                 if (!(t == null || tm.type == t))
363                                         continue;
364
365                                 int method_count = tm.methods.Length;
366                                 MethodInfo m;
367                                 for (int i = 0; i < method_count; i++){
368                                         m = tm.methods [i];
369
370                                         if (m == null)
371                                                 continue;
372
373                                         //
374                                         // `need_proxy' is not null when we're implementing an
375                                         // interface indexer and this is Clear(One/All) operation.
376                                         //
377                                         // If `name' is null, then we do a match solely based on the
378                                         // signature and not on the name (this is done in the Lookup
379                                         // for an interface indexer).
380                                         //
381                                         if (name == null){
382                                                 if (m.Name != tm.get_indexer_name && m.Name != tm.set_indexer_name)
383                                                         continue;
384                                         } else if ((need_proxy == null) && (name != m.Name))
385                                                 continue;
386
387                                         if (ret_type != m.ReturnType){
388                                                 if (!((ret_type == null && m.ReturnType == TypeManager.void_type) ||
389                                                       (m.ReturnType == null && ret_type == TypeManager.void_type)))
390                                                         continue;
391                                         }
392
393                                         //
394                                         // Check if we have the same parameters
395                                         //
396                                         if (tm.args [i].Length != arg_len)
397                                                 continue;
398
399                                         int j, top = args.Length;
400                                         bool fail = false;
401                                         
402                                         for (j = 0; j < top; j++){
403                                                 if (tm.args [i][j] != args[j]){
404                                                         fail = true;
405                                                         break;
406                                                 }
407                                         }
408                                         if (fail)
409                                                 continue;
410
411                                         if (op != Operation.Lookup){
412                                                 // If `t != null', then this is an explicitly interface
413                                                 // implementation and we can always clear the method.
414                                                 // `need_proxy' is not null if we're implementing an
415                                                 // interface indexer.  In this case, we need to create
416                                                 // a proxy if the implementation's IndexerName doesn't
417                                                 // match the IndexerName in the interface.
418                                                 bool name_matches = false;
419                                                 if (name == m.Name || m.Name == tm.get_indexer_name || m.Name == tm.set_indexer_name)
420                                                         name_matches = true;
421                                                 
422                                                 if ((t == null) && (need_proxy != null) && !name_matches)
423                                                         tm.need_proxy [i] = need_proxy;
424                                                 else 
425                                                         tm.methods [i] = null;
426                                         }
427                                         tm.found [i] = true;
428
429                                         //
430                                         // Lookups and ClearOne return
431                                         //
432                                         if (op != Operation.ClearAll)
433                                                 return m;
434                                 }
435
436                                 // If a specific type was requested, we can stop now.
437                                 if (tm.type == t)
438                                         return null;
439                         }
440                         return null;
441                 }
442
443                 /// <summary>
444                 ///   C# allows this kind of scenarios:
445                 ///   interface I { void M (); }
446                 ///   class X { public void M (); }
447                 ///   class Y : X, I { }
448                 ///
449                 ///   For that case, we create an explicit implementation function
450                 ///   I.M in Y.
451                 /// </summary>
452                 void DefineProxy (Type iface, MethodInfo parent_method, MethodInfo iface_method,
453                                   Type [] args)
454                 {
455                         MethodBuilder proxy;
456
457                         string proxy_name = iface.Name + "." + iface_method.Name;
458
459                         proxy = container.TypeBuilder.DefineMethod (
460                                 proxy_name,
461                                 MethodAttributes.HideBySig |
462                                 MethodAttributes.NewSlot |
463                                 MethodAttributes.Virtual,
464                                 CallingConventions.Standard | CallingConventions.HasThis,
465                                 parent_method.ReturnType, args);
466
467                         int top = args.Length;
468                         ILGenerator ig = proxy.GetILGenerator ();
469
470                         ig.Emit (OpCodes.Ldarg_0);
471                         for (int i = 0; i < top; i++){
472                                 switch (i){
473                                 case 0:
474                                         ig.Emit (OpCodes.Ldarg_1); break;
475                                 case 1:
476                                         ig.Emit (OpCodes.Ldarg_2); break;
477                                 case 2:
478                                         ig.Emit (OpCodes.Ldarg_3); break;
479                                 default:
480                                         ig.Emit (OpCodes.Ldarg, i - 1); break;
481                                 }
482                         }
483                         ig.Emit (OpCodes.Call, parent_method);
484                         ig.Emit (OpCodes.Ret);
485
486                         container.TypeBuilder.DefineMethodOverride (proxy, iface_method);
487                 }
488                 
489                 /// <summary>
490                 ///   This function tells whether one of our parent classes implements
491                 ///   the given method (which turns out, it is valid to have an interface
492                 ///   implementation in a parent
493                 /// </summary>
494                 bool ParentImplements (Type iface_type, MethodInfo mi)
495                 {
496                         MethodSignature ms;
497                         
498                         Type [] args = TypeManager.GetArgumentTypes (mi);
499                         ms = new MethodSignature (mi.Name, mi.ReturnType, args);
500                         MemberList list = TypeContainer.FindMembers (
501                                 container.TypeBuilder.BaseType, MemberTypes.Method | MemberTypes.Property,
502                                 BindingFlags.Public | BindingFlags.Instance,
503                                 MethodSignature.method_signature_filter, ms);
504
505                         if (list.Count == 0)
506                                 return false;
507
508                         MethodInfo parent = (MethodInfo) list [0];
509                         if (!parent.IsAbstract)
510                                 DefineProxy (iface_type, parent, mi, args);
511                         return true;
512                 }
513
514                 /// <summary>
515                 ///   Verifies that any pending abstract methods or interface methods
516                 ///   were implemented.
517                 /// </summary>
518                 public bool VerifyPendingMethods ()
519                 {
520                         int top = pending_implementations.Length;
521                         bool errors = false;
522                         int i;
523                         
524                         for (i = 0; i < top; i++){
525                                 Type type = pending_implementations [i].type;
526                                 int j = 0;
527                                 
528                                 foreach (MethodInfo mi in pending_implementations [i].methods){
529                                         if (mi == null)
530                                                 continue;
531
532                                         if (type.IsInterface){
533                                                 MethodInfo need_proxy =
534                                                         pending_implementations [i].need_proxy [j];
535
536                                                 if (need_proxy != null) {
537                                                         Type [] args = TypeManager.GetArgumentTypes (mi);
538                                                         DefineProxy (type, need_proxy, mi, args);
539                                                         continue;
540                                                 }
541
542                                                 if (ParentImplements (type, mi))
543                                                         continue;
544
545                                                 if (pending_implementations [i].optional)
546                                                         continue;
547                                                 
548                                                 if (pending_implementations [i].found [j]) {
549                                                         string[] methodLabel = TypeManager.CSharpSignature (mi).Split ('.');
550                                                         Report.Error (536, container.Location, "'{0}' does not implement interface member '{1}'. '{2}.{3}' is either static, not public, or has the wrong return type",
551                                                                 container.Name, TypeManager.CSharpSignature (mi), container.Name, methodLabel[methodLabel.Length - 1]);
552                                                 }
553                                                 else { 
554                                                         Report.Error (535, container.Location, "'{0}' does not implement interface member '{1}'",
555                                                                 container.Name, TypeManager.CSharpSignature (mi));
556                                                 }
557                                         } else {
558                                                 Report.Error (534, container.Location, "'{0}' does not implement inherited abstract member '{1}'",
559                                                         container.Name, TypeManager.CSharpSignature (mi));
560                                         }
561                                         errors = true;
562                                         j++;
563                                 }
564                         }
565                         return errors;
566                 }
567         } /* end of class */
568 }