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