**** Merged r41276 from MCS ****
[mono.git] / mcs / gmcs / 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 base 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 base 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                 //   bases 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.NonPublic |
106                                         BindingFlags.Instance | 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.IsInterface)
153                                         continue;
154
155                                 if (t is TypeBuilder){
156                                         TypeContainer iface;
157
158                                         iface = TypeManager.LookupInterface (t);
159                                         
160                                         mi = iface.GetMethods ();
161                                 } else 
162                                         mi = t.GetMethods ();
163                                 
164                                 int count = mi.Length;
165                                 pending_implementations [i].type = t;
166                                 pending_implementations [i].optional = missing.Optional;
167                                 pending_implementations [i].methods = mi;
168                                 pending_implementations [i].args = new Type [count][];
169                                 pending_implementations [i].found = new bool [count];
170                                 pending_implementations [i].need_proxy = new MethodInfo [count];
171                                 string indexer_name = TypeManager.IndexerPropertyName (t);
172
173                                 pending_implementations [i].set_indexer_name = "set_" + indexer_name;
174                                 pending_implementations [i].get_indexer_name = "get_" + indexer_name;
175                                 
176                                 int j = 0;
177                                 foreach (MethodInfo m in mi){
178                                         Type [] types;
179                                         
180                                         // If there is a previous error, just ignore
181                                         if (m == null)
182                                                 types = TypeManager.NoTypes;
183                                         else
184                                                 types = TypeManager.GetArgumentTypes (m);
185                                         
186                                         pending_implementations [i].args [j] = types;
187                                         j++;
188                                 }
189                                 i++;
190                         }
191
192                         if (abstract_methods != null){
193                                 int count = abstract_methods.Count;
194                                 pending_implementations [i].methods = new MethodInfo [count];
195                                 pending_implementations [i].need_proxy = new MethodInfo [count];
196                                 
197                                 abstract_methods.CopyTo (pending_implementations [i].methods, 0);
198                                 pending_implementations [i].found = new bool [count];
199                                 pending_implementations [i].args = new Type [count][];
200                                 pending_implementations [i].type = type_builder;
201
202                                 string indexer_name = TypeManager.IndexerPropertyName (type_builder);
203                                 pending_implementations [i].set_indexer_name = "set_" + indexer_name;
204                                 pending_implementations [i].get_indexer_name = "get_" + indexer_name;
205                                 
206                                 int j = 0;
207                                 foreach (MemberInfo m in abstract_methods){
208                                         MethodInfo mi = (MethodInfo) m;
209                                         
210                                         Type [] types = TypeManager.GetArgumentTypes (mi);
211                                         
212                                         pending_implementations [i].args [j] = types;
213                                         j++;
214                                 }
215                         }
216                 }
217
218                 struct MissingInterfacesInfo {
219                         public Type Type;
220                         public bool Optional;
221
222                         public MissingInterfacesInfo (Type t)
223                         {
224                                 Type = t;
225                                 Optional = false;
226                         }
227                 }
228
229                 static MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
230                 
231                 static MissingInterfacesInfo [] GetMissingInterfaces (TypeBuilder type_builder)
232                 {
233                         //
234                         // Notice that TypeBuilders will only return the interfaces that the Type
235                         // is supposed to implement, not all the interfaces that the type implements.
236                         //
237                         // Even better -- on MS it returns an empty array, no matter what.
238                         //
239                         // Completely broken.  So we do it ourselves!
240                         //
241                         Type [] impl = TypeManager.GetExplicitInterfaces (type_builder);
242
243                         if (impl == null || impl.Length == 0)
244                                 return EmptyMissingInterfacesInfo;
245
246                         MissingInterfacesInfo [] ret = new MissingInterfacesInfo [impl.Length];
247
248                         for (int i = 0; i < impl.Length; i++)
249                                 ret [i] = new MissingInterfacesInfo (impl [i]);
250
251                         // we really should not get here because Object doesnt implement any
252                         // interfaces. But it could implement something internal, so we have
253                         // to handle that case.
254                         if (type_builder.BaseType == null)
255                                 return ret;
256                         
257                         Type [] base_impls = TypeManager.GetInterfaces (type_builder.BaseType);
258                         
259                         foreach (Type t in base_impls) {
260                                 for (int i = 0; i < ret.Length; i ++) {
261                                         if (t == ret [i].Type) {
262                                                 ret [i].Optional = true;
263                                                 break;
264                                         }
265                                 }
266                         }
267                         return ret;
268                 }
269                 
270                 //
271                 // Factory method: if there are pending implementation methods, we return a PendingImplementation
272                 // object, otherwise we return null.
273                 //
274                 // Register method implementations are either abstract methods
275                 // flagged as such on the base class or interface methods
276                 //
277                 static public PendingImplementation GetPendingImplementations (TypeContainer container)
278                 {
279                         TypeBuilder type_builder = container.TypeBuilder;
280                         MissingInterfacesInfo [] missing_interfaces;
281                         Type b = type_builder.BaseType;
282
283                         missing_interfaces = GetMissingInterfaces (type_builder);
284
285                         //
286                         // If we are implementing an abstract class, and we are not
287                         // ourselves abstract, and there are abstract methods (C# allows
288                         // abstract classes that have no abstract methods), then allocate
289                         // one slot.
290                         //
291                         // We also pre-compute the methods.
292                         //
293                         bool implementing_abstract = ((b != null) && b.IsAbstract && !type_builder.IsAbstract);
294                         ArrayList abstract_methods = null;
295
296                         if (implementing_abstract){
297                                 abstract_methods = GetAbstractMethods (b);
298                                 
299                                 if (abstract_methods == null)
300                                         implementing_abstract = false;
301                         }
302                         
303                         int total = missing_interfaces.Length +  (implementing_abstract ? 1 : 0);
304                         if (total == 0)
305                                 return null;
306
307                         return new PendingImplementation (container, missing_interfaces, abstract_methods, total);
308                 }
309
310                 public enum Operation {
311                         //
312                         // If you change this, review the whole InterfaceMethod routine as there
313                         // are a couple of assumptions on these three states
314                         //
315                         Lookup, ClearOne, ClearAll
316                 }
317
318                 /// <summary>
319                 ///   Whether the specified method is an interface method implementation
320                 /// </summary>
321                 public MethodInfo IsInterfaceMethod (Type t, string name, Type ret_type, Type [] args)
322                 {
323                         return InterfaceMethod (t, name, ret_type, args, Operation.Lookup, null);
324                 }
325
326                 public MethodInfo IsInterfaceIndexer (Type t, Type ret_type, Type [] args)
327                 {
328                         return InterfaceMethod (t, null, ret_type, args, Operation.Lookup, null);
329                 }
330
331                 public void ImplementMethod (Type t, string name, Type ret_type, Type [] args, bool clear_one) 
332                 {
333                         InterfaceMethod (t, name, ret_type, args,
334                                          clear_one ? Operation.ClearOne : Operation.ClearAll, null);
335                 }
336
337                 public void ImplementIndexer (Type t, MethodInfo mi, Type ret_type, Type [] args, bool clear_one) 
338                 {
339                         InterfaceMethod (t, null, ret_type, args,
340                                          clear_one ? Operation.ClearOne : Operation.ClearAll, mi);
341                 }
342                 
343                 /// <remarks>
344                 ///   If a method in Type `t' (or null to look in all interfaces
345                 ///   and the base abstract class) with name `Name', return type `ret_type' and
346                 ///   arguments `args' implements an interface, this method will
347                 ///   return the MethodInfo that this method implements.
348                 ///
349                 ///   If `name' is null, we operate solely on the method's signature.  This is for
350                 ///   instance used when implementing indexers.
351                 ///
352                 ///   The `Operation op' controls whether to lookup, clear the pending bit, or clear
353                 ///   all the methods with the given signature.
354                 ///
355                 ///   The `MethodInfo need_proxy' is used when we're implementing an interface's
356                 ///   indexer in a class.  If the new indexer's IndexerName does not match the one
357                 ///   that was used in the interface, then we always need to create a proxy for it.
358                 ///
359                 /// </remarks>
360                 public MethodInfo InterfaceMethod (Type t, string name, Type ret_type, Type [] args,
361                                                    Operation op, MethodInfo need_proxy)
362                 {
363                         int arg_len = args.Length;
364
365                         if (pending_implementations == null)
366                                 return null;
367
368                         foreach (TypeAndMethods tm in pending_implementations){
369                                 if (!(t == null || tm.type == t))
370                                         continue;
371
372                                 int method_count = tm.methods.Length;
373                                 MethodInfo m;
374                                 for (int i = 0; i < method_count; i++){
375                                         m = tm.methods [i];
376
377                                         if (m == null)
378                                                 continue;
379
380                                         string mname = TypeManager.GetMethodName (m);
381
382                                         //
383                                         // `need_proxy' is not null when we're implementing an
384                                         // interface indexer and this is Clear(One/All) operation.
385                                         //
386                                         // If `name' is null, then we do a match solely based on the
387                                         // signature and not on the name (this is done in the Lookup
388                                         // for an interface indexer).
389                                         //
390                                         if (name == null){
391                                                 if (mname != tm.get_indexer_name && mname != tm.set_indexer_name)
392                                                         continue;
393                                         } else if ((need_proxy == null) && (name != mname))
394                                                 continue;
395
396                                         if (!TypeManager.IsEqual (ret_type, m.ReturnType)){
397                                                 if (!((ret_type == null && m.ReturnType == TypeManager.void_type) ||
398                                                       (m.ReturnType == null && ret_type == TypeManager.void_type)))
399                                                         continue;
400                                         }
401
402                                         //
403                                         // Check if we have the same parameters
404                                         //
405                                         if (tm.args [i].Length != arg_len)
406                                                 continue;
407
408                                         int j, top = args.Length;
409                                         bool fail = false;
410
411                                         for (j = 0; j < top; j++){
412                                                 if (!TypeManager.IsEqual (tm.args [i][j], args[j])){
413                                                         fail = true;
414                                                         break;
415                                                 }
416                                         }
417                                         if (fail)
418                                                 continue;
419
420                                         if (op != Operation.Lookup){
421                                                 // If `t != null', then this is an explicitly interface
422                                                 // implementation and we can always clear the method.
423                                                 // `need_proxy' is not null if we're implementing an
424                                                 // interface indexer.  In this case, we need to create
425                                                 // a proxy if the implementation's IndexerName doesn't
426                                                 // match the IndexerName in the interface.
427                                                 bool name_matches = false;
428                                                 if (name == mname || mname == tm.get_indexer_name || mname == tm.set_indexer_name)
429                                                         name_matches = true;
430                                                 
431                                                 if ((t == null) && (need_proxy != null) && !name_matches)
432                                                         tm.need_proxy [i] = need_proxy;
433                                                 else 
434                                                         tm.methods [i] = null;
435                                         }
436                                         tm.found [i] = true;
437
438                                         //
439                                         // Lookups and ClearOne return
440                                         //
441                                         if (op != Operation.ClearAll)
442                                                 return m;
443                                 }
444
445                                 // If a specific type was requested, we can stop now.
446                                 if (tm.type == t)
447                                         return null;
448                         }
449                         return null;
450                 }
451
452                 /// <summary>
453                 ///   C# allows this kind of scenarios:
454                 ///   interface I { void M (); }
455                 ///   class X { public void M (); }
456                 ///   class Y : X, I { }
457                 ///
458                 ///   For that case, we create an explicit implementation function
459                 ///   I.M in Y.
460                 /// </summary>
461                 void DefineProxy (Type iface, MethodInfo base_method, MethodInfo iface_method,
462                                   Type [] args)
463                 {
464                         MethodBuilder proxy;
465
466                         string proxy_name = iface.Name + "." + iface_method.Name;
467
468                         proxy = container.TypeBuilder.DefineMethod (
469                                 proxy_name,
470                                 MethodAttributes.HideBySig |
471                                 MethodAttributes.NewSlot |
472                                 MethodAttributes.Virtual,
473                                 CallingConventions.Standard | CallingConventions.HasThis,
474                                 base_method.ReturnType, args);
475
476                         ParameterData pd = TypeManager.GetParameterData (iface_method);
477                         proxy.DefineParameter (0, ParameterAttributes.None, "");
478                         for (int i = 0; i < pd.Count; i++) {
479                                 string name = pd.ParameterName (i);
480                                 ParameterAttributes attr = Parameter.GetParameterAttributes (pd.ParameterModifier (i));
481                                 proxy.DefineParameter (i + 1, attr, name);
482                         }
483
484                         int top = args.Length;
485                         ILGenerator ig = proxy.GetILGenerator ();
486
487                         for (int i = 0; i <= top; i++)
488                                 ParameterReference.EmitLdArg (ig, i);
489
490                         ig.Emit (OpCodes.Call, base_method);
491                         ig.Emit (OpCodes.Ret);
492
493                         container.TypeBuilder.DefineMethodOverride (proxy, iface_method);
494                 }
495                 
496                 /// <summary>
497                 ///   This function tells whether one of our base classes implements
498                 ///   the given method (which turns out, it is valid to have an interface
499                 ///   implementation in a base
500                 /// </summary>
501                 bool BaseImplements (Type iface_type, MethodInfo mi)
502                 {
503                         MethodSignature ms;
504                         
505                         Type [] args = TypeManager.GetArgumentTypes (mi);
506                         ms = new MethodSignature (mi.Name, mi.ReturnType, args);
507                         MemberList list = TypeContainer.FindMembers (
508                                 container.TypeBuilder.BaseType, MemberTypes.Method | MemberTypes.Property,
509                                 BindingFlags.Public | BindingFlags.Instance,
510                                 MethodSignature.method_signature_filter, ms);
511
512                         if (list.Count == 0)
513                                 return false;
514
515                         MethodInfo base_method = (MethodInfo) list [0];
516                         if (!base_method.IsAbstract)
517                                 DefineProxy (iface_type, base_method, mi, args);
518                         return true;
519                 }
520
521                 /// <summary>
522                 ///   Verifies that any pending abstract methods or interface methods
523                 ///   were implemented.
524                 /// </summary>
525                 public bool VerifyPendingMethods ()
526                 {
527                         int top = pending_implementations.Length;
528                         bool errors = false;
529                         int i;
530                         
531                         for (i = 0; i < top; i++){
532                                 Type type = pending_implementations [i].type;
533                                 int j = 0;
534
535                                 foreach (MethodInfo mi in pending_implementations [i].methods){
536                                         if (mi == null)
537                                                 continue;
538
539                                         if (type.IsInterface){
540                                                 MethodInfo need_proxy =
541                                                         pending_implementations [i].need_proxy [j];
542
543                                                 if (need_proxy != null) {
544                                                         Type [] args = TypeManager.GetArgumentTypes (mi);
545                                                         DefineProxy (type, need_proxy, mi, args);
546                                                         continue;
547                                                 }
548
549                                                 if (BaseImplements (type, mi))
550                                                         continue;
551
552                                                 if (pending_implementations [i].optional)
553                                                         continue;
554
555                                                 Report.SymbolRelatedToPreviousError (mi);
556                                                 if (pending_implementations [i].found [j]) {
557                                                         if (mi.IsSpecialName) {
558                                                                 string name = TypeManager.CSharpName (mi.DeclaringType) + '.' + mi.Name.Substring (4);
559                                                                 Report.Error (551, container.Location, "Explicit interface implementation '{0}.{1}' is missing accessor '{1}'",
560                                                                         container.Name, name);
561                                                         } else {
562                                                                 string[] methodLabel = TypeManager.CSharpSignature (mi).Split ('.');
563                                                                 Report.Error (536, container.Location,
564                                                                         "'{0}' does not implement interface member '{1}'. '{2}.{3}' " +
565                                                                         "is either static, not public, or has the wrong return type",
566                                                                         container.Name, TypeManager.CSharpSignature (mi),
567                                                                         container.Name, methodLabel[methodLabel.Length - 1]);
568                                                         }
569                                                 }
570                                                 else {
571                                                         Report.Error (535, container.Location, "'{0}' does not implement interface member '{1}'",
572                                                                 container.Name, TypeManager.CSharpSignature (mi));
573                                                 }
574                                         } else {
575                                                 Report.Error (534, container.Location, "'{0}' does not implement inherited abstract member '{1}'",
576                                                         container.Name, TypeManager.CSharpSignature (mi));
577                                         }
578                                         errors = true;
579                                         j++;
580                                 }
581                         }
582                         return errors;
583                 }
584         } /* end of class */
585 }