This error checking rule was never applied due to a reduce/reduce conflict.
[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 == "return") {
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 (TypeContainer container)
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 (!container.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 (container))
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 (!container.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 (container))
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 (container, 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 (container, 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 (container, end_parameters),
388                                 end_param_types);
389
390                         return true;
391                 }
392
393                 public override void Emit (TypeContainer tc)
394                 {
395                         if (OptAttributes != null) {
396                                 EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
397                                 Parameters.LabelParameters (ec, InvokeBuilder, Location);
398                                 OptAttributes.Emit (ec, this);
399                         }
400
401                         base.Emit (tc);
402                 }
403
404                 protected override string[] ValidAttributeTargets {
405                         get {
406                                 return attribute_targets;
407                         }
408                 }
409
410                 //TODO: duplicate
411                 protected override bool VerifyClsCompliance (DeclSpace ds)
412                 {
413                         if (!base.VerifyClsCompliance (ds)) {
414                                 return false;
415                         }
416
417                         AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
418
419                         if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
420                                 Report.Error_T (3002, Location, GetSignatureForError ());
421                         }
422                         return true;
423                 }
424
425                 /// <summary>
426                 ///  Verifies whether the method in question is compatible with the delegate
427                 ///  Returns the method itself if okay and null if not.
428                 /// </summary>
429                 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
430                                                        Location loc)
431                 {
432                         Expression ml = Expression.MemberLookup (
433                                 ec, delegate_type, "Invoke", loc);
434
435                         if (!(ml is MethodGroupExpr)) {
436                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
437                                 return null;
438                         }
439
440                         MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
441
442                         ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
443
444                         if (!((MethodGroupExpr) ml).HasTypeArguments &&
445                             !Invocation.InferTypeArguments (ec, invoke_pd, ref mb))
446                                 return null;
447
448                         ParameterData pd = Invocation.GetParameterData (mb);
449                         int pd_count = pd.Count;
450
451                         if (invoke_pd.Count != pd_count)
452                                 return null;
453
454                         for (int i = pd_count; i > 0; ) {
455                                 i--;
456
457                                 if (invoke_pd.ParameterType (i) == pd.ParameterType (i) &&
458                                     invoke_pd.ParameterModifier (i) == pd.ParameterModifier (i))
459                                         continue;
460                                 else {
461                                         return null;
462                                 }
463                         }
464
465                         if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
466                                 return mb;
467                         else
468                                 return null;
469                 }
470
471                 // <summary>
472                 //  Verifies whether the invocation arguments are compatible with the
473                 //  delegate's target method
474                 // </summary>
475                 public static bool VerifyApplicability (EmitContext ec,
476                                                         Type delegate_type,
477                                                         ArrayList args,
478                                                         Location loc)
479                 {
480                         int arg_count;
481
482                         if (args == null)
483                                 arg_count = 0;
484                         else
485                                 arg_count = args.Count;
486
487                         Expression ml = Expression.MemberLookup (
488                                 ec, delegate_type, "Invoke", loc);
489
490                         if (!(ml is MethodGroupExpr)) {
491                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
492                                 return false;
493                         }
494                         
495                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
496                         ParameterData pd = Invocation.GetParameterData (mb);
497
498                         int pd_count = pd.Count;
499
500                         bool params_method = (pd_count != 0) &&
501                                 (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
502
503                         if (!params_method && pd_count != arg_count) {
504                                 Report.Error (1593, loc,
505                                               "Delegate '" + delegate_type.ToString ()
506                                               + "' does not take '" + arg_count + "' arguments");
507                                 return false;
508                         }
509
510                         //
511                         // Consider the case:
512                         //   delegate void FOO(param object[] args);
513                         //   FOO f = new FOO(...);
514                         //   f(new object[] {1, 2, 3});
515                         //
516                         // This should be treated like f(1,2,3).  This is done by ignoring the 
517                         // 'param' modifier for that invocation.  If that fails, then the
518                         // 'param' modifier is considered.
519                         //
520                         // One issue is that 'VerifyArgumentsCompat' modifies the elements of
521                         // the 'args' array.  However, the modifications appear idempotent.
522                         // Normal 'Invocation's also have the same behaviour, implicitly.
523                         //
524
525                         bool ans = false;
526                         if (arg_count == pd_count)
527                                 ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, false, delegate_type, loc);
528                         if (!ans && params_method)
529                                 ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, true,  delegate_type, loc);
530                         return ans;
531                 }
532                 
533                 /// <summary>
534                 ///  Verifies whether the delegate in question is compatible with this one in
535                 ///  order to determine if instantiation from the same is possible.
536                 /// </summary>
537                 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
538                 {
539                         Expression ml = Expression.MemberLookup (
540                                 ec, delegate_type, "Invoke", loc);
541                         
542                         if (!(ml is MethodGroupExpr)) {
543                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
544                                 return false;
545                         }
546                         
547                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
548                         ParameterData pd = Invocation.GetParameterData (mb);
549
550                         Expression probe_ml = Expression.MemberLookup (
551                                 ec, delegate_type, "Invoke", loc);
552                         
553                         if (!(probe_ml is MethodGroupExpr)) {
554                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
555                                 return false;
556                         }
557                         
558                         MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
559                         ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
560                         
561                         if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
562                                 return false;
563
564                         if (pd.Count != probe_pd.Count)
565                                 return false;
566
567                         for (int i = pd.Count; i > 0; ) {
568                                 i--;
569
570                                 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
571                                     pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
572                                         return false;
573                         }
574                         
575                         return true;
576                 }
577                 
578                 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
579                 {
580                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
581                         
582                         sb.Append (" " + del_type.ToString ());
583                         sb.Append (" (");
584
585                         int length = pd.Count;
586                         
587                         for (int i = length; i > 0; ) {
588                                 i--;
589
590                                 sb.Append (pd.ParameterDesc (length - i - 1));
591                                 if (i != 0)
592                                         sb.Append (", ");
593                         }
594                         
595                         sb.Append (")");
596                         return sb.ToString ();
597                         
598                 }
599                 
600                 // Hack around System.Reflection as found everywhere else
601                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
602                                                         MemberFilter filter, object criteria)
603                 {
604                         ArrayList members = new ArrayList ();
605
606                         if ((mt & MemberTypes.Method) != 0) {
607                                 if (ConstructorBuilder != null)
608                                 if (filter (ConstructorBuilder, criteria))
609                                         members.Add (ConstructorBuilder);
610
611                                 if (InvokeBuilder != null)
612                                 if (filter (InvokeBuilder, criteria))
613                                         members.Add (InvokeBuilder);
614
615                                 if (BeginInvokeBuilder != null)
616                                 if (filter (BeginInvokeBuilder, criteria))
617                                         members.Add (BeginInvokeBuilder);
618
619                                 if (EndInvokeBuilder != null)
620                                 if (filter (EndInvokeBuilder, criteria))
621                                         members.Add (EndInvokeBuilder);
622                         }
623
624                         return new MemberList (members);
625                 }
626
627                 public override MemberCache MemberCache {
628                         get {
629                                 return null;
630                         }
631                 }
632
633                 public Expression InstanceExpression {
634                         get {
635                                 return instance_expr;
636                         }
637                         set {
638                                 instance_expr = value;
639                         }
640                 }
641
642                 public MethodBase TargetMethod {
643                         get {
644                                 return delegate_method;
645                         }
646                         set {
647                                 delegate_method = value;
648                         }
649                 }
650
651                 public Type TargetReturnType {
652                         get {
653                                 return ret_type;
654                         }
655                 }
656
657                 public Type [] ParameterTypes {
658                         get {
659                                 return param_types;
660                         }
661                 }
662
663                 public override AttributeTargets AttributeTargets {
664                         get {
665                                 return AttributeTargets.Delegate | AttributeTargets.ReturnValue;
666                         }
667                 }
668
669                 protected override void VerifyObsoleteAttribute()
670                 {
671                         CheckUsageOfObsoleteAttribute (ret_type);
672
673                         foreach (Type type in param_types) {
674                                 CheckUsageOfObsoleteAttribute (type);
675                         }
676                 }
677         }
678
679         //
680         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
681         //
682         public abstract class DelegateCreation : Expression {
683                 protected MethodBase constructor_method;
684                 protected MethodBase delegate_method;
685                 protected Expression delegate_instance_expr;
686
687                 public DelegateCreation () {}
688
689                 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
690                 {
691                         string method_desc;
692
693                         MethodBase candidate = mg.Methods [0];
694                         if (mg.Methods.Length > 1)
695                                 method_desc = candidate.Name;
696                         else
697                                 method_desc = Invocation.FullMethodDesc (candidate);
698
699                         Expression invoke_method = Expression.MemberLookup (
700                                 ec, type, "Invoke", MemberTypes.Method,
701                                 Expression.AllBindingFlags, loc);
702                         MethodBase method = ((MethodGroupExpr) invoke_method).Methods [0];
703                         ParameterData param = Invocation.GetParameterData (method);
704                         string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
705
706                         if (!mg.HasTypeArguments &&
707                             !Invocation.InferTypeArguments (ec, param, ref candidate))
708                                 Report.Error (411, loc, "The type arguments for " +
709                                               "method `{0}' cannot be infered from " +
710                                               "the usage. Try specifying the type " +
711                                               "arguments explicitly.", method_desc);
712                         else
713                                 Report.Error (123, loc, "Method '{0}' does not " +
714                                               "match delegate '{1}'", method_desc,
715                                               delegate_desc);
716                 }
717                 
718                 public override void Emit (EmitContext ec)
719                 {
720                         if (delegate_instance_expr == null ||
721                             delegate_method.IsStatic)
722                                 ec.ig.Emit (OpCodes.Ldnull);
723                         else
724                                 delegate_instance_expr.Emit (ec);
725                         
726                         if (delegate_method.IsVirtual) {
727                                 ec.ig.Emit (OpCodes.Dup);
728                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
729                         } else
730                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
731                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
732                 }
733
734                 protected bool ResolveConstructorMethod (EmitContext ec)
735                 {
736                         Expression ml = Expression.MemberLookup (
737                                 ec, type, ".ctor", loc);
738
739                         if (!(ml is MethodGroupExpr)) {
740                                 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
741                                 return false;
742                         }
743
744                         constructor_method = ((MethodGroupExpr) ml).Methods [0];
745                         return true;
746                 }
747
748                 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
749                 {
750                                 foreach (MethodInfo mi in mg.Methods){
751                                         delegate_method = Delegate.VerifyMethod (
752                                                 ec, type, mi, loc);
753
754                                         if (delegate_method != null)
755                                                 break;
756                                 }
757                                         
758                                 if (delegate_method == null) {
759                                         Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
760                                         return null;
761                                 }
762
763                                 //
764                                 // Check safe/unsafe of the delegate
765                                 //
766                                 if (!ec.InUnsafe){
767                                         ParameterData param = Invocation.GetParameterData (delegate_method);
768                                         int count = param.Count;
769                                         
770                                         for (int i = 0; i < count; i++){
771                                                 if (param.ParameterType (i).IsPointer){
772                                                         Expression.UnsafeError (loc);
773                                                         return null;
774                                                 }
775                                         }
776                                 }
777                                                 
778                                 if (mg.InstanceExpression != null)
779                                         delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
780                                 else {
781                                         if (ec.IsStatic){
782                                                 if (!delegate_method.IsStatic){
783                                                         Report.Error (120, loc,
784                                                                       "An object reference is required for the non-static method " +
785                                                                       delegate_method.Name);
786                                                         return null;
787                                                 }
788                                                 delegate_instance_expr = null;
789                                         } else
790                                                 delegate_instance_expr = ec.GetThis (loc);
791                                 }
792
793                                 if (delegate_instance_expr != null)
794                                         if (delegate_instance_expr.Type.IsValueType)
795                                                 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
796                                 
797                                 eclass = ExprClass.Value;
798                                 return this;
799                         }
800         }
801
802         //
803         // Created from the conversion code
804         //
805         public class ImplicitDelegateCreation : DelegateCreation {
806
807                 ImplicitDelegateCreation (Type t, Location l)
808                 {
809                         type = t;
810                         loc = l;
811                 }
812
813                 public override Expression DoResolve (EmitContext ec)
814                 {
815                         return this;
816                 }
817                 
818                 static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
819                 {
820                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
821                         if (d.ResolveConstructorMethod (ec))
822                                 return d.ResolveMethodGroupExpr (ec, mge);
823                         else
824                                 return null;
825                 }
826         }
827         
828         //
829         // A delegate-creation-expression, invoked from the `New' class 
830         //
831         public class NewDelegate : DelegateCreation {
832                 public ArrayList Arguments;
833
834                 //
835                 // This constructor is invoked from the `New' expression
836                 //
837                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
838                 {
839                         this.type = type;
840                         this.Arguments = Arguments;
841                         this.loc  = loc; 
842                 }
843
844                 public override Expression DoResolve (EmitContext ec)
845                 {
846                         if (Arguments == null || Arguments.Count != 1) {
847                                 Report.Error (149, loc,
848                                               "Method name expected");
849                                 return null;
850                         }
851
852                         if (!ResolveConstructorMethod (ec))
853                                 return null;
854
855                         Argument a = (Argument) Arguments [0];
856                         
857                         Expression invoke_method = Expression.MemberLookup (
858                                 ec, type, "Invoke", MemberTypes.Method,
859                                 Expression.AllBindingFlags, loc);
860
861                         if (invoke_method == null) {
862                                 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
863                                 return null;
864                         }
865
866                         if (!a.ResolveMethodGroup (ec, loc))
867                                 return null;
868                         
869                         Expression e = a.Expr;
870
871                         MethodGroupExpr mg = e as MethodGroupExpr;
872                         if (mg != null)
873                                 return ResolveMethodGroupExpr (ec, mg);
874
875                         Type e_type = e.Type;
876
877                         if (!TypeManager.IsDelegateType (e_type)) {
878                                 e.Error_UnexpectedKind ("method");
879                                 return null;
880                         }
881
882                         // This is what MS' compiler reports. We could always choose
883                         // to be more verbose and actually give delegate-level specifics
884                         
885                         if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
886                                 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
887                                               "to type '" + type + "'");
888                                 return null;
889                         }
890                                 
891                         delegate_instance_expr = e;
892                         delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
893                         
894                         eclass = ExprClass.Value;
895                         return this;
896                 }
897                 
898                 public override void Emit (EmitContext ec)
899                 {
900                         if (delegate_instance_expr == null || delegate_method.IsStatic)
901                                 ec.ig.Emit (OpCodes.Ldnull);
902                         else
903                                 delegate_instance_expr.Emit (ec);
904                         
905                         if (delegate_method.IsVirtual) {
906                                 ec.ig.Emit (OpCodes.Dup);
907                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
908                         } else
909                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
910                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
911                 }
912         }
913
914         public class DelegateInvocation : ExpressionStatement {
915
916                 public Expression InstanceExpr;
917                 public ArrayList  Arguments;
918
919                 MethodBase method;
920                 
921                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
922                 {
923                         this.InstanceExpr = instance_expr;
924                         this.Arguments = args;
925                         this.loc = loc;
926                 }
927
928                 public override Expression DoResolve (EmitContext ec)
929                 {
930                         if (InstanceExpr is EventExpr) {
931                                 
932                                 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
933                                 
934                                 Expression ml = MemberLookup (
935                                         ec, ec.ContainerType, ei.Name,
936                                         MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
937
938                                 if (ml == null) {
939                                         //
940                                         // If this is the case, then the Event does not belong 
941                                         // to this Type and so, according to the spec
942                                         // cannot be accessed directly
943                                         //
944                                         // Note that target will not appear as an EventExpr
945                                         // in the case it is being referenced within the same type container;
946                                         // it will appear as a FieldExpr in that case.
947                                         //
948                                         
949                                         Assign.error70 (ei, loc);
950                                         return null;
951                                 }
952                         }
953                         
954                         
955                         Type del_type = InstanceExpr.Type;
956                         if (del_type == null)
957                                 return null;
958                         
959                         if (Arguments != null){
960                                 foreach (Argument a in Arguments){
961                                         if (!a.Resolve (ec, loc))
962                                                 return null;
963                                 }
964                         }
965                         
966                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
967                                 return null;
968
969                         Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
970                         if (!(lookup is MethodGroupExpr)) {
971                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
972                                 return null;
973                         }
974                         
975                         method = ((MethodGroupExpr) lookup).Methods [0];
976                         type = ((MethodInfo) method).ReturnType;
977                         eclass = ExprClass.Value;
978                         
979                         return this;
980                 }
981
982                 public override void Emit (EmitContext ec)
983                 {
984                         //
985                         // Invocation on delegates call the virtual Invoke member
986                         // so we are always `instance' calls
987                         //
988                         Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
989                 }
990
991                 public override void EmitStatement (EmitContext ec)
992                 {
993                         Emit (ec);
994                         // 
995                         // Pop the return value if there is one
996                         //
997                         if (method is MethodInfo){
998                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
999                                         ec.ig.Emit (OpCodes.Pop);
1000                         }
1001                 }
1002
1003         }
1004 }