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