Merge pull request #1404 from woodsb02/mono-route
[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 ((caching_flags & Flags.CloseTypeCreated) != 0)
298                                 return;
299
300                         if (!Parameters.IsEmpty) {
301                                 parameters.ResolveDefaultValues (this);
302                         }
303
304                         InvokeBuilder.PrepareEmit ();
305                         if (BeginInvokeBuilder != null) {
306                                 BeginInvokeBuilder.PrepareEmit ();
307                                 EndInvokeBuilder.PrepareEmit ();
308                         }
309                 }
310
311                 public override void Emit ()
312                 {
313                         base.Emit ();
314
315                         if (ReturnType.Type != null) {
316                                 if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
317                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
318                                         Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
319                                 } else if (ReturnType.Type.HasDynamicElement) {
320                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
321                                         Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
322                                 }
323
324                                 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
325                         }
326
327                         Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
328                         Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
329
330                         parameters.CheckConstraints (this);
331                         parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
332                         InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
333
334                         if (BeginInvokeBuilder != null) {
335                                 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
336                                 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
337
338                                 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
339                                 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
340                         }
341                 }
342
343                 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
344                 {
345                         base_type = Compiler.BuiltinTypes.MulticastDelegate;
346                         base_class = null;
347                         return null;
348                 }
349
350                 protected override TypeAttributes TypeAttr {
351                         get {
352                                 return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
353                         }
354                 }
355
356                 public override string[] ValidAttributeTargets {
357                         get {
358                                 return attribute_targets;
359                         }
360                 }
361
362                 //TODO: duplicate
363                 protected override bool VerifyClsCompliance ()
364                 {
365                         if (!base.VerifyClsCompliance ()) {
366                                 return false;
367                         }
368
369                         parameters.VerifyClsCompliance (this);
370
371                         if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
372                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
373                                         GetSignatureForError ());
374                         }
375                         return true;
376                 }
377
378
379                 public static MethodSpec GetConstructor (TypeSpec delType)
380                 {
381                         var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
382                         return (MethodSpec) ctor;
383                 }
384
385                 //
386                 // Returns the "Invoke" from a delegate type
387                 //
388                 public static MethodSpec GetInvokeMethod (TypeSpec delType)
389                 {
390                         var invoke = MemberCache.FindMember (delType,
391                                 MemberFilter.Method (InvokeMethodName, 0, null, null),
392                                 BindingRestriction.DeclaredOnly);
393
394                         return (MethodSpec) invoke;
395                 }
396
397                 public static AParametersCollection GetParameters (TypeSpec delType)
398                 {
399                         var invoke_mb = GetInvokeMethod (delType);
400                         return invoke_mb.Parameters;
401                 }
402
403                 //
404                 // 15.2 Delegate compatibility
405                 //
406                 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
407                 {
408                         //
409                         // For each value parameter (a parameter with no ref or out modifier), an 
410                         // identity conversion or implicit reference conversion exists from the
411                         // parameter type in D to the corresponding parameter type in M
412                         //
413                         if (a == b)
414                                 return true;
415
416                         if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
417                                 return false;
418
419                         if (a.IsGenericParameter && b.IsGenericParameter)
420                                 return a == b;
421
422                         return Convert.ImplicitReferenceConversionExists (a, b);
423                 }
424
425                 public static string FullDelegateDesc (MethodSpec invoke_method)
426                 {
427                         return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
428                 }
429                 
430                 public Expression InstanceExpression {
431                         get {
432                                 return instance_expr;
433                         }
434                         set {
435                                 instance_expr = value;
436                         }
437                 }
438         }
439
440         //
441         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
442         //
443         public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
444         {
445                 bool conditional_access_receiver;
446                 protected MethodSpec constructor_method;
447                 protected MethodGroupExpr method_group;
448
449                 public bool AllowSpecialMethodsInvocation { get; set; }
450
451                 public override bool ContainsEmitWithAwait ()
452                 {
453                         var instance = method_group.InstanceExpression;
454                         return instance != null && instance.ContainsEmitWithAwait ();
455                 }
456
457                 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
458                 {
459                         Arguments delegate_arguments = new Arguments (pd.Count);
460                         for (int i = 0; i < pd.Count; ++i) {
461                                 Argument.AType atype_modifier;
462                                 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
463                                 case Parameter.Modifier.REF:
464                                         atype_modifier = Argument.AType.Ref;
465                                         break;
466                                 case Parameter.Modifier.OUT:
467                                         atype_modifier = Argument.AType.Out;
468                                         break;
469                                 default:
470                                         atype_modifier = 0;
471                                         break;
472                                 }
473
474                                 var ptype = types[i];
475                                 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
476                                         ptype = rc.BuiltinTypes.Object;
477
478                                 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
479                         }
480
481                         return delegate_arguments;
482                 }
483
484                 public override Expression CreateExpressionTree (ResolveContext ec)
485                 {
486                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
487
488                         Arguments args = new Arguments (3);
489                         args.Add (new Argument (new TypeOf (type, loc)));
490
491                         if (method_group.InstanceExpression == null)
492                                 args.Add (new Argument (new NullLiteral (loc)));
493                         else
494                                 args.Add (new Argument (method_group.InstanceExpression));
495
496                         args.Add (new Argument (method_group.CreateExpressionTree (ec)));
497                         Expression e = new Invocation (ma, args).Resolve (ec);
498                         if (e == null)
499                                 return null;
500
501                         e = Convert.ExplicitConversion (ec, e, type, loc);
502                         if (e == null)
503                                 return null;
504
505                         return e.CreateExpressionTree (ec);
506                 }
507
508                 protected override Expression DoResolve (ResolveContext ec)
509                 {
510                         constructor_method = Delegate.GetConstructor (type);
511
512                         var invoke_method = Delegate.GetInvokeMethod (type);
513
514                         if (!ec.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
515                                 if (method_group.HasConditionalAccess ()) {
516                                         conditional_access_receiver = true;
517                                         ec.Set (ResolveContext.Options.ConditionalAccessReceiver);
518                                 }
519                         }
520
521                         Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
522                         method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
523
524                         if (conditional_access_receiver)
525                                 ec.With (ResolveContext.Options.ConditionalAccessReceiver, false);
526
527                         if (method_group == null)
528                                 return null;
529
530                         var delegate_method = method_group.BestCandidate;
531                         
532                         if (delegate_method.DeclaringType.IsNullableType) {
533                                 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
534                                         delegate_method.GetSignatureForError ());
535                                 return null;
536                         }               
537                         
538                         if (!AllowSpecialMethodsInvocation)
539                                 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
540
541                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
542                         if (emg != null) {
543                                 method_group.InstanceExpression = emg.ExtensionExpression;
544                                 TypeSpec e_type = emg.ExtensionExpression.Type;
545                                 if (TypeSpec.IsValueType (e_type)) {
546                                         ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
547                                                 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
548                                 }
549                         }
550
551                         TypeSpec rt = method_group.BestCandidateReturnType;
552                         if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
553                                 rt = ec.BuiltinTypes.Object;
554
555                         if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
556                                 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
557                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
558                         }
559
560                         if (method_group.IsConditionallyExcluded) {
561                                 ec.Report.SymbolRelatedToPreviousError (delegate_method);
562                                 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
563                                 if (m != null && m.IsPartialDefinition) {
564                                         ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
565                                                 delegate_method.GetSignatureForError ());
566                                 } else {
567                                         ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
568                                                 TypeManager.CSharpSignature (delegate_method));
569                                 }
570                         }
571
572                         var expr = method_group.InstanceExpression;
573                         if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
574                                 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
575
576                         eclass = ExprClass.Value;
577                         return this;
578                 }
579                 
580                 public override void Emit (EmitContext ec)
581                 {
582                         if (conditional_access_receiver)
583                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
584
585                         if (method_group.InstanceExpression == null) {
586                                 ec.EmitNull ();
587                         } else {
588                                 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
589                                 ie.Emit (ec, method_group.ConditionalAccess);
590                         }
591
592                         var delegate_method = method_group.BestCandidate;
593
594                         // Any delegate must be sealed
595                         if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
596                                 ec.Emit (OpCodes.Dup);
597                                 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
598                         } else {
599                                 ec.Emit (OpCodes.Ldftn, delegate_method);
600                         }
601
602                         ec.Emit (OpCodes.Newobj, constructor_method);
603
604                         if (conditional_access_receiver)
605                                 ec.CloseConditionalAccess (null);
606                 }
607
608                 public override void FlowAnalysis (FlowAnalysisContext fc)
609                 {
610                         base.FlowAnalysis (fc);
611                         method_group.FlowAnalysis (fc);
612
613                         if (conditional_access_receiver)
614                                 fc.ConditionalAccessEnd ();
615                 }
616
617                 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
618                 {
619                         var invoke_method = Delegate.GetInvokeMethod (type);
620                         string member_name = method_group.InstanceExpression != null ?
621                                 Delegate.FullDelegateDesc (method) :
622                                 TypeManager.GetFullNameSignature (method);
623
624                         ec.Report.SymbolRelatedToPreviousError (type);
625                         ec.Report.SymbolRelatedToPreviousError (method);
626                         if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
627                                 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",
628                                         method.ReturnType.GetSignatureForError (), member_name,
629                                         invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
630                                 return;
631                         }
632
633                         if (return_type == null) {
634                                 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
635                                         member_name, Delegate.FullDelegateDesc (invoke_method));
636                                 return;
637                         }
638
639                         ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
640                                 return_type.GetSignatureForError (), member_name,
641                                 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
642                 }
643
644                 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
645                 {
646 //                      if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
647 //                              return false;
648
649                         var invoke = Delegate.GetInvokeMethod (target_type);
650
651                         Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
652                         mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
653                         return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
654                 }
655
656                 #region IErrorHandler Members
657
658                 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
659                 {
660                         return false;
661                 }
662
663                 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
664                 {
665                         Error_ConversionFailed (rc, best as MethodSpec, null);
666                         return true;
667                 }
668
669                 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
670                 {
671                         Error_ConversionFailed (rc, best as MethodSpec, null);
672                         return true;
673                 }
674
675                 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
676                 {
677                         return false;
678                 }
679
680                 #endregion
681         }
682
683         //
684         // Created from the conversion code
685         //
686         public class ImplicitDelegateCreation : DelegateCreation
687         {
688                 Field mg_cache;
689
690                 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
691                 {
692                         type = delegateType;
693                         this.method_group = mg;
694                         this.loc = loc;
695                 }
696
697                 //
698                 // Returns true when type is MVAR or has MVAR reference
699                 //
700                 public static bool ContainsMethodTypeParameter (TypeSpec type)
701                 {
702                         var tps = type as TypeParameterSpec;
703                         if (tps != null)
704                                 return tps.IsMethodOwned;
705
706                         var ec = type as ElementTypeSpec;
707                         if (ec != null)
708                                 return ContainsMethodTypeParameter (ec.Element);
709
710                         foreach (var t in type.TypeArguments) {
711                                 if (ContainsMethodTypeParameter (t)) {
712                                         return true;
713                                 }
714                         }
715
716                         if (type.IsNested)
717                                 return ContainsMethodTypeParameter (type.DeclaringType);
718
719                         return false;
720                 }
721                 
722                 bool HasMvar ()
723                 {
724                         if (ContainsMethodTypeParameter (type))
725                                 return false;
726
727                         var best = method_group.BestCandidate;
728                         if (ContainsMethodTypeParameter (best.DeclaringType))
729                                 return false;
730
731                         if (best.TypeArguments != null) {
732                                 foreach (var ta in best.TypeArguments) {
733                                         if (ContainsMethodTypeParameter (ta))
734                                                 return false;
735                                 }
736                         }
737
738                         return true;
739                 }
740
741                 protected override Expression DoResolve (ResolveContext ec)
742                 {
743                         var expr = base.DoResolve (ec);
744                         if (expr == null)
745                                 return ErrorExpression.Instance;
746
747                         if (ec.IsInProbingMode)
748                                 return expr;
749
750                         //
751                         // Cache any static delegate creation
752                         //
753                         if (method_group.InstanceExpression != null)
754                                 return expr;
755
756                         //
757                         // Cannot easily cache types with MVAR
758                         //
759                         if (!HasMvar ())
760                                 return expr;
761
762                         //
763                         // Create type level cache for a delegate instance
764                         //
765                         var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
766                         int id = parent.MethodGroupsCounter++;
767
768                         mg_cache = new Field (parent, new TypeExpression (type, loc),
769                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
770                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
771                         mg_cache.Define ();
772                         parent.AddField (mg_cache);
773
774                         return expr;
775                 }
776
777                 public override void Emit (EmitContext ec)
778                 {
779                         Label l_initialized = ec.DefineLabel ();
780
781                         if (mg_cache != null) {
782                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
783                                 ec.Emit (OpCodes.Brtrue_S, l_initialized);
784                         }
785
786                         base.Emit (ec);
787
788                         if (mg_cache != null) {
789                                 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
790                                 ec.MarkLabel (l_initialized);
791                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
792                         }
793                 }
794         }
795         
796         //
797         // A delegate-creation-expression, invoked from the `New' class 
798         //
799         public class NewDelegate : DelegateCreation
800         {
801                 public Arguments Arguments;
802
803                 //
804                 // This constructor is invoked from the `New' expression
805                 //
806                 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
807                 {
808                         this.type = type;
809                         this.Arguments = Arguments;
810                         this.loc  = loc; 
811                 }
812
813                 protected override Expression DoResolve (ResolveContext ec)
814                 {
815                         if (Arguments == null || Arguments.Count != 1) {
816                                 ec.Report.Error (149, loc, "Method name expected");
817                                 return null;
818                         }
819
820                         Argument a = Arguments [0];
821                         if (!a.ResolveMethodGroup (ec))
822                                 return null;
823
824                         Expression e = a.Expr;
825
826                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
827                         if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
828                                 e = ame.Compatible (ec, type);
829                                 if (e == null)
830                                         return null;
831
832                                 return e.Resolve (ec);
833                         }
834
835                         method_group = e as MethodGroupExpr;
836                         if (method_group == null) {
837                                 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
838                                         e = Convert.ImplicitConversionRequired (ec, e, type, loc);
839                                 } else if (!e.Type.IsDelegate) {
840                                         e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
841                                         return null;
842                                 }
843
844                                 //
845                                 // An argument is not a method but another delegate
846                                 //
847                                 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
848                                 method_group.InstanceExpression = e;
849                         }
850
851                         return base.DoResolve (ec);
852                 }
853         }
854
855         //
856         // Invocation converted to delegate Invoke call
857         //
858         class DelegateInvocation : ExpressionStatement
859         {
860                 readonly Expression InstanceExpr;
861                 readonly bool conditionalAccessReceiver;
862                 Arguments arguments;
863                 MethodSpec method;
864                 
865                 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
866                 {
867                         this.InstanceExpr = instance_expr;
868                         this.arguments = args;
869                         this.conditionalAccessReceiver = conditionalAccessReceiver;
870                         this.loc = loc;
871                 }
872
873                 public override bool ContainsEmitWithAwait ()
874                 {
875                         return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
876                 }
877                 
878                 public override Expression CreateExpressionTree (ResolveContext ec)
879                 {
880                         Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
881                                 InstanceExpr.CreateExpressionTree (ec));
882
883                         return CreateExpressionFactoryCall (ec, "Invoke", args);
884                 }
885
886                 public override void FlowAnalysis (FlowAnalysisContext fc)
887                 {
888                         InstanceExpr.FlowAnalysis (fc);
889                         if (arguments != null)
890                                 arguments.FlowAnalysis (fc);
891                 }
892
893                 protected override Expression DoResolve (ResolveContext ec)
894                 {               
895                         TypeSpec del_type = InstanceExpr.Type;
896                         if (del_type == null)
897                                 return null;
898
899                         //
900                         // Do only core overload resolution the rest of the checks has been
901                         // done on primary expression
902                         //
903                         method = Delegate.GetInvokeMethod (del_type);
904                         var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
905                         var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
906                         if (valid == null && !res.BestCandidateIsDynamic)
907                                 return null;
908
909                         type = method.ReturnType;
910                         if (conditionalAccessReceiver)
911                                 type = LiftMemberType (ec, type);
912
913                         eclass = ExprClass.Value;
914                         return this;
915                 }
916
917                 public override void Emit (EmitContext ec)
918                 {
919                         if (conditionalAccessReceiver) {
920                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
921                         }
922
923                         //
924                         // Invocation on delegates call the virtual Invoke member
925                         // so we are always `instance' calls
926                         //
927                         var call = new CallEmitter ();
928                         call.InstanceExpression = InstanceExpr;
929                         call.Emit (ec, method, arguments, loc);
930
931                         if (conditionalAccessReceiver)
932                                 ec.CloseConditionalAccess (type.IsNullableType && type !=  method.ReturnType ? type : null);
933                 }
934
935                 public override void EmitStatement (EmitContext ec)
936                 {
937                         if (conditionalAccessReceiver) {
938                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
939                                         Statement = true
940                                 };
941                         }
942
943                         var call = new CallEmitter ();
944                         call.InstanceExpression = InstanceExpr;
945                         call.EmitStatement (ec, method, arguments, loc);
946
947                         if (conditionalAccessReceiver)
948                                 ec.CloseConditionalAccess (null);
949                 }
950
951                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
952                 {
953                         return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
954                 }
955         }
956 }