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