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