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