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