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