2008-04-28 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 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 //
11 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
12 // Copyright 2003-2008 Novell, Inc (http://www.ximian.com)
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                 FullNamedExpression 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, FullNamedExpression 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 CreateExpressionTree (EmitContext ec)
692                 {
693                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
694
695                         ArrayList args = new ArrayList (3);
696                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
697                         args.Add (new Argument (new NullLiteral (loc)));
698                         args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
699                         Expression e = new Invocation (ma, args).Resolve (ec);
700                         if (e == null)
701                                 return null;
702
703                         e = Convert.ExplicitConversion (ec, e, type, loc);
704                         if (e == null)
705                                 return null;
706
707                         return e.CreateExpressionTree (ec);
708                 }
709
710                 public override Expression DoResolve (EmitContext ec)
711                 {
712                         constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
713
714                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
715                         method_group.DelegateType = type;
716                         method_group.CustomErrorHandler = this;
717
718                         ArrayList arguments = CreateDelegateMethodArguments (invoke_method);
719                         method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
720                         if (method_group == null)
721                                 return null;
722
723                         delegate_method = (MethodInfo) method_group;
724                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
725                         if (emg != null) {
726                                 delegate_instance_expression = emg.ExtensionExpression;
727                                 Type e_type = delegate_instance_expression.Type;
728                                 if (TypeManager.IsValueType (e_type)) {
729                                         Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
730                                                 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
731                                 }
732                         }
733
734                         Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
735                         Expression ret_expr = new TypeExpression (rt, loc);
736                         if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
737                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
738                         }
739
740                         DoResolveInstanceExpression (ec);
741                         eclass = ExprClass.Value;
742                         return this;
743                 }
744
745                 void DoResolveInstanceExpression (EmitContext ec)
746                 {
747                         //
748                         // Argument is another delegate
749                         //
750                         if (delegate_instance_expression != null)
751                                 return;
752                         
753                         if (method_group.InstanceExpression != null)
754                                 delegate_instance_expression = method_group.InstanceExpression;
755                         else if (!delegate_method.IsStatic && !ec.IsStatic)
756                                 delegate_instance_expression = ec.GetThis (loc);
757
758                         if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
759                                 delegate_instance_expression = new BoxedCast (
760                                         delegate_instance_expression, TypeManager.object_type);
761                 }
762                 
763                 public override void Emit (EmitContext ec)
764                 {
765                         if (delegate_instance_expression == null)
766                                 ec.ig.Emit (OpCodes.Ldnull);
767                         else
768                                 delegate_instance_expression.Emit (ec);
769
770                         if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
771                                 ec.ig.Emit (OpCodes.Dup);
772                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
773                         } else
774                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
775                         ec.ig.Emit (OpCodes.Newobj, constructor_method);
776                 }
777
778                 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
779                 {
780                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
781                         string member_name = delegate_instance_expression != null ?
782                                 Delegate.FullDelegateDesc (method) :
783                                 TypeManager.GetFullNameSignature (method);
784
785                         Report.SymbolRelatedToPreviousError (type);
786                         Report.SymbolRelatedToPreviousError (method);
787                         if (RootContext.Version == LanguageVersion.ISO_1) {
788                                 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",
789                                         TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
790                                         TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
791                                 return;
792                         }
793                         if (return_type == null) {
794                                 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
795                                         member_name, Delegate.FullDelegateDesc (invoke_method));
796                                 return;
797                         }
798
799                         Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
800                                 return_type.GetSignatureForError (), member_name,
801                                 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
802                 }
803
804                 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
805                 {
806                         if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
807                                 return null;
808
809                         foreach (MethodInfo mi in mg.Methods){
810                                 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
811                                 if (mb != null)
812                                         return mb;
813                         }
814                         return null;
815                 }
816
817                 #region IErrorHandler Members
818
819                 public bool NoExactMatch (EmitContext ec, MethodBase method)
820                 {
821                         if (TypeManager.IsGenericMethod (method))
822                                 return false;
823
824                         Error_ConversionFailed (ec, method, null);
825                         return true;
826                 }
827
828                 #endregion
829         }
830
831         //
832         // Created from the conversion code
833         //
834         public class ImplicitDelegateCreation : DelegateCreation
835         {
836                 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
837                 {
838                         type = t;
839                         this.method_group = mg;
840                         loc = l;
841                 }
842
843                 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
844                                                  Type target_type, Location loc)
845                 {
846                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
847                         return d.DoResolve (ec);
848                 }
849         }
850         
851         //
852         // A delegate-creation-expression, invoked from the `New' class 
853         //
854         public class NewDelegate : DelegateCreation
855         {
856                 public ArrayList Arguments;
857
858                 //
859                 // This constructor is invoked from the `New' expression
860                 //
861                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
862                 {
863                         this.type = type;
864                         this.Arguments = Arguments;
865                         this.loc  = loc; 
866                 }
867
868                 public override Expression DoResolve (EmitContext ec)
869                 {
870                         if (Arguments == null) {
871                                 Error_InvalidDelegateArgument ();
872                                 return null;
873                         }
874
875                         Argument a = (Argument) Arguments [0];
876                         if (!a.ResolveMethodGroup (ec))
877                                 return null;
878                         
879                         Expression e = a.Expr;
880                         if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
881                                 e = ((AnonymousMethodExpression) e).Compatible (ec, type);
882                                 if (e == null)
883                                         return null;
884                                 return e.Resolve (ec);
885                         }
886
887                         method_group = e as MethodGroupExpr;
888                         if (method_group == null) {
889                                 if (!TypeManager.IsDelegateType (e.Type)) {
890                                         Report.Error (149, loc, "Method name expected");
891                                         return null;
892                                 }
893
894                                 //
895                                 // An argument is not a method but another delegate
896                                 //
897                                 delegate_instance_expression = e;
898                                 method_group = new MethodGroupExpr (new MemberInfo [] { 
899                                         Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
900                         }
901
902                         if (base.DoResolve (ec) == null)
903                                 return null;
904
905                         if (TypeManager.IsNullableType (method_group.DeclaringType)) {
906                                 Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
907                                         TypeManager.GetFullNameSignature (delegate_method));
908                         }
909
910                         if (Invocation.IsMethodExcluded (delegate_method)) {
911                                 Report.SymbolRelatedToPreviousError (delegate_method);
912                                 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
913                                         TypeManager.CSharpSignature (delegate_method));
914                         }
915
916                         return this;
917                 }
918
919                 void Error_InvalidDelegateArgument ()
920                 {
921                         Report.Error (149, loc, "Method name expected");
922                 }
923         }
924
925         public class DelegateInvocation : ExpressionStatement {
926
927                 readonly Expression InstanceExpr;
928                 readonly ArrayList  Arguments;
929
930                 MethodBase method;
931                 
932                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
933                 {
934                         this.InstanceExpr = instance_expr;
935                         this.Arguments = args;
936                         this.loc = loc;
937                 }
938
939                 public override Expression DoResolve (EmitContext ec)
940                 {
941                         if (InstanceExpr is EventExpr) {
942                                 ((EventExpr) InstanceExpr).Error_CannotAssign ();
943                                 return null;
944                         }
945                         
946                         Type del_type = InstanceExpr.Type;
947                         if (del_type == null)
948                                 return null;
949                         
950                         if (Arguments != null){
951                                 foreach (Argument a in Arguments){
952                                         if (!a.Resolve (ec, loc))
953                                                 return null;
954                                 }
955                         }
956                         
957                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
958                                 return null;
959
960                         method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
961                         type = ((MethodInfo) method).ReturnType;
962                         type = TypeManager.TypeToCoreType (type);
963                         eclass = ExprClass.Value;
964                         
965                         return this;
966                 }
967
968                 public override void Emit (EmitContext ec)
969                 {
970                         //
971                         // Invocation on delegates call the virtual Invoke member
972                         // so we are always `instance' calls
973                         //
974                         Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
975                 }
976
977                 public override void EmitStatement (EmitContext ec)
978                 {
979                         Emit (ec);
980                         // 
981                         // Pop the return value if there is one
982                         //
983                         if (method is MethodInfo){
984                                 Type ret = ((MethodInfo)method).ReturnType;
985                                 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
986                                         ec.ig.Emit (OpCodes.Pop);
987                         }
988                 }
989
990         }
991 }