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