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