Merge remote branch 'upstream/master'
[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-2009 Novell, Inc (http://www.novell.com)
13 //
14
15 using System;
16
17 #if STATIC
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
20 #else
21 using System.Reflection;
22 using System.Reflection.Emit;
23 #endif
24
25 namespace Mono.CSharp {
26
27         //
28         // Delegate container implementation
29         //
30         public class Delegate : TypeContainer, IParametersMember
31         {
32                 FullNamedExpression ReturnType;
33                 readonly ParametersCompiled parameters;
34
35                 Constructor Constructor;
36                 Method InvokeBuilder;
37                 Method BeginInvokeBuilder;
38                 Method EndInvokeBuilder;
39
40                 static readonly string[] attribute_targets = new string [] { "type", "return" };
41
42                 public static readonly string InvokeMethodName = "Invoke";
43                 
44                 Expression instance_expr;
45                 ReturnParameter return_attributes;
46
47                 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
48
49                 const Modifiers 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                                  Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
59                                  Attributes attrs)
60                         : base (ns, parent, name, attrs, MemberKind.Delegate)
61
62                 {
63                         this.ReturnType = type;
64                         ModFlags        = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
65                                                            IsTopLevel ? Modifiers.INTERNAL :
66                                                            Modifiers.PRIVATE, name.Location, Report);
67                         parameters      = param_list;
68                         spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
69                 }
70
71                 #region Properties
72                 public TypeSpec MemberType {
73                         get {
74                                 return ReturnType.Type;
75                         }
76                 }
77
78                 public AParametersCollection Parameters {
79                         get {
80                                 return parameters;
81                         }
82                 }
83                 #endregion
84
85                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
86                 {
87                         if (a.Target == AttributeTargets.ReturnValue) {
88                                 if (return_attributes == null)
89                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
90
91                                 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
92                                 return;
93                         }
94
95                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
96                 }
97
98                 public override AttributeTargets AttributeTargets {
99                         get {
100                                 return AttributeTargets.Delegate;
101                         }
102                 }
103
104                 protected override bool DoDefineMembers ()
105                 {
106                         var ctor_parameters = ParametersCompiled.CreateFullyResolved (
107                                 new [] {
108                                         new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
109                                         new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
110                                 },
111                                 new [] {
112                                         TypeManager.object_type,
113                                         TypeManager.intptr_type
114                                 }
115                         );
116
117                         Constructor = new Constructor (this, Constructor.ConstructorName,
118                                 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
119                         Constructor.Define ();
120
121                         //
122                         // Here the various methods like Invoke, BeginInvoke etc are defined
123                         //
124                         // First, call the `out of band' special method for
125                         // defining recursively any types we need:
126                         //
127                         var p = parameters;
128
129                         if (!p.Resolve (this))
130                                 return false;
131
132                         //
133                         // Invoke method
134                         //
135
136                         // Check accessibility
137                         foreach (var partype in p.Types) {
138                                 if (!IsAccessibleAs (partype)) {
139                                         Report.SymbolRelatedToPreviousError (partype);
140                                         Report.Error (59, Location,
141                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
142                                                 TypeManager.CSharpName (partype), GetSignatureForError ());
143                                 }
144                         }
145
146                         ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
147                         if (ReturnType == null)
148                                 return false;
149
150                         var ret_type = ReturnType.Type;
151
152                         //
153                         // We don't have to check any others because they are all
154                         // guaranteed to be accessible - they are standard types.
155                         //
156                         if (!IsAccessibleAs (ret_type)) {
157                                 Report.SymbolRelatedToPreviousError (ret_type);
158                                 Report.Error (58, Location,
159                                                   "Inconsistent accessibility: return type `" +
160                                                   TypeManager.CSharpName (ret_type) + "' is less " +
161                                                   "accessible than delegate `" + GetSignatureForError () + "'");
162                                 return false;
163                         }
164
165                         CheckProtectedModifier ();
166
167                         if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
168                                 Method.Error1599 (Location, ret_type, Report);
169                                 return false;
170                         }
171
172                         TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
173
174                         InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
175                         InvokeBuilder.Define ();
176
177                         //
178                         // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
179                         //
180                         if (!IsCompilerGenerated) {
181                                 DefineAsyncMethods (Parameters.CallingConvention);
182                         }
183
184                         return true;
185                 }
186
187                 void DefineAsyncMethods (CallingConventions cc)
188                 {
189                         var iasync_result = Module.PredefinedTypes.IAsyncResult;
190                         var async_callback = Module.PredefinedTypes.AsyncCallback;
191
192                         //
193                         // It's ok when async types don't exist, the delegate will have Invoke method only
194                         //
195                         if (!iasync_result.Define () || !async_callback.Define ())
196                                 return;
197
198                         //
199                         // BeginInvoke
200                         //
201                         ParametersCompiled async_parameters;
202                         if (Parameters.Count == 0) {
203                                 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
204                         } else {
205                                 var compiled = new Parameter[Parameters.Count];
206                                 for (int i = 0; i < compiled.Length; ++i) {
207                                         var p = parameters[i];
208                                         compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
209                                                 p.Name,
210                                                 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
211                                                 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
212                                 }
213
214                                 async_parameters = new ParametersCompiled (compiled);
215                         }
216
217                         async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
218                                 new Parameter[] {
219                                         new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
220                                         new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
221                                 },
222                                 new [] {
223                                         async_callback.TypeSpec,
224                                         TypeManager.object_type
225                                 }
226                         );
227
228                         BeginInvokeBuilder = new Method (this, null,
229                                 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
230                                 new MemberName ("BeginInvoke"), async_parameters, null);
231                         BeginInvokeBuilder.Define ();
232
233                         //
234                         // EndInvoke is a bit more interesting, all the parameters labeled as
235                         // out or ref have to be duplicated here.
236                         //
237
238                         //
239                         // Define parameters, and count out/ref parameters
240                         //
241                         ParametersCompiled end_parameters;
242                         int out_params = 0;
243
244                         foreach (Parameter p in Parameters.FixedParameters) {
245                                 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
246                                         ++out_params;
247                         }
248
249                         if (out_params > 0) {
250                                 Parameter[] end_params = new Parameter[out_params];
251
252                                 int param = 0;
253                                 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
254                                         Parameter p = parameters [i];
255                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
256                                                 continue;
257
258                                         end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
259                                                 p.Name,
260                                                 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
261                                                 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
262                                 }
263
264                                 end_parameters = new ParametersCompiled (end_params);
265                         } else {
266                                 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
267                         }
268
269                         end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
270                                 new Parameter (
271                                         new TypeExpression (iasync_result.TypeSpec, Location),
272                                         "result", Parameter.Modifier.NONE, null, Location),
273                                 iasync_result.TypeSpec);
274
275                         //
276                         // Create method, define parameters, register parameters with type system
277                         //
278                         EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
279                         EndInvokeBuilder.Define ();
280                 }
281
282                 public override void DefineConstants ()
283                 {
284                         if (!Parameters.IsEmpty) {
285                                 parameters.ResolveDefaultValues (this);
286                         }
287                 }
288
289                 public override void EmitType ()
290                 {
291                         if (ReturnType.Type != null) {
292                                 if (ReturnType.Type == InternalType.Dynamic) {
293                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
294                                         Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
295                                 } else if (ReturnType.Type.HasDynamicElement) {
296                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
297                                         Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
298                                 }
299                         }
300
301                         Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
302                         Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
303
304                         parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
305                         InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
306
307                         if (BeginInvokeBuilder != null) {
308                                 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
309                                 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
310
311                                 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
312                                 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
313                         }
314
315                         if (OptAttributes != null) {
316                                 OptAttributes.Emit ();
317                         }
318
319                         base.Emit ();
320                 }
321
322                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
323                 {
324                         base_type = TypeManager.multicast_delegate_type;
325                         base_class = null;
326                         return null;
327                 }
328
329                 protected override TypeAttributes TypeAttr {
330                         get {
331                                 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
332                                         TypeAttributes.Class | TypeAttributes.Sealed |
333                                         base.TypeAttr;
334                         }
335                 }
336
337                 public override string[] ValidAttributeTargets {
338                         get {
339                                 return attribute_targets;
340                         }
341                 }
342
343                 //TODO: duplicate
344                 protected override bool VerifyClsCompliance ()
345                 {
346                         if (!base.VerifyClsCompliance ()) {
347                                 return false;
348                         }
349
350                         parameters.VerifyClsCompliance (this);
351
352                         if (!ReturnType.Type.IsCLSCompliant ()) {
353                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
354                                         GetSignatureForError ());
355                         }
356                         return true;
357                 }
358
359
360                 public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
361                 {
362                         var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
363                         return (MethodSpec) ctor;
364                 }
365
366                 //
367                 // Returns the "Invoke" from a delegate type
368                 //
369                 public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
370                 {
371                         var invoke = MemberCache.FindMember (delType,
372                                 MemberFilter.Method (InvokeMethodName, 0, null, null),
373                                 BindingRestriction.DeclaredOnly);
374
375                         return (MethodSpec) invoke;
376                 }
377
378                 public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
379                 {
380                         var invoke_mb = GetInvokeMethod (ctx, delType);
381                         return invoke_mb.Parameters;
382                 }
383
384                 //
385                 // 15.2 Delegate compatibility
386                 //
387                 public static bool IsTypeCovariant (Expression a, TypeSpec b)
388                 {
389                         //
390                         // For each value parameter (a parameter with no ref or out modifier), an 
391                         // identity conversion or implicit reference conversion exists from the
392                         // parameter type in D to the corresponding parameter type in M
393                         //
394                         if (a.Type == b)
395                                 return true;
396
397                         if (RootContext.Version == LanguageVersion.ISO_1)
398                                 return false;
399
400                         return Convert.ImplicitReferenceConversionExists (a, b);
401                 }
402
403                 public static string FullDelegateDesc (MethodSpec invoke_method)
404                 {
405                         return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
406                 }
407                 
408                 public Expression InstanceExpression {
409                         get {
410                                 return instance_expr;
411                         }
412                         set {
413                                 instance_expr = value;
414                         }
415                 }
416         }
417
418         //
419         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
420         //
421         public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
422         {
423                 protected MethodSpec constructor_method;
424                 protected MethodGroupExpr method_group;
425
426                 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
427                 {
428                         Arguments delegate_arguments = new Arguments (pd.Count);
429                         for (int i = 0; i < pd.Count; ++i) {
430                                 Argument.AType atype_modifier;
431                                 switch (pd.FixedParameters [i].ModFlags) {
432                                 case Parameter.Modifier.REF:
433                                         atype_modifier = Argument.AType.Ref;
434                                         break;
435                                 case Parameter.Modifier.OUT:
436                                         atype_modifier = Argument.AType.Out;
437                                         break;
438                                 default:
439                                         atype_modifier = 0;
440                                         break;
441                                 }
442
443                                 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
444                         }
445
446                         return delegate_arguments;
447                 }
448
449                 public override Expression CreateExpressionTree (ResolveContext ec)
450                 {
451                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
452
453                         Arguments args = new Arguments (3);
454                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
455
456                         if (method_group.InstanceExpression == null)
457                                 args.Add (new Argument (new NullLiteral (loc)));
458                         else
459                                 args.Add (new Argument (method_group.InstanceExpression));
460
461                         args.Add (new Argument (method_group.CreateExpressionTree (ec)));
462                         Expression e = new Invocation (ma, args).Resolve (ec);
463                         if (e == null)
464                                 return null;
465
466                         e = Convert.ExplicitConversion (ec, e, type, loc);
467                         if (e == null)
468                                 return null;
469
470                         return e.CreateExpressionTree (ec);
471                 }
472
473                 protected override Expression DoResolve (ResolveContext ec)
474                 {
475                         constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
476
477                         var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
478
479                         Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
480                         method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
481                         if (method_group == null)
482                                 return null;
483
484                         var delegate_method = method_group.BestCandidate;
485                         
486                         if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
487                                 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
488                                         delegate_method.GetSignatureForError ());
489                                 return null;
490                         }               
491                         
492                         Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
493
494                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
495                         if (emg != null) {
496                                 method_group.InstanceExpression = emg.ExtensionExpression;
497                                 TypeSpec e_type = emg.ExtensionExpression.Type;
498                                 if (TypeManager.IsValueType (e_type)) {
499                                         ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
500                                                 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
501                                 }
502                         }
503
504                         TypeSpec rt = delegate_method.ReturnType;
505                         Expression ret_expr = new TypeExpression (rt, loc);
506                         if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
507                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
508                         }
509
510                         if (delegate_method.IsConditionallyExcluded (loc)) {
511                                 ec.Report.SymbolRelatedToPreviousError (delegate_method);
512                                 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
513                                 if (m != null && m.IsPartialDefinition) {
514                                         ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
515                                                 delegate_method.GetSignatureForError ());
516                                 } else {
517                                         ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
518                                                 TypeManager.CSharpSignature (delegate_method));
519                                 }
520                         }
521
522                         var expr = method_group.InstanceExpression;
523                         if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType (expr.Type)))
524                                 method_group.InstanceExpression = new BoxedCast (expr, TypeManager.object_type);
525
526                         eclass = ExprClass.Value;
527                         return this;
528                 }
529                 
530                 public override void Emit (EmitContext ec)
531                 {
532                         if (method_group.InstanceExpression == null)
533                                 ec.Emit (OpCodes.Ldnull);
534                         else
535                                 method_group.InstanceExpression.Emit (ec);
536
537                         var delegate_method = method_group.BestCandidate;
538
539                         // Any delegate must be sealed
540                         if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
541                                 ec.Emit (OpCodes.Dup);
542                                 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
543                         } else {
544                                 ec.Emit (OpCodes.Ldftn, delegate_method);
545                         }
546
547                         ec.Emit (OpCodes.Newobj, constructor_method);
548                 }
549
550                 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
551                 {
552                         var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
553                         string member_name = method_group.InstanceExpression != null ?
554                                 Delegate.FullDelegateDesc (method) :
555                                 TypeManager.GetFullNameSignature (method);
556
557                         ec.Report.SymbolRelatedToPreviousError (type);
558                         ec.Report.SymbolRelatedToPreviousError (method);
559                         if (RootContext.Version == LanguageVersion.ISO_1) {
560                                 ec.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",
561                                         TypeManager.CSharpName (method.ReturnType), member_name,
562                                         TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
563                                 return;
564                         }
565
566                         if (return_type == null) {
567                                 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
568                                         member_name, Delegate.FullDelegateDesc (invoke_method));
569                                 return;
570                         }
571
572                         ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
573                                 return_type.GetSignatureForError (), member_name,
574                                 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
575                 }
576
577                 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
578                 {
579                         if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
580                                 return false;
581
582                         var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
583
584                         Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
585                         return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
586                 }
587
588                 #region IErrorHandler Members
589
590                 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
591                 {
592                         return false;
593                 }
594
595                 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
596                 {
597                         Error_ConversionFailed (rc, best as MethodSpec, null);
598                         return true;
599                 }
600
601                 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
602                 {
603                         Error_ConversionFailed (rc, best as MethodSpec, null);
604                         return true;
605                 }
606
607                 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
608                 {
609                         return false;
610                 }
611
612                 #endregion
613         }
614
615         //
616         // Created from the conversion code
617         //
618         public class ImplicitDelegateCreation : DelegateCreation
619         {
620                 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
621                 {
622                         type = t;
623                         this.method_group = mg;
624                         loc = l;
625                 }
626
627                 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
628                                                  TypeSpec target_type, Location loc)
629                 {
630                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
631                         return d.DoResolve (ec);
632                 }
633         }
634         
635         //
636         // A delegate-creation-expression, invoked from the `New' class 
637         //
638         public class NewDelegate : DelegateCreation
639         {
640                 public Arguments Arguments;
641
642                 //
643                 // This constructor is invoked from the `New' expression
644                 //
645                 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
646                 {
647                         this.type = type;
648                         this.Arguments = Arguments;
649                         this.loc  = loc; 
650                 }
651
652                 protected override Expression DoResolve (ResolveContext ec)
653                 {
654                         if (Arguments == null || Arguments.Count != 1) {
655                                 ec.Report.Error (149, loc, "Method name expected");
656                                 return null;
657                         }
658
659                         Argument a = Arguments [0];
660                         if (!a.ResolveMethodGroup (ec))
661                                 return null;
662
663                         Expression e = a.Expr;
664
665                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
666                         if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
667                                 e = ame.Compatible (ec, type);
668                                 if (e == null)
669                                         return null;
670
671                                 return e.Resolve (ec);
672                         }
673
674                         method_group = e as MethodGroupExpr;
675                         if (method_group == null) {
676                                 if (e.Type == InternalType.Dynamic) {
677                                         e = Convert.ImplicitConversionRequired (ec, e, type, loc);
678                                 } else if (!e.Type.IsDelegate) {
679                                         e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
680                                         return null;
681                                 }
682
683                                 //
684                                 // An argument is not a method but another delegate
685                                 //
686                                 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
687                                 method_group.InstanceExpression = e;
688                         }
689
690                         return base.DoResolve (ec);
691                 }
692         }
693
694         //
695         // Invocation converted to delegate Invoke call
696         //
697         class DelegateInvocation : ExpressionStatement
698         {
699                 readonly Expression InstanceExpr;
700                 Arguments arguments;
701                 MethodSpec method;
702                 
703                 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
704                 {
705                         this.InstanceExpr = instance_expr;
706                         this.arguments = args;
707                         this.loc = loc;
708                 }
709                 
710                 public override Expression CreateExpressionTree (ResolveContext ec)
711                 {
712                         Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
713                                 InstanceExpr.CreateExpressionTree (ec));
714
715                         return CreateExpressionFactoryCall (ec, "Invoke", args);
716                 }
717
718                 protected override Expression DoResolve (ResolveContext ec)
719                 {               
720                         TypeSpec del_type = InstanceExpr.Type;
721                         if (del_type == null)
722                                 return null;
723
724                         //
725                         // Do only core overload resolution the rest of the checks has been
726                         // done on primary expression
727                         //
728                         method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
729                         var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
730                         var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
731                         if (valid == null && !res.BestCandidateIsDynamic)
732                                 return null;
733
734                         type = method.ReturnType;
735                         eclass = ExprClass.Value;
736                         return this;
737                 }
738
739                 public override void Emit (EmitContext ec)
740                 {
741                         //
742                         // Invocation on delegates call the virtual Invoke member
743                         // so we are always `instance' calls
744                         //
745                         Invocation.EmitCall (ec, InstanceExpr, method, arguments, loc);
746                 }
747
748                 public override void EmitStatement (EmitContext ec)
749                 {
750                         Emit (ec);
751                         // 
752                         // Pop the return value if there is one
753                         //
754                         if (type != TypeManager.void_type)
755                                 ec.Emit (OpCodes.Pop);
756                 }
757
758                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
759                 {
760                         return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
761                 }
762         }
763 }