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