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