error messages review
[mono.git] / mcs / gmcs / delegate.cs
1 //
2 // delegate.cs: Delegate Handler
3 //
4 // Authors:
5 //     Ravi Pratap (ravi@ximian.com)
6 //     Miguel de Icaza (miguel@ximian.com)
7 //
8 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 //
12 //
13
14 using System;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Text;
19
20 namespace Mono.CSharp {
21
22         /// <summary>
23         ///   Holds Delegates
24         /// </summary>
25         public class Delegate : DeclSpace {
26                 public Expression ReturnType;
27                 public Parameters      Parameters;
28
29                 public ConstructorBuilder ConstructorBuilder;
30                 public MethodBuilder      InvokeBuilder;
31                 public MethodBuilder      BeginInvokeBuilder;
32                 public MethodBuilder      EndInvokeBuilder;
33                 
34                 Type [] param_types;
35                 Type ret_type;
36
37                 static string[] attribute_targets = new string [] { "type", "return" };
38                 
39                 Expression instance_expr;
40                 MethodBase delegate_method;
41                 ReturnParameter return_attributes;
42         
43                 const int AllowedModifiers =
44                         Modifiers.NEW |
45                         Modifiers.PUBLIC |
46                         Modifiers.PROTECTED |
47                         Modifiers.INTERNAL |
48                         Modifiers.UNSAFE |
49                         Modifiers.PRIVATE;
50
51                 public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
52                                  int mod_flags, MemberName name, Parameters param_list,
53                                  Attributes attrs, Location l)
54                         : base (ns, parent, name, attrs, l)
55
56                 {
57                         this.ReturnType = type;
58                         ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,
59                                                            IsTopLevel ? Modifiers.INTERNAL :
60                                                            Modifiers.PRIVATE, l);
61                         Parameters      = param_list;
62                 }
63
64                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
65                 {
66                         if (a.Target == AttributeTargets.ReturnValue) {
67                                 if (return_attributes == null)
68                                         return_attributes = new ReturnParameter (InvokeBuilder, Location);
69
70                                 return_attributes.ApplyAttributeBuilder (a, cb);
71                                 return;
72                         }
73
74                         base.ApplyAttributeBuilder (a, cb);
75                 }
76
77                 public override TypeBuilder DefineType ()
78                 {
79                         if (TypeBuilder != null)
80                                 return TypeBuilder;
81
82                         ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
83
84                         if (IsGeneric) {
85                                 foreach (TypeParameter type_param in TypeParameters)
86                                         if (!type_param.Resolve (this))
87                                                 return null;
88                         }
89                         
90                         if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
91                                 Namespace system = Namespace.LookupNamespace ("System", true);
92                                 TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
93                                 TypeManager.multicast_delegate_type = expr.ResolveType (ec);
94                         }
95
96                         if (TypeManager.multicast_delegate_type == null)
97                                 Report.Error (-100, Location, "Internal error: delegate used before " +
98                                               "System.MulticastDelegate is resolved.  This can only " +
99                                               "happen during corlib compilation, when using a delegate " +
100                                               "in any of the `core' classes.  See bug #72015 for details.");
101
102                         if (IsTopLevel) {
103                                 if (TypeManager.NamespaceClash (Name, Location))
104                                         return null;
105                                 
106                                 ModuleBuilder builder = CodeGen.Module.Builder;
107
108                                 TypeBuilder = builder.DefineType (
109                                         Name, TypeAttr, TypeManager.multicast_delegate_type);
110                         } else {
111                                 TypeBuilder builder = Parent.TypeBuilder;
112
113                                 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
114                                 TypeBuilder = builder.DefineNestedType (
115                                         name, TypeAttr, TypeManager.multicast_delegate_type);
116                         }
117
118                         TypeManager.AddDelegateType (Name, TypeBuilder, this);
119
120                         if (IsGeneric) {
121                                 string[] param_names = new string [TypeParameters.Length];
122                                 for (int i = 0; i < TypeParameters.Length; i++)
123                                         param_names [i] = TypeParameters [i].Name;
124
125                                 GenericTypeParameterBuilder[] gen_params;
126                                 gen_params = TypeBuilder.DefineGenericParameters (param_names);
127
128                                 int offset = CountTypeParameters - CurrentTypeParameters.Length;
129                                 for (int i = offset; i < gen_params.Length; i++)
130                                         CurrentTypeParameters [i - offset].Define (gen_params [i]);
131
132                                 foreach (TypeParameter type_param in CurrentTypeParameters) {
133                                         if (!type_param.Resolve (this))
134                                                 return null;
135                                 }
136
137                                 for (int i = offset; i < gen_params.Length; i++)
138                                         CurrentTypeParameters [i - offset].DefineConstraints ();
139
140                                 Expression current = new SimpleName (Name, TypeParameters, Location);
141                                 current = current.ResolveAsTypeTerminal (ec);
142                                 if (current == null)
143                                         return null;
144
145                                 CurrentType = current.Type;
146                         }
147
148                         return TypeBuilder;
149                 }
150
151                 public override bool DefineMembers (TypeContainer container)
152                 {
153                         return true;
154                 }
155
156                 public override bool Define ()
157                 {
158                         MethodAttributes mattr;
159                         int i;
160
161                         if (IsGeneric) {
162                                 foreach (TypeParameter type_param in TypeParameters)
163                                         type_param.DefineType (ec);
164                         }
165
166                         if (ec == null)
167                                 throw new InternalErrorException ("Define called before DefineType?");
168
169                         // FIXME: POSSIBLY make this static, as it is always constant
170                         //
171                         Type [] const_arg_types = new Type [2];
172                         const_arg_types [0] = TypeManager.object_type;
173                         const_arg_types [1] = TypeManager.intptr_type;
174
175                         mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
176                                 MethodAttributes.HideBySig | MethodAttributes.Public;
177
178                         ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
179                                                                             CallingConventions.Standard,
180                                                                             const_arg_types);
181
182                         ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
183                         ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
184                         //
185                         // HACK because System.Reflection.Emit is lame
186                         //
187                         Parameter [] fixed_pars = new Parameter [2];
188                         fixed_pars [0] = new Parameter (TypeManager.system_object_expr, "object",
189                                                         Parameter.Modifier.NONE, null, Location);
190                         fixed_pars [1] = new Parameter (TypeManager.system_intptr_expr, "method", 
191                                                         Parameter.Modifier.NONE, null, Location);
192                         Parameters const_parameters = new Parameters (fixed_pars, null);
193                         
194                         TypeManager.RegisterMethod (
195                                 ConstructorBuilder,
196                                 new InternalParameters (const_arg_types, const_parameters),
197                                 const_arg_types);
198                                 
199                         
200                         ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
201
202                         //
203                         // Here the various methods like Invoke, BeginInvoke etc are defined
204                         //
205                         // First, call the `out of band' special method for
206                         // defining recursively any types we need:
207                         
208                         param_types = Parameters.GetParameterInfo (ec);
209                         if (param_types == null)
210                                 return false;
211
212                         //
213                         // Invoke method
214                         //
215
216                         // Check accessibility
217                         foreach (Type partype in param_types){
218                                 if (!Parent.AsAccessible (partype, ModFlags)) {
219                                         Report.Error (59, Location,
220                                                       "Inconsistent accessibility: parameter type `" +
221                                                       TypeManager.CSharpName (partype) + "` is less " +
222                                                       "accessible than delegate `" + Name + "'");
223                                         return false;
224                                 }
225                                 if (partype.IsPointer && !UnsafeOK (Parent))
226                                         return false;
227                         }
228                         
229                         ReturnType = ReturnType.ResolveAsTypeTerminal (ec);
230                         if (ReturnType == null)
231                             return false;
232                         
233                         ret_type = ReturnType.Type;
234                         if (ret_type == null)
235                                 return false;
236
237                         if (!Parent.AsAccessible (ret_type, ModFlags)) {
238                                 Report.Error (58, Location,
239                                               "Inconsistent accessibility: return type `" +
240                                               TypeManager.CSharpName (ret_type) + "` is less " +
241                                               "accessible than delegate `" + Name + "'");
242                                 return false;
243                         }
244
245                         if (ret_type.IsPointer && !UnsafeOK (Parent))
246                                 return false;
247
248                         if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
249                                 Method.Error1599 (Location, ret_type);
250                                 return false;
251                         }
252
253                         //
254                         // We don't have to check any others because they are all
255                         // guaranteed to be accessible - they are standard types.
256                         //
257                         
258                         CallingConventions cc = Parameters.GetCallingConvention ();
259
260                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
261
262                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
263                                                                   mattr,                     
264                                                                   cc,
265                                                                   ret_type,                  
266                                                                   param_types);
267
268                         //
269                         // Define parameters, and count out/ref parameters
270                         //
271                         int out_params = 0;
272                         i = 0;
273                         if (Parameters.FixedParameters != null){
274                                 int top = Parameters.FixedParameters.Length;
275                                 Parameter p;
276                                 
277                                 for (; i < top; i++) {
278                                         p = Parameters.FixedParameters [i];
279                                         p.DefineParameter (ec, InvokeBuilder, null, i + 1);
280
281                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
282                                                 out_params++;
283                                 }
284                         }
285                         if (Parameters.ArrayParameter != null){
286                                 if (TypeManager.param_array_type == null && !RootContext.StdLib) {
287                                         Namespace system = Namespace.LookupNamespace ("System", true);
288                                         TypeExpr expr = system.Lookup (this, "ParamArrayAttribute", Location) as TypeExpr;
289                                         TypeManager.param_array_type = expr.ResolveType (ec);
290                                 }
291
292                                 if (TypeManager.cons_param_array_attribute == null) {
293                                         Type [] void_arg = { };
294                                         TypeManager.cons_param_array_attribute = TypeManager.GetConstructor (
295                                                 TypeManager.param_array_type, void_arg);
296                                 }
297
298                                 ParameterBuilder pb = InvokeBuilder.DefineParameter (
299                                         i + 1, Parameters.ArrayParameter.Attributes,Parameters.ArrayParameter.Name);
300                                 
301                                 pb.SetCustomAttribute (
302                                         new CustomAttributeBuilder (TypeManager.cons_param_array_attribute, new object [0]));
303                         }
304                         
305                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
306
307                         TypeManager.RegisterMethod (InvokeBuilder,
308                                                     new InternalParameters (param_types, Parameters),
309                                                     param_types);
310
311                         //
312                         // BeginInvoke
313                         //
314                         int params_num = param_types.Length;
315                         Type [] async_param_types = new Type [params_num + 2];
316
317                         param_types.CopyTo (async_param_types, 0);
318
319                         async_param_types [params_num] = TypeManager.asynccallback_type;
320                         async_param_types [params_num + 1] = TypeManager.object_type;
321
322                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
323                                 MethodAttributes.Virtual | MethodAttributes.NewSlot;
324                         
325                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
326                                                                        mattr,
327                                                                        cc,
328                                                                        TypeManager.iasyncresult_type,
329                                                                        async_param_types);
330
331                         i = 0;
332                         if (Parameters.FixedParameters != null){
333                                 int top = Parameters.FixedParameters.Length;
334                                 Parameter p;
335                                 
336                                 for (i = 0 ; i < top; i++) {
337                                         p = Parameters.FixedParameters [i];
338
339                                         p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1);
340                                 }
341                         }
342                         if (Parameters.ArrayParameter != null){
343                                 Parameter p = Parameters.ArrayParameter;
344                                 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1);
345
346                                 i++;
347                         }
348
349                         BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
350                         BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
351                         
352                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
353
354                         Parameter [] async_params = new Parameter [params_num + 2];
355                         int n = 0;
356                         if (Parameters.FixedParameters != null){
357                                 Parameters.FixedParameters.CopyTo (async_params, 0);
358                                 n = Parameters.FixedParameters.Length;
359                         }
360                         if (Parameters.ArrayParameter != null)
361                                 async_params [n] = Parameters.ArrayParameter;
362                         
363                         async_params [params_num] = new Parameter (
364                                 TypeManager.system_asynccallback_expr, "callback",
365                                                                    Parameter.Modifier.NONE, null, Location);
366                         async_params [params_num + 1] = new Parameter (
367                                 TypeManager.system_object_expr, "object",
368                                                                    Parameter.Modifier.NONE, null, Location);
369
370                         Parameters async_parameters = new Parameters (async_params, null);
371                         
372                         TypeManager.RegisterMethod (BeginInvokeBuilder,
373                                                     new InternalParameters (async_parameters.GetParameterInfo (ec), async_parameters),
374                                                     async_param_types);
375
376                         //
377                         // EndInvoke is a bit more interesting, all the parameters labeled as
378                         // out or ref have to be duplicated here.
379                         //
380                         
381                         Type [] end_param_types = new Type [out_params + 1];
382                         Parameter [] end_params = new Parameter [out_params + 1];
383                         int param = 0; 
384                         if (out_params > 0){
385                                 int top = Parameters.FixedParameters.Length;
386                                 for (i = 0; i < top; i++){
387                                         Parameter p = Parameters.FixedParameters [i];
388                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
389                                                 continue;
390
391                                         end_param_types [param] = param_types [i];
392                                         end_params [param] = p;
393                                         param++;
394                                 }
395                         }
396                         end_param_types [out_params] = TypeManager.iasyncresult_type;
397                         end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null, Location);
398
399                         //
400                         // Create method, define parameters, register parameters with type system
401                         //
402                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
403                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
404
405                         //
406                         // EndInvoke: Label the parameters
407                         //
408                         EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
409                         for (i = 0; i < end_params.Length-1; i++){
410                                 EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
411                         }
412
413                         Parameters end_parameters = new Parameters (end_params, null);
414
415                         TypeManager.RegisterMethod (
416                                 EndInvokeBuilder,
417                                 new InternalParameters (end_parameters.GetParameterInfo (ec), end_parameters),
418                                 end_param_types);
419
420                         return true;
421                 }
422
423                 public override void Emit ()
424                 {
425                         if (OptAttributes != null) {
426                                 Parameters.LabelParameters (ec, InvokeBuilder);
427                                 OptAttributes.Emit (ec, this);
428                         }
429
430                         base.Emit ();
431                 }
432
433                 protected override TypeAttributes TypeAttr {
434                         get {
435                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
436                                         TypeAttributes.Class | TypeAttributes.Sealed |
437                                         base.TypeAttr;
438                         }
439                 }
440
441                 public override string[] ValidAttributeTargets {
442                         get {
443                                 return attribute_targets;
444                         }
445                 }
446
447                 //TODO: duplicate
448                 protected override bool VerifyClsCompliance (DeclSpace ds)
449                 {
450                         if (!base.VerifyClsCompliance (ds)) {
451                                 return false;
452                         }
453
454                         AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
455
456                         if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
457                                 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
458                         }
459                         return true;
460                 }
461
462                 //
463                 // Returns the MethodBase for "Invoke" from a delegate type, this is used
464                 // to extract the signature of a delegate.
465                 //
466                 public static MethodGroupExpr GetInvokeMethod (EmitContext ec, Type delegate_type,
467                                                                Location loc)
468                 {
469                         Expression ml = Expression.MemberLookup (
470                                 ec, delegate_type, "Invoke", loc);
471
472                         MethodGroupExpr mg = ml as MethodGroupExpr;
473                         if (mg == null) {
474                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
475                                 return null;
476                         }
477
478                         return mg;
479                 }
480                 
481                 /// <summary>
482                 ///  Verifies whether the method in question is compatible with the delegate
483                 ///  Returns the method itself if okay and null if not.
484                 /// </summary>
485                 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type,
486                                                        MethodGroupExpr old_mg, MethodBase mb,
487                                                        Location loc)
488                 {
489                         MethodGroupExpr mg = GetInvokeMethod (ec, delegate_type, loc);
490                         if (mg == null)
491                                 return null;
492
493                         if (old_mg.HasTypeArguments)
494                                 mg.HasTypeArguments = true;
495
496                         MethodBase invoke_mb = mg.Methods [0];
497                         ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
498
499                         if (!mg.HasTypeArguments &&
500                             !TypeManager.InferTypeArguments (ec, invoke_pd, ref mb))
501                                 return null;
502
503                         ParameterData pd = TypeManager.GetParameterData (mb);
504
505                         if (invoke_pd.Count != pd.Count)
506                                 return null;
507
508                         for (int i = pd.Count; i > 0; ) {
509                                 i--;
510
511                                 Type invoke_pd_type = invoke_pd.ParameterType (i);
512                                 Type pd_type = pd.ParameterType (i);
513                                 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
514                                 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
515
516                                 if (invoke_pd_type == pd_type &&
517                                     invoke_pd_type_mod == pd_type_mod)
518                                         continue;
519                                 
520                                 if (invoke_pd_type.IsSubclassOf (pd_type) && 
521                                     invoke_pd_type_mod == pd_type_mod)
522                                         if (RootContext.Version == LanguageVersion.ISO_1) {
523                                                 Report.FeatureIsNotStandardized (loc, "contravariance");
524                                                 return null;
525                                         } else
526                                                 continue;
527
528                                 return null;
529                         }
530
531                         Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
532                         Type mb_retval = ((MethodInfo) mb).ReturnType;
533                         if (invoke_mb_retval == mb_retval)
534                                 return mb;
535                         
536                         if (mb_retval.IsSubclassOf (invoke_mb_retval))
537                                 if (RootContext.Version == LanguageVersion.ISO_1) {
538                                         Report.FeatureIsNotStandardized (loc, "covariance");
539                                         return null;
540                                 }
541                                 else
542                                         return mb;
543                         
544                         return null;
545                 }
546
547                 // <summary>
548                 //  Verifies whether the invocation arguments are compatible with the
549                 //  delegate's target method
550                 // </summary>
551                 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
552                                                         ArrayList args, Location loc)
553                 {
554                         int arg_count;
555
556                         if (args == null)
557                                 arg_count = 0;
558                         else
559                                 arg_count = args.Count;
560
561                         Expression ml = Expression.MemberLookup (
562                                 ec, delegate_type, "Invoke", loc);
563
564                         MethodGroupExpr me = ml as MethodGroupExpr;
565                         if (me == null) {
566                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
567                                 return false;
568                         }
569                         
570                         MethodBase mb = me.Methods [0];
571                         ParameterData pd = TypeManager.GetParameterData (mb);
572
573                         int pd_count = pd.Count;
574
575                         bool params_method = (pd_count != 0) &&
576                                 (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
577
578                         bool is_params_applicable = false;
579                         bool is_applicable = Invocation.IsApplicable (ec, me, args, arg_count, ref mb);
580
581                         if (!is_applicable && params_method &&
582                             Invocation.IsParamsMethodApplicable (ec, me, args, arg_count, ref mb))
583                                 is_applicable = is_params_applicable = true;
584
585                         if (!is_applicable && !params_method && arg_count != pd_count) {
586                                 Report.Error (1593, loc,
587                                               "Delegate '{0}' does not take {1} arguments",
588                                               delegate_type.ToString (), arg_count);
589                                 return false;
590                         }
591
592                         return Invocation.VerifyArgumentsCompat (
593                                         ec, args, arg_count, mb, 
594                                         is_params_applicable || (!is_applicable && params_method),
595                                         delegate_type, false, loc);
596                 }
597                 
598                 /// <summary>
599                 ///  Verifies whether the delegate in question is compatible with this one in
600                 ///  order to determine if instantiation from the same is possible.
601                 /// </summary>
602                 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
603                 {
604                         Expression ml = Expression.MemberLookup (
605                                 ec, delegate_type, "Invoke", loc);
606                         
607                         if (!(ml is MethodGroupExpr)) {
608                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
609                                 return false;
610                         }
611                         
612                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
613                         ParameterData pd = TypeManager.GetParameterData (mb);
614
615                         Expression probe_ml = Expression.MemberLookup (
616                                 ec, delegate_type, "Invoke", loc);
617                         
618                         if (!(probe_ml is MethodGroupExpr)) {
619                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
620                                 return false;
621                         }
622                         
623                         MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
624                         ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
625                         
626                         if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
627                                 return false;
628
629                         if (pd.Count != probe_pd.Count)
630                                 return false;
631
632                         for (int i = pd.Count; i > 0; ) {
633                                 i--;
634
635                                 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
636                                     pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
637                                         return false;
638                         }
639                         
640                         return true;
641                 }
642                 
643                 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
644                 {
645                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
646                         
647                         sb.Append (" " + del_type.ToString ());
648                         sb.Append (" (");
649
650                         int length = pd.Count;
651                         
652                         for (int i = length; i > 0; ) {
653                                 i--;
654
655                                 sb.Append (pd.ParameterDesc (length - i - 1));
656                                 if (i != 0)
657                                         sb.Append (", ");
658                         }
659                         
660                         sb.Append (")");
661                         return sb.ToString ();
662                         
663                 }
664                 
665                 // Hack around System.Reflection as found everywhere else
666                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
667                                                         MemberFilter filter, object criteria)
668                 {
669                         ArrayList members = new ArrayList ();
670
671                         if ((mt & MemberTypes.Method) != 0) {
672                                 if (ConstructorBuilder != null)
673                                 if (filter (ConstructorBuilder, criteria))
674                                         members.Add (ConstructorBuilder);
675
676                                 if (InvokeBuilder != null)
677                                 if (filter (InvokeBuilder, criteria))
678                                         members.Add (InvokeBuilder);
679
680                                 if (BeginInvokeBuilder != null)
681                                 if (filter (BeginInvokeBuilder, criteria))
682                                         members.Add (BeginInvokeBuilder);
683
684                                 if (EndInvokeBuilder != null)
685                                 if (filter (EndInvokeBuilder, criteria))
686                                         members.Add (EndInvokeBuilder);
687                         }
688
689                         return new MemberList (members);
690                 }
691
692                 public override MemberCache MemberCache {
693                         get {
694                                 return null;
695                         }
696                 }
697
698                 public Expression InstanceExpression {
699                         get {
700                                 return instance_expr;
701                         }
702                         set {
703                                 instance_expr = value;
704                         }
705                 }
706
707                 public MethodBase TargetMethod {
708                         get {
709                                 return delegate_method;
710                         }
711                         set {
712                                 delegate_method = value;
713                         }
714                 }
715
716                 public Type TargetReturnType {
717                         get {
718                                 return ret_type;
719                         }
720                 }
721
722                 public Type [] ParameterTypes {
723                         get {
724                                 return param_types;
725                         }
726                 }
727
728                 public override AttributeTargets AttributeTargets {
729                         get {
730                                 return AttributeTargets.Delegate;
731                         }
732                 }
733
734                 //
735                 //   Represents header string for documentation comment.
736                 //
737                 public override string DocCommentHeader {
738                         get { return "T:"; }
739                 }
740
741                 protected override void VerifyObsoleteAttribute()
742                 {
743                         CheckUsageOfObsoleteAttribute (ret_type);
744
745                         foreach (Type type in param_types) {
746                                 CheckUsageOfObsoleteAttribute (type);
747                         }
748                 }
749         }
750
751         //
752         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
753         //
754         public abstract class DelegateCreation : Expression {
755                 protected MethodBase constructor_method;
756                 protected MethodBase delegate_method;
757                 protected MethodGroupExpr method_group;
758                 protected Expression delegate_instance_expression;
759
760                 public DelegateCreation () {}
761
762                 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
763                 {
764                         string method_desc;
765                         MethodBase found_method = mg.Methods [0];
766
767                         if (mg.Methods.Length > 1)
768                                 method_desc = found_method.Name;
769                         else
770                                 method_desc = Invocation.FullMethodDesc (found_method);
771
772                         Expression invoke_method = Expression.MemberLookup (
773                                 ec, type, "Invoke", MemberTypes.Method,
774                                 Expression.AllBindingFlags, loc);
775                         MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
776
777                         ParameterData param = TypeManager.GetParameterData (method);
778                         string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
779
780                         if (!mg.HasTypeArguments &&
781                             !TypeManager.InferTypeArguments (ec, param, ref found_method))
782                                 Report.Error (411, loc, "The type arguments for " +
783                                               "method `{0}' cannot be infered from " +
784                                               "the usage. Try specifying the type " +
785                                               "arguments explicitly.", method_desc);
786                         else if (method.ReturnType != ((MethodInfo) found_method).ReturnType) {
787                                 Report.Error (407, loc, "'{0}' has the wrong return type to match delegate '{1}'", method_desc, delegate_desc);
788                         } else {
789                                 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
790                                         "match delegate '" + delegate_desc + "'");
791                         }
792                 }
793                 
794                 public override void Emit (EmitContext ec)
795                 {
796                         if (delegate_instance_expression == null || delegate_method.IsStatic)
797                                 ec.ig.Emit (OpCodes.Ldnull);
798                         else
799                                 delegate_instance_expression.Emit (ec);
800                         
801                         if (delegate_method.IsVirtual && !method_group.IsBase) {
802                                 ec.ig.Emit (OpCodes.Dup);
803                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
804                         } else
805                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
806                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
807                 }
808
809                 protected bool ResolveConstructorMethod (EmitContext ec)
810                 {
811                         Expression ml = Expression.MemberLookup (
812                                 ec, type, ".ctor", loc);
813
814                         if (!(ml is MethodGroupExpr)) {
815                                 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
816                                 return false;
817                         }
818
819                         constructor_method = ((MethodGroupExpr) ml).Methods [0];
820                         return true;
821                 }
822
823                 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg,
824                                                              bool check_only)
825                 {
826                         foreach (MethodInfo mi in mg.Methods){
827                                 delegate_method  = Delegate.VerifyMethod (ec, type, mg, mi, loc);
828                                 
829                                 if (delegate_method != null)
830                                         break;
831                         }
832                         
833                         if (delegate_method == null) {
834                                 if (!check_only)
835                                         Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
836                                 return null;
837                         }
838                         
839                         //
840                         // Check safe/unsafe of the delegate
841                         //
842                         if (!ec.InUnsafe){
843                                 ParameterData param = TypeManager.GetParameterData (delegate_method);
844                                 int count = param.Count;
845                                 
846                                 for (int i = 0; i < count; i++){
847                                         if (param.ParameterType (i).IsPointer){
848                                                 Expression.UnsafeError (loc);
849                                                 return null;
850                                         }
851                                 }
852                         }
853                                                 
854                         //TODO: implement caching when performance will be low
855                         IMethodData md = TypeManager.GetMethod (delegate_method);
856                         if (md == null) {
857                                 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
858                                         Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
859                                 }
860                         } else {
861                                 md.SetMemberIsUsed ();
862                                 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
863                                         Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
864                                 }
865                         }
866                         
867                         if (mg.InstanceExpression != null)
868                                 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
869                         else if (ec.IsStatic) {
870                                 if (!delegate_method.IsStatic) {
871                                         Report.Error (120, loc,
872                                                       "An object reference is required for the non-static method " +
873                                                       delegate_method.Name);
874                                         return null;
875                                 }
876                                 delegate_instance_expression = null;
877                         } else
878                                 delegate_instance_expression = ec.GetThis (loc);
879
880                         if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
881                                 delegate_instance_expression = new BoxedCast (delegate_instance_expression);
882
883                         method_group = mg;
884                         eclass = ExprClass.Value;
885                         return this;
886                 }
887         }
888
889         //
890         // Created from the conversion code
891         //
892         public class ImplicitDelegateCreation : DelegateCreation {
893
894                 ImplicitDelegateCreation (Type t, Location l)
895                 {
896                         type = t;
897                         loc = l;
898                 }
899
900                 public override Expression DoResolve (EmitContext ec)
901                 {
902                         return this;
903                 }
904
905                 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
906                                                  Type target_type, bool check_only, Location loc)
907                 {
908                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
909                         if (d.ResolveConstructorMethod (ec))
910                                 return d.ResolveMethodGroupExpr (ec, mge, check_only);
911                         else
912                                 return null;
913                 }
914         }
915         
916         //
917         // A delegate-creation-expression, invoked from the `New' class 
918         //
919         public class NewDelegate : DelegateCreation {
920                 public ArrayList Arguments;
921
922                 //
923                 // This constructor is invoked from the `New' expression
924                 //
925                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
926                 {
927                         this.type = type;
928                         this.Arguments = Arguments;
929                         this.loc  = loc; 
930                 }
931
932                 public override Expression DoResolve (EmitContext ec)
933                 {
934                         if (Arguments == null || Arguments.Count != 1) {
935                                 Report.Error (149, loc,
936                                               "Method name expected");
937                                 return null;
938                         }
939
940                         if (!ResolveConstructorMethod (ec))
941                                 return null;
942
943                         Argument a = (Argument) Arguments [0];
944                         
945                         if (!a.ResolveMethodGroup (ec, loc))
946                                 return null;
947                         
948                         Expression e = a.Expr;
949
950                         if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
951                                 return ((AnonymousMethod) e).Compatible (ec, type, false);
952
953                         MethodGroupExpr mg = e as MethodGroupExpr;
954                         if (mg != null)
955                                 return ResolveMethodGroupExpr (ec, mg, false);
956
957                         Type e_type = e.Type;
958
959                         if (!TypeManager.IsDelegateType (e_type)) {
960                                 Report.Error (149, loc, "Method name expected");
961                                 return null;
962                         }
963
964                         method_group = Expression.MemberLookup (
965                                 ec, type, "Invoke", MemberTypes.Method,
966                                 Expression.AllBindingFlags, loc) as MethodGroupExpr;
967
968                         if (method_group == null) {
969                                 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
970                                 return null;
971                         }
972
973                         // This is what MS' compiler reports. We could always choose
974                         // to be more verbose and actually give delegate-level specifics
975                         if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
976                                 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
977                                               "to type '" + type + "'");
978                                 return null;
979                         }
980                                 
981                         delegate_instance_expression = e;
982                         delegate_method = method_group.Methods [0];
983                         
984                         eclass = ExprClass.Value;
985                         return this;
986                 }
987         }
988
989         public class DelegateInvocation : ExpressionStatement {
990
991                 public Expression InstanceExpr;
992                 public ArrayList  Arguments;
993
994                 MethodBase method;
995                 
996                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
997                 {
998                         this.InstanceExpr = instance_expr;
999                         this.Arguments = args;
1000                         this.loc = loc;
1001                 }
1002
1003                 public override Expression DoResolve (EmitContext ec)
1004                 {
1005                         if (InstanceExpr is EventExpr) {
1006                                 
1007                                 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
1008                                 
1009                                 Expression ml = MemberLookup (
1010                                         ec, ec.ContainerType, ei.Name,
1011                                         MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
1012
1013                                 if (ml == null) {
1014                                         //
1015                                         // If this is the case, then the Event does not belong 
1016                                         // to this Type and so, according to the spec
1017                                         // cannot be accessed directly
1018                                         //
1019                                         // Note that target will not appear as an EventExpr
1020                                         // in the case it is being referenced within the same type container;
1021                                         // it will appear as a FieldExpr in that case.
1022                                         //
1023                                         
1024                                         Assign.error70 (ei, loc);
1025                                         return null;
1026                                 }
1027                         }
1028                         
1029                         
1030                         Type del_type = InstanceExpr.Type;
1031                         if (del_type == null)
1032                                 return null;
1033                         
1034                         if (Arguments != null){
1035                                 foreach (Argument a in Arguments){
1036                                         if (!a.Resolve (ec, loc))
1037                                                 return null;
1038                                 }
1039                         }
1040                         
1041                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1042                                 return null;
1043
1044                         Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
1045                         if (!(lookup is MethodGroupExpr)) {
1046                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
1047                                 return null;
1048                         }
1049                         
1050                         method = ((MethodGroupExpr) lookup).Methods [0];
1051                         type = ((MethodInfo) method).ReturnType;
1052                         eclass = ExprClass.Value;
1053                         
1054                         return this;
1055                 }
1056
1057                 public override void Emit (EmitContext ec)
1058                 {
1059                         //
1060                         // Invocation on delegates call the virtual Invoke member
1061                         // so we are always `instance' calls
1062                         //
1063                         Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
1064                 }
1065
1066                 public override void EmitStatement (EmitContext ec)
1067                 {
1068                         Emit (ec);
1069                         // 
1070                         // Pop the return value if there is one
1071                         //
1072                         if (method is MethodInfo){
1073                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
1074                                         ec.ig.Emit (OpCodes.Pop);
1075                         }
1076                 }
1077
1078         }
1079 }