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