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