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