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