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