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