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