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