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