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