2008-06-23 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 (!TypeManager.IsReferenceType (a_type))
459                                 return false;
460
461                         return Convert.ImplicitReferenceConversionExists (a, b);
462                 }
463                 
464                 /// <summary>
465                 ///  Verifies whether the method in question is compatible with the delegate
466                 ///  Returns the method itself if okay and null if not.
467                 /// </summary>
468                 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
469                                                        MethodGroupExpr old_mg, MethodBase mb,
470                                                        Location loc)
471                 {
472                         MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
473                         if (invoke_mb == null)
474                                 return null;
475
476                         ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
477
478 #if GMCS_SOURCE
479                         if (old_mg.type_arguments == null &&
480                             !TypeManager.InferTypeArguments (invoke_pd, ref mb))
481                                 return null;
482 #endif
483
484                         ParameterData pd = TypeManager.GetParameterData (mb);
485
486                         if (invoke_pd.Count != pd.Count)
487                                 return null;
488
489                         for (int i = pd.Count; i > 0; ) {
490                                 i--;
491
492                                 Type invoke_pd_type = invoke_pd.ParameterType (i);
493                                 Type pd_type = pd.ParameterType (i);
494                                 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
495                                 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
496
497                                 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
498                                 pd_type_mod &= ~Parameter.Modifier.PARAMS;
499
500                                 if (invoke_pd_type_mod != pd_type_mod)
501                                         return null;
502
503                                 if (invoke_pd_type == pd_type)
504                                         continue;
505
506                                 //if (!IsTypeCovariant (invoke_pd_type, pd_type))
507                                 //      return null;
508
509                                 if (RootContext.Version == LanguageVersion.ISO_1)
510                                         return null;
511                         }
512
513                         Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
514                         Type mb_retval = ((MethodInfo) mb).ReturnType;
515                         if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
516                                 return mb;
517
518                         //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
519                         //      return null;
520
521                         if (RootContext.Version == LanguageVersion.ISO_1) 
522                                 return null;
523
524                         return mb;
525                 }
526
527                 // <summary>
528                 //  Verifies whether the invocation arguments are compatible with the
529                 //  delegate's target method
530                 // </summary>
531                 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
532                                                         ArrayList args, Location loc)
533                 {
534                         int arg_count;
535
536                         if (args == null)
537                                 arg_count = 0;
538                         else
539                                 arg_count = args.Count;
540
541                         Expression ml = Expression.MemberLookup (
542                                 ec.ContainerType, delegate_type, "Invoke", loc);
543
544                         MethodGroupExpr me = ml as MethodGroupExpr;
545                         if (me == null) {
546                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
547                                 return false;
548                         }
549                         
550                         MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
551                         ParameterData pd = TypeManager.GetParameterData (mb);
552
553                         int pd_count = pd.Count;
554
555                         bool params_method = pd.HasParams;
556                         bool is_params_applicable = false;
557                         me.DelegateType = delegate_type;
558                         bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
559
560                         if (!is_applicable && !params_method && arg_count != pd_count) {
561                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
562                                         TypeManager.CSharpName (delegate_type), arg_count.ToString ());
563                                 return false;
564                         }
565
566                         return me.VerifyArgumentsCompat (
567                                         ec, ref args, arg_count, mb, 
568                                         is_params_applicable || (!is_applicable && params_method),
569                                         false, loc);
570                 }
571                 
572                 public static string FullDelegateDesc (MethodBase invoke_method)
573                 {
574                         return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
575                 }
576                 
577                 public override MemberCache MemberCache {
578                         get {
579                                 return member_cache;
580                         }
581                 }
582
583                 public Expression InstanceExpression {
584                         get {
585                                 return instance_expr;
586                         }
587                         set {
588                                 instance_expr = value;
589                         }
590                 }
591
592                 public MethodBase TargetMethod {
593                         get {
594                                 return delegate_method;
595                         }
596                         set {
597                                 delegate_method = value;
598                         }
599                 }
600
601                 public Type TargetReturnType {
602                         get {
603                                 return ret_type;
604                         }
605                 }
606
607                 public override AttributeTargets AttributeTargets {
608                         get {
609                                 return AttributeTargets.Delegate;
610                         }
611                 }
612
613                 //
614                 //   Represents header string for documentation comment.
615                 //
616                 public override string DocCommentHeader {
617                         get { return "T:"; }
618                 }
619
620                 #region IMemberContainer Members
621
622                 string IMemberContainer.Name
623                 {
624                         get { throw new NotImplementedException (); }
625                 }
626
627                 Type IMemberContainer.Type
628                 {
629                         get { throw new NotImplementedException (); }
630                 }
631
632                 MemberCache IMemberContainer.BaseCache
633                 {
634                         get { throw new NotImplementedException (); }
635                 }
636
637                 bool IMemberContainer.IsInterface {
638                         get {
639                                 return false;
640                         }
641                 }
642
643                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
644                 {
645                         throw new NotImplementedException ();
646                 }
647
648                 #endregion
649         }
650
651         //
652         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
653         //
654         public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
655         {
656                 protected ConstructorInfo constructor_method;
657                 protected MethodInfo delegate_method;
658                 // We keep this to handle IsBase only
659                 protected MethodGroupExpr method_group;
660                 protected Expression delegate_instance_expression;
661
662                 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
663                 {
664                         ParameterData pd = TypeManager.GetParameterData (invoke_method);
665                         ArrayList delegate_arguments = new ArrayList (pd.Count);
666                         for (int i = 0; i < pd.Count; ++i) {
667                                 Argument.AType atype_modifier;
668                                 Type atype = pd.Types [i];
669                                 switch (pd.ParameterModifier (i)) {
670                                         case Parameter.Modifier.REF:
671                                                 atype_modifier = Argument.AType.Ref;
672                                                 atype = atype.GetElementType ();
673                                                 break;
674                                         case Parameter.Modifier.OUT:
675                                                 atype_modifier = Argument.AType.Out;
676                                                 atype = atype.GetElementType ();
677                                                 break;
678                                         case Parameter.Modifier.ARGLIST:
679                                                 // __arglist is not valid
680                                                 throw new InternalErrorException ("__arglist modifier");
681                                         default:
682                                                 atype_modifier = Argument.AType.Expression;
683                                                 break;
684                                 }
685                                 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
686                         }
687                         return delegate_arguments;
688                 }
689
690                 public override Expression CreateExpressionTree (EmitContext ec)
691                 {
692                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
693
694                         ArrayList args = new ArrayList (3);
695                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
696                         args.Add (new Argument (new NullLiteral (loc)));
697                         args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
698                         Expression e = new Invocation (ma, args).Resolve (ec);
699                         if (e == null)
700                                 return null;
701
702                         e = Convert.ExplicitConversion (ec, e, type, loc);
703                         if (e == null)
704                                 return null;
705
706                         return e.CreateExpressionTree (ec);
707                 }
708
709                 public override Expression DoResolve (EmitContext ec)
710                 {
711                         constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
712
713                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
714                         method_group.DelegateType = type;
715                         method_group.CustomErrorHandler = this;
716
717                         ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
718                         method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
719                         if (method_group == null)
720                                 return null;
721
722                         delegate_method = (MethodInfo) method_group;
723                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
724                         if (emg != null) {
725                                 delegate_instance_expression = emg.ExtensionExpression;
726                                 Type e_type = delegate_instance_expression.Type;
727                                 if (TypeManager.IsValueType (e_type)) {
728                                         Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
729                                                 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
730                                 }
731                         }
732
733                         Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
734                         Expression ret_expr = new TypeExpression (rt, loc);
735                         if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
736                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
737                         }
738
739                         DoResolveInstanceExpression (ec);
740                         eclass = ExprClass.Value;
741                         return this;
742                 }
743
744                 void DoResolveInstanceExpression (EmitContext ec)
745                 {
746                         //
747                         // Argument is another delegate
748                         //
749                         if (delegate_instance_expression != null)
750                                 return;
751                         
752                         if (method_group.InstanceExpression != null)
753                                 delegate_instance_expression = method_group.InstanceExpression;
754                         else if (!delegate_method.IsStatic && !ec.IsStatic)
755                                 delegate_instance_expression = ec.GetThis (loc);
756
757                         if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
758                                 delegate_instance_expression = new BoxedCast (
759                                         delegate_instance_expression, TypeManager.object_type);
760                 }
761                 
762                 public override void Emit (EmitContext ec)
763                 {
764                         if (delegate_instance_expression == null)
765                                 ec.ig.Emit (OpCodes.Ldnull);
766                         else
767                                 delegate_instance_expression.Emit (ec);
768
769                         if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
770                                 ec.ig.Emit (OpCodes.Dup);
771                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
772                         } else
773                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
774                         ec.ig.Emit (OpCodes.Newobj, constructor_method);
775                 }
776
777                 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
778                 {
779                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
780                         string member_name = delegate_instance_expression != null ?
781                                 Delegate.FullDelegateDesc (method) :
782                                 TypeManager.GetFullNameSignature (method);
783
784                         Report.SymbolRelatedToPreviousError (type);
785                         Report.SymbolRelatedToPreviousError (method);
786                         if (RootContext.Version == LanguageVersion.ISO_1) {
787                                 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",
788                                         TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
789                                         TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
790                                 return;
791                         }
792                         if (return_type == null) {
793                                 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
794                                         member_name, Delegate.FullDelegateDesc (invoke_method));
795                                 return;
796                         }
797
798                         Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
799                                 return_type.GetSignatureForError (), member_name,
800                                 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
801                 }
802
803                 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
804                 {
805                         if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
806                                 return null;
807
808                         foreach (MethodInfo mi in mg.Methods){
809                                 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
810                                 if (mb != null)
811                                         return mb;
812                         }
813                         return null;
814                 }
815
816                 #region IErrorHandler Members
817
818                 public bool NoExactMatch (EmitContext ec, MethodBase method)
819                 {
820                         if (TypeManager.IsGenericMethod (method))
821                                 return false;
822
823                         Error_ConversionFailed (ec, method, null);
824                         return true;
825                 }
826
827                 #endregion
828         }
829
830         //
831         // Created from the conversion code
832         //
833         public class ImplicitDelegateCreation : DelegateCreation
834         {
835                 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
836                 {
837                         type = t;
838                         this.method_group = mg;
839                         loc = l;
840                 }
841
842                 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
843                                                  Type target_type, Location loc)
844                 {
845                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
846                         return d.DoResolve (ec);
847                 }
848         }
849         
850         //
851         // A delegate-creation-expression, invoked from the `New' class 
852         //
853         public class NewDelegate : DelegateCreation
854         {
855                 public ArrayList Arguments;
856
857                 //
858                 // This constructor is invoked from the `New' expression
859                 //
860                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
861                 {
862                         this.type = type;
863                         this.Arguments = Arguments;
864                         this.loc  = loc; 
865                 }
866
867                 public override Expression DoResolve (EmitContext ec)
868                 {
869                         if (Arguments == null) {
870                                 Error_InvalidDelegateArgument ();
871                                 return null;
872                         }
873
874                         Argument a = (Argument) Arguments [0];
875                         if (!a.ResolveMethodGroup (ec))
876                                 return null;
877                         
878                         Expression e = a.Expr;
879                         if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
880                                 return e;
881                         }
882
883                         method_group = e as MethodGroupExpr;
884                         if (method_group == null) {
885                                 if (!TypeManager.IsDelegateType (e.Type)) {
886                                         Report.Error (149, loc, "Method name expected");
887                                         return null;
888                                 }
889
890                                 //
891                                 // An argument is not a method but another delegate
892                                 //
893                                 delegate_instance_expression = e;
894                                 method_group = new MethodGroupExpr (new MemberInfo [] { 
895                                         Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
896                         }
897
898                         if (base.DoResolve (ec) == null)
899                                 return null;
900
901                         if (TypeManager.IsNullableType (method_group.DeclaringType)) {
902                                 Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
903                                         TypeManager.GetFullNameSignature (delegate_method));
904                         }
905
906                         if (Invocation.IsMethodExcluded (delegate_method)) {
907                                 Report.SymbolRelatedToPreviousError (delegate_method);
908                                 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
909                                         TypeManager.CSharpSignature (delegate_method));
910                         }
911
912                         return this;
913                 }
914
915                 void Error_InvalidDelegateArgument ()
916                 {
917                         Report.Error (149, loc, "Method name expected");
918                 }
919         }
920
921         public class DelegateInvocation : ExpressionStatement {
922
923                 readonly Expression InstanceExpr;
924                 readonly ArrayList  Arguments;
925
926                 MethodInfo method;
927                 
928                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
929                 {
930                         this.InstanceExpr = instance_expr;
931                         this.Arguments = args;
932                         this.loc = loc;
933                 }
934                 
935                 public override Expression CreateExpressionTree (EmitContext ec)
936                 {
937                         ArrayList args;
938                         if (Arguments == null)
939                                 args = new ArrayList (1);
940                         else
941                                 args = new ArrayList (Arguments.Count + 1);
942
943                         args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
944                         if (Arguments != null) {
945                                 foreach (Argument a in Arguments)
946                                         args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
947                         }
948
949                         return CreateExpressionFactoryCall ("Invoke", args);
950                 }
951
952                 public override Expression DoResolve (EmitContext ec)
953                 {
954                         if (InstanceExpr is EventExpr) {
955                                 ((EventExpr) InstanceExpr).Error_CannotAssign ();
956                                 return null;
957                         }
958                         
959                         Type del_type = InstanceExpr.Type;
960                         if (del_type == null)
961                                 return null;
962                         
963                         if (Arguments != null){
964                                 foreach (Argument a in Arguments){
965                                         if (!a.Resolve (ec, loc))
966                                                 return null;
967                                 }
968                         }
969                         
970                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
971                                 return null;
972
973                         method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
974                         type = TypeManager.TypeToCoreType (method.ReturnType);
975                         eclass = ExprClass.Value;
976                         
977                         return this;
978                 }
979
980                 public override void Emit (EmitContext ec)
981                 {
982                         //
983                         // Invocation on delegates call the virtual Invoke member
984                         // so we are always `instance' calls
985                         //
986                         Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
987                 }
988
989                 public override void EmitStatement (EmitContext ec)
990                 {
991                         Emit (ec);
992                         // 
993                         // Pop the return value if there is one
994                         //
995                         if (type != TypeManager.void_type)
996                                 ec.ig.Emit (OpCodes.Pop);
997                 }
998
999                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1000                 {
1001                         method = storey.MutateGenericMethod (method);
1002
1003                         if (Arguments != null) {
1004                                 foreach (Argument a in Arguments) {
1005                                         a.Expr.MutateHoistedGenericType (storey);
1006                                 }
1007                         }
1008
1009                         InstanceExpr.MutateHoistedGenericType (storey);
1010                 }
1011         }
1012 }