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