2009-06-12 Bill Holmes <billholmes54@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 ParametersCompiled      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, ParametersCompiled 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, PredefinedAttributes pa)
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, pa);
77                                 return;
78                         }
79
80                         base.ApplyAttributeBuilder (a, cb, pa);
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 = 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 (IsGeneric) {
140                                 foreach (TypeParameter type_param in TypeParameters) {
141                                         if (!type_param.Resolve (this))
142                                                 return false;
143                                 }
144
145                                 foreach (TypeParameter type_param in TypeParameters) {
146                                         if (!type_param.DefineType (this))
147                                                 return false;
148                                 }
149                         }
150
151                         member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
152
153                         // FIXME: POSSIBLY make this static, as it is always constant
154                         //
155                         Type [] const_arg_types = new Type [2];
156                         const_arg_types [0] = TypeManager.object_type;
157                         const_arg_types [1] = TypeManager.intptr_type;
158
159                         const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
160                                 MethodAttributes.HideBySig | MethodAttributes.Public;
161
162                         ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
163                                                                             CallingConventions.Standard,
164                                                                             const_arg_types);
165
166                         ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
167                         ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
168                         //
169                         // HACK because System.Reflection.Emit is lame
170                         //
171                         IParameterData [] fixed_pars = new IParameterData [] {
172                                 new ParameterData ("object", Parameter.Modifier.NONE),
173                                 new ParameterData ("method", Parameter.Modifier.NONE)
174                         };
175
176                         AParametersCollection const_parameters = new ParametersImported (
177                                 fixed_pars,
178                                 new Type[] { TypeManager.object_type, TypeManager.intptr_type });
179                         
180                         TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
181                         member_cache.AddMember (ConstructorBuilder, this);
182                         
183                         ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
184
185                         //
186                         // Here the various methods like Invoke, BeginInvoke etc are defined
187                         //
188                         // First, call the `out of band' special method for
189                         // defining recursively any types we need:
190                         
191                         if (!Parameters.Resolve (this))
192                                 return false;
193
194                         //
195                         // Invoke method
196                         //
197
198                         // Check accessibility
199                         foreach (Type partype in Parameters.Types){
200                                 if (!IsAccessibleAs (partype)) {
201                                         Report.SymbolRelatedToPreviousError (partype);
202                                         Report.Error (59, Location,
203                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
204                                                       TypeManager.CSharpName (partype),
205                                                       GetSignatureForError ());
206                                         return false;
207                                 }
208                         }
209                         
210                         ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
211                         if (ReturnType == null)
212                                 return false;
213
214                         ret_type = ReturnType.Type;
215             
216                         if (!IsAccessibleAs (ret_type)) {
217                                 Report.SymbolRelatedToPreviousError (ret_type);
218                                 Report.Error (58, Location,
219                                               "Inconsistent accessibility: return type `" +
220                                               TypeManager.CSharpName (ret_type) + "' is less " +
221                                               "accessible than delegate `" + GetSignatureForError () + "'");
222                                 return false;
223                         }
224
225                         CheckProtectedModifier ();
226
227                         if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
228                                 Method.Error1599 (Location, ret_type);
229                                 return false;
230                         }
231
232                         TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
233
234                         //
235                         // We don't have to check any others because they are all
236                         // guaranteed to be accessible - they are standard types.
237                         //
238                         
239                         CallingConventions cc = Parameters.CallingConvention;
240
241                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
242                                                                   mattr,                     
243                                                                   cc,
244                                                                   ret_type,                  
245                                                                   Parameters.GetEmitTypes ());
246                         
247                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
248
249                         TypeManager.RegisterMethod (InvokeBuilder, Parameters);
250                         member_cache.AddMember (InvokeBuilder, this);
251
252                         if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
253                                 DefineAsyncMethods (cc);
254                         }
255
256                         return true;
257                 }
258
259                 void DefineAsyncMethods (CallingConventions cc)
260                 {
261                         //
262                         // BeginInvoke
263                         //
264                         ParametersCompiled async_parameters = ParametersCompiled.MergeGenerated (Parameters, false,
265                                 new Parameter [] {
266                                         new Parameter (null, "callback", Parameter.Modifier.NONE, null, Location),
267                                         new Parameter (null, "object", Parameter.Modifier.NONE, null, Location)
268                                 },
269                                 new Type [] {
270                                         TypeManager.asynccallback_type,
271                                         TypeManager.object_type
272                                 }
273                         );
274
275                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
276                                 mattr, cc, TypeManager.iasyncresult_type, async_parameters.GetEmitTypes ());
277
278                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
279                         TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
280                         member_cache.AddMember (BeginInvokeBuilder, this);
281
282                         //
283                         // EndInvoke is a bit more interesting, all the parameters labeled as
284                         // out or ref have to be duplicated here.
285                         //
286
287                         //
288                         // Define parameters, and count out/ref parameters
289                         //
290                         ParametersCompiled end_parameters;
291                         int out_params = 0;
292
293                         foreach (Parameter p in Parameters.FixedParameters) {
294                                 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
295                                         ++out_params;
296                         }
297
298                         if (out_params > 0) {
299                                 Type [] end_param_types = new Type [out_params];
300                                 Parameter[] end_params = new Parameter [out_params];
301
302                                 int param = 0;
303                                 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
304                                         Parameter p = Parameters [i];
305                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
306                                                 continue;
307
308                                         end_param_types [param] = Parameters.Types [i];
309                                         end_params [param] = p;
310                                         ++param;
311                                 }
312                                 end_parameters = ParametersCompiled.CreateFullyResolved (end_params, end_param_types);
313                         } else {
314                                 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
315                         }
316
317                         end_parameters = ParametersCompiled.MergeGenerated (end_parameters, false,
318                                 new Parameter (null, "result", Parameter.Modifier.NONE, null, Location), TypeManager.iasyncresult_type);
319
320                         //
321                         // Create method, define parameters, register parameters with type system
322                         //
323                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.GetEmitTypes ());
324                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
325
326                         end_parameters.ApplyAttributes (EndInvokeBuilder);
327                         TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
328                         member_cache.AddMember (EndInvokeBuilder, this);
329                 }
330
331                 public override void Emit ()
332                 {
333                         Parameters.ApplyAttributes (InvokeBuilder);
334
335                         if (BeginInvokeBuilder != null) {
336                                 ParametersCompiled p = (ParametersCompiled) TypeManager.GetParameterData (BeginInvokeBuilder);
337                                 p.ApplyAttributes (BeginInvokeBuilder);
338                         }
339
340                         if (OptAttributes != null) {
341                                 OptAttributes.Emit ();
342                         }
343
344                         base.Emit ();
345                 }
346
347                 protected override TypeAttributes TypeAttr {
348                         get {
349                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
350                                         TypeAttributes.Class | TypeAttributes.Sealed |
351                                         base.TypeAttr;
352                         }
353                 }
354
355                 public override string[] ValidAttributeTargets {
356                         get {
357                                 return attribute_targets;
358                         }
359                 }
360
361                 //TODO: duplicate
362                 protected override bool VerifyClsCompliance ()
363                 {
364                         if (!base.VerifyClsCompliance ()) {
365                                 return false;
366                         }
367
368                         Parameters.VerifyClsCompliance ();
369
370                         if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
371                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
372                                         GetSignatureForError ());
373                         }
374                         return true;
375                 }
376
377
378                 public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
379                 {
380                         Type dt = delegate_type;
381                         Type[] g_args = null;
382                         if (TypeManager.IsGenericType (delegate_type)) {
383                                 g_args = TypeManager.GetTypeArguments (delegate_type);
384                                 delegate_type = TypeManager.DropGenericTypeArguments (delegate_type);
385                         }
386
387                         Delegate d = TypeManager.LookupDelegate (delegate_type);
388                         if (d != null) {
389 #if GMCS_SOURCE
390                                 if (g_args != null)
391                                         return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
392 #endif
393                                 return d.ConstructorBuilder;
394                         }
395
396                         Expression ml = Expression.MemberLookup (container_type,
397                                 null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
398                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
399
400                         MethodGroupExpr mg = ml as MethodGroupExpr;
401                         if (mg == null) {
402                                 Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
403                                 // FIXME: null will cause a crash later
404                                 return null;
405                         }
406
407                         return (ConstructorInfo) mg.Methods[0];
408                 }
409
410                 //
411                 // Returns the MethodBase for "Invoke" from a delegate type, this is used
412                 // to extract the signature of a delegate.
413                 //
414                 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
415                 {
416                         Type dt = delegate_type;
417
418                         Type[] g_args = null;
419                         if (TypeManager.IsGenericType (delegate_type)) {
420                                 g_args = TypeManager.GetTypeArguments (delegate_type);
421                                 delegate_type = TypeManager.DropGenericTypeArguments (delegate_type);
422                         }
423
424                         Delegate d = TypeManager.LookupDelegate (delegate_type);
425                         MethodInfo invoke;
426                         if (d != null) {
427 #if GMCS_SOURCE
428                                 if (g_args != null) {
429                                         invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
430 #if MS_COMPATIBLE
431                                         ParametersCompiled p = (ParametersCompiled) d.Parameters.InflateTypes (g_args, g_args);
432                                         TypeManager.RegisterMethod (invoke, p);
433 #endif
434                                         return invoke;
435                                 }
436 #endif
437                                 return d.InvokeBuilder;
438                         }
439
440                         Expression ml = Expression.MemberLookup (container_type, null, dt,
441                                 "Invoke", Location.Null);
442
443                         MethodGroupExpr mg = ml as MethodGroupExpr;
444                         if (mg == null) {
445                                 Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
446                                 // FIXME: null will cause a crash later
447                                 return null;
448                         }
449
450                         invoke = (MethodInfo) mg.Methods[0];
451 #if MS_COMPATIBLE
452                         if (g_args != null) {
453                                 AParametersCollection p = TypeManager.GetParameterData (invoke);
454                                 p = p.InflateTypes (g_args, g_args);
455                                 TypeManager.RegisterMethod (invoke, p);
456                                 return invoke;
457                         }
458 #endif
459
460                         return invoke;
461                 }
462
463                 //
464                 // 15.2 Delegate compatibility
465                 //
466                 public static bool IsTypeCovariant (Expression a, Type b)
467                 {
468                         //
469                         // For each value parameter (a parameter with no ref or out modifier), an 
470                         // identity conversion or implicit reference conversion exists from the
471                         // parameter type in D to the corresponding parameter type in M
472                         //
473                         if (a.Type == b)
474                                 return true;
475
476                         if (RootContext.Version == LanguageVersion.ISO_1)
477                                 return false;
478
479                         return Convert.ImplicitReferenceConversionExists (a, b);
480                 }
481                 
482                 /// <summary>
483                 ///  Verifies whether the method in question is compatible with the delegate
484                 ///  Returns the method itself if okay and null if not.
485                 /// </summary>
486                 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
487                                                        MethodGroupExpr old_mg, MethodBase mb)
488                 {
489                         bool is_method_definition = TypeManager.IsGenericMethodDefinition (mb);
490                         
491                         MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
492                         if (invoke_mb == null)
493                                 return null;
494                                 
495                         if (is_method_definition)
496                                 invoke_mb = (MethodInfo) TypeManager.DropGenericMethodArguments (invoke_mb);
497
498                         AParametersCollection invoke_pd = TypeManager.GetParameterData (invoke_mb);
499
500 #if GMCS_SOURCE
501                         if (!is_method_definition && old_mg.type_arguments == null &&
502                             !TypeManager.InferTypeArguments (invoke_pd, ref mb))
503                                 return null;
504 #endif
505                         AParametersCollection pd = TypeManager.GetParameterData (mb);
506
507                         if (invoke_pd.Count != pd.Count)
508                                 return null;
509
510                         for (int i = pd.Count; i > 0; ) {
511                                 i--;
512
513                                 Type invoke_pd_type = invoke_pd.Types [i];
514                                 Type pd_type = pd.Types [i];
515                                 Parameter.Modifier invoke_pd_type_mod = invoke_pd.FixedParameters [i].ModFlags;
516                                 Parameter.Modifier pd_type_mod = pd.FixedParameters [i].ModFlags;
517
518                                 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
519                                 pd_type_mod &= ~Parameter.Modifier.PARAMS;
520
521                                 if (invoke_pd_type_mod != pd_type_mod)
522                                         return null;
523
524                                 if (TypeManager.IsEqual (invoke_pd_type, pd_type))
525                                         continue;
526
527                                 if (IsTypeCovariant (new EmptyExpression (invoke_pd_type), pd_type))
528                                         continue;
529
530                                 return null;
531                         }
532
533                         Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
534                         Type mb_retval = ((MethodInfo) mb).ReturnType;
535                         if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
536                                 return mb;
537
538                         //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
539                         //      return null;
540
541                         if (RootContext.Version == LanguageVersion.ISO_1) 
542                                 return null;
543
544                         return mb;
545                 }
546
547                 // <summary>
548                 //  Verifies whether the invocation arguments are compatible with the
549                 //  delegate's target method
550                 // </summary>
551                 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
552                                                         ArrayList args, Location loc)
553                 {
554                         int arg_count;
555
556                         if (args == null)
557                                 arg_count = 0;
558                         else
559                                 arg_count = args.Count;
560
561                         MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
562                         MethodGroupExpr me = new MethodGroupExpr (new MemberInfo [] { mb }, delegate_type, loc);
563                         
564                         AParametersCollection pd = TypeManager.GetParameterData (mb);
565
566                         int pd_count = pd.Count;
567
568                         bool params_method = pd.HasParams;
569                         bool is_params_applicable = false;
570                         bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
571
572                         if (!is_applicable && !params_method && arg_count != pd_count) {
573                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
574                                         TypeManager.CSharpName (delegate_type), arg_count.ToString ());
575                                 return false;
576                         }
577
578                         return me.VerifyArgumentsCompat (
579                                         ec, ref args, arg_count, mb, 
580                                         is_params_applicable || (!is_applicable && params_method),
581                                         false, loc);
582                 }
583                 
584                 public static string FullDelegateDesc (MethodBase invoke_method)
585                 {
586                         return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
587                 }
588                 
589                 public override MemberCache MemberCache {
590                         get {
591                                 return member_cache;
592                         }
593                 }
594
595                 public Expression InstanceExpression {
596                         get {
597                                 return instance_expr;
598                         }
599                         set {
600                                 instance_expr = value;
601                         }
602                 }
603
604                 public MethodBase TargetMethod {
605                         get {
606                                 return delegate_method;
607                         }
608                         set {
609                                 delegate_method = value;
610                         }
611                 }
612
613                 public Type TargetReturnType {
614                         get {
615                                 return ret_type;
616                         }
617                 }
618
619                 public override AttributeTargets AttributeTargets {
620                         get {
621                                 return AttributeTargets.Delegate;
622                         }
623                 }
624
625                 //
626                 //   Represents header string for documentation comment.
627                 //
628                 public override string DocCommentHeader {
629                         get { return "T:"; }
630                 }
631
632                 #region IMemberContainer Members
633
634                 string IMemberContainer.Name
635                 {
636                         get { throw new NotImplementedException (); }
637                 }
638
639                 Type IMemberContainer.Type
640                 {
641                         get { throw new NotImplementedException (); }
642                 }
643
644                 MemberCache IMemberContainer.BaseCache
645                 {
646                         get { throw new NotImplementedException (); }
647                 }
648
649                 bool IMemberContainer.IsInterface {
650                         get {
651                                 return false;
652                         }
653                 }
654
655                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
656                 {
657                         throw new NotImplementedException ();
658                 }
659
660                 #endregion
661         }
662
663         //
664         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
665         //
666         public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
667         {
668                 protected ConstructorInfo constructor_method;
669                 protected MethodInfo delegate_method;
670                 // We keep this to handle IsBase only
671                 protected MethodGroupExpr method_group;
672                 protected Expression delegate_instance_expression;
673
674                 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
675                 {
676                         AParametersCollection pd = TypeManager.GetParameterData (invoke_method);
677                         ArrayList delegate_arguments = new ArrayList (pd.Count);
678                         for (int i = 0; i < pd.Count; ++i) {
679                                 Argument.AType atype_modifier;
680                                 Type atype = pd.Types [i];
681                                 switch (pd.FixedParameters [i].ModFlags) {
682                                 case Parameter.Modifier.REF:
683                                         atype_modifier = Argument.AType.Ref;
684                                         //atype = atype.GetElementType ();
685                                         break;
686                                 case Parameter.Modifier.OUT:
687                                         atype_modifier = Argument.AType.Out;
688                                         //atype = atype.GetElementType ();
689                                         break;
690                                 case Parameter.Modifier.ARGLIST:
691                                         // __arglist is not valid
692                                         throw new InternalErrorException ("__arglist modifier");
693                                 default:
694                                         atype_modifier = Argument.AType.Expression;
695                                         break;
696                                 }
697                                 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
698                         }
699                         return delegate_arguments;
700                 }
701
702                 public override Expression CreateExpressionTree (EmitContext ec)
703                 {
704                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
705
706                         ArrayList args = new ArrayList (3);
707                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
708                         args.Add (new Argument (new NullLiteral (loc)));
709                         args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
710                         Expression e = new Invocation (ma, args).Resolve (ec);
711                         if (e == null)
712                                 return null;
713
714                         e = Convert.ExplicitConversion (ec, e, type, loc);
715                         if (e == null)
716                                 return null;
717
718                         return e.CreateExpressionTree (ec);
719                 }
720
721                 public override Expression DoResolve (EmitContext ec)
722                 {
723                         constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
724
725                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
726                         method_group.DelegateType = type;
727                         method_group.CustomErrorHandler = this;
728
729                         ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
730                         method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
731                         if (method_group == null)
732                                 return null;
733
734                         delegate_method = (MethodInfo) method_group;
735                         
736                         if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
737                                 Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
738                                         TypeManager.GetFullNameSignature (delegate_method));
739                                 return null;
740                         }               
741                         
742                         Invocation.IsSpecialMethodInvocation (delegate_method, loc);
743
744                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
745                         if (emg != null) {
746                                 delegate_instance_expression = emg.ExtensionExpression;
747                                 Type e_type = delegate_instance_expression.Type;
748                                 if (TypeManager.IsValueType (e_type)) {
749                                         Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
750                                                 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
751                                 }
752                         }
753
754                         Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
755                         Expression ret_expr = new TypeExpression (rt, loc);
756                         if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
757                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
758                         }
759
760                         if (Invocation.IsMethodExcluded (delegate_method, loc)) {
761                                 Report.SymbolRelatedToPreviousError (delegate_method);
762                                 MethodOrOperator m = TypeManager.GetMethod (delegate_method) as MethodOrOperator;
763                                 if (m != null && m.IsPartialDefinition) {
764                                         Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
765                                                 TypeManager.CSharpSignature (delegate_method));
766                                 } else {
767                                         Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
768                                                 TypeManager.CSharpSignature (delegate_method));
769                                 }
770                         }
771
772                         DoResolveInstanceExpression (ec);
773                         eclass = ExprClass.Value;
774                         return this;
775                 }
776
777                 void DoResolveInstanceExpression (EmitContext ec)
778                 {
779                         //
780                         // Argument is another delegate
781                         //
782                         if (delegate_instance_expression != null)
783                                 return;
784
785                         Expression instance = method_group.InstanceExpression;
786                         if (instance != null && instance != EmptyExpression.Null) {
787                                 delegate_instance_expression = instance;
788                                 Type instance_type = delegate_instance_expression.Type;
789                                 if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
790                                         delegate_instance_expression = new BoxedCast (
791                                                 delegate_instance_expression, TypeManager.object_type);
792                                 }
793                         } else if (!delegate_method.IsStatic && !ec.IsStatic) {
794                                 delegate_instance_expression = ec.GetThis (loc);
795                         }
796                 }
797                 
798                 public override void Emit (EmitContext ec)
799                 {
800                         if (delegate_instance_expression == null)
801                                 ec.ig.Emit (OpCodes.Ldnull);
802                         else
803                                 delegate_instance_expression.Emit (ec);
804
805                         if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
806                                 ec.ig.Emit (OpCodes.Dup);
807                                 ec.ig.Emit (OpCodes.Ldvirtftn, delegate_method);
808                         } else {
809                                 ec.ig.Emit (OpCodes.Ldftn, delegate_method);
810                         }
811
812                         ec.ig.Emit (OpCodes.Newobj, constructor_method);
813                 }
814
815                 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
816                 {
817                         MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
818                         string member_name = delegate_instance_expression != null ?
819                                 Delegate.FullDelegateDesc (method) :
820                                 TypeManager.GetFullNameSignature (method);
821
822                         Report.SymbolRelatedToPreviousError (type);
823                         Report.SymbolRelatedToPreviousError (method);
824                         if (RootContext.Version == LanguageVersion.ISO_1) {
825                                 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",
826                                         TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
827                                         TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
828                                 return;
829                         }
830                         if (return_type == null) {
831                                 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
832                                         member_name, Delegate.FullDelegateDesc (invoke_method));
833                                 return;
834                         }
835
836                         Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
837                                 return_type.GetSignatureForError (), member_name,
838                                 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
839                 }
840
841                 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
842                 {
843                         if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
844                                 return null;
845
846                         foreach (MethodInfo mi in mg.Methods){
847                                 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi);
848                                 if (mb != null)
849                                         return mb;
850                         }
851                         return null;
852                 }
853
854                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
855                 {
856                         if (delegate_instance_expression != null)
857                                 delegate_instance_expression.MutateHoistedGenericType (storey);
858
859                         delegate_method = storey.MutateGenericMethod (delegate_method);
860                         constructor_method = storey.MutateConstructor (constructor_method);
861                 }
862
863                 #region IErrorHandler Members
864
865                 public bool NoExactMatch (EmitContext ec, MethodBase method)
866                 {
867                         if (TypeManager.IsGenericMethod (method))
868                                 return false;
869
870                         Error_ConversionFailed (ec, method, null);
871                         return true;
872                 }
873
874                 public bool AmbiguousCall (MethodBase ambiguous)
875                 {
876                         return false;
877                 }
878
879                 #endregion
880         }
881
882         //
883         // Created from the conversion code
884         //
885         public class ImplicitDelegateCreation : DelegateCreation
886         {
887                 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
888                 {
889                         type = t;
890                         this.method_group = mg;
891                         loc = l;
892                 }
893
894                 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
895                                                  Type target_type, Location loc)
896                 {
897                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
898                         return d.DoResolve (ec);
899                 }
900         }
901         
902         //
903         // A delegate-creation-expression, invoked from the `New' class 
904         //
905         public class NewDelegate : DelegateCreation
906         {
907                 public ArrayList Arguments;
908
909                 //
910                 // This constructor is invoked from the `New' expression
911                 //
912                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
913                 {
914                         this.type = type;
915                         this.Arguments = Arguments;
916                         this.loc  = loc; 
917                 }
918
919                 public override Expression DoResolve (EmitContext ec)
920                 {
921                         if (Arguments == null || Arguments.Count != 1) {
922                                 Error_InvalidDelegateArgument ();
923                                 return null;
924                         }
925
926                         Argument a = (Argument) Arguments [0];
927                         if (!a.ResolveMethodGroup (ec))
928                                 return null;
929
930                         Expression e = a.Expr;
931
932                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
933                         if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
934                                 e = ame.Compatible (ec, type);
935                                 if (e == null)
936                                         return null;
937
938                                 return e.Resolve (ec);
939                         }
940
941                         method_group = e as MethodGroupExpr;
942                         if (method_group == null) {
943                                 if (!TypeManager.IsDelegateType (e.Type)) {
944                                         e.Error_UnexpectedKind (ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
945                                         return null;
946                                 }
947
948                                 //
949                                 // An argument is not a method but another delegate
950                                 //
951                                 delegate_instance_expression = e;
952                                 method_group = new MethodGroupExpr (new MemberInfo [] { 
953                                         Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
954                         }
955
956                         return base.DoResolve (ec);
957                 }
958
959                 void Error_InvalidDelegateArgument ()
960                 {
961                         Report.Error (149, loc, "Method name expected");
962                 }
963         }
964
965         public class DelegateInvocation : ExpressionStatement {
966
967                 readonly Expression InstanceExpr;
968                 readonly ArrayList  Arguments;
969
970                 MethodInfo method;
971                 
972                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
973                 {
974                         this.InstanceExpr = instance_expr;
975                         this.Arguments = args;
976                         this.loc = loc;
977                 }
978                 
979                 public override Expression CreateExpressionTree (EmitContext ec)
980                 {
981                         ArrayList args;
982                         if (Arguments == null)
983                                 args = new ArrayList (1);
984                         else
985                                 args = new ArrayList (Arguments.Count + 1);
986
987                         args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
988                         if (Arguments != null) {
989                                 foreach (Argument a in Arguments)
990                                         args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
991                         }
992
993                         return CreateExpressionFactoryCall ("Invoke", args);
994                 }
995
996                 public override Expression DoResolve (EmitContext ec)
997                 {
998                         if (InstanceExpr is EventExpr) {
999                                 ((EventExpr) InstanceExpr).Error_CannotAssign ();
1000                                 return null;
1001                         }
1002                         
1003                         Type del_type = InstanceExpr.Type;
1004                         if (del_type == null)
1005                                 return null;
1006                         
1007                         if (Arguments != null){
1008                                 foreach (Argument a in Arguments){
1009                                         if (!a.Resolve (ec, loc))
1010                                                 return null;
1011                                 }
1012                         }
1013                         
1014                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1015                                 return null;
1016
1017                         method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
1018                         type = TypeManager.TypeToCoreType (method.ReturnType);
1019                         eclass = ExprClass.Value;
1020                         
1021                         return this;
1022                 }
1023
1024                 public override void Emit (EmitContext ec)
1025                 {
1026                         //
1027                         // Invocation on delegates call the virtual Invoke member
1028                         // so we are always `instance' calls
1029                         //
1030                         Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
1031                 }
1032
1033                 public override void EmitStatement (EmitContext ec)
1034                 {
1035                         Emit (ec);
1036                         // 
1037                         // Pop the return value if there is one
1038                         //
1039                         if (type != TypeManager.void_type)
1040                                 ec.ig.Emit (OpCodes.Pop);
1041                 }
1042
1043                 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1044                 {
1045                         method = storey.MutateGenericMethod (method);
1046                         type = storey.MutateType (type);
1047
1048                         if (Arguments != null) {
1049                                 foreach (Argument a in Arguments) {
1050                                         a.Expr.MutateHoistedGenericType (storey);
1051                                 }
1052                         }
1053
1054                         InstanceExpr.MutateHoistedGenericType (storey);
1055                 }
1056         }
1057 }