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