Merge pull request #1325 from madrang/CryptoToolsCtorCheck
[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                 protected MethodSpec constructor_method;
463                 protected MethodGroupExpr method_group;
464
465                 public bool AllowSpecialMethodsInvocation { get; set; }
466
467                 public override bool ContainsEmitWithAwait ()
468                 {
469                         var instance = method_group.InstanceExpression;
470                         return instance != null && instance.ContainsEmitWithAwait ();
471                 }
472
473                 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
474                 {
475                         Arguments delegate_arguments = new Arguments (pd.Count);
476                         for (int i = 0; i < pd.Count; ++i) {
477                                 Argument.AType atype_modifier;
478                                 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
479                                 case Parameter.Modifier.REF:
480                                         atype_modifier = Argument.AType.Ref;
481                                         break;
482                                 case Parameter.Modifier.OUT:
483                                         atype_modifier = Argument.AType.Out;
484                                         break;
485                                 default:
486                                         atype_modifier = 0;
487                                         break;
488                                 }
489
490                                 var ptype = types[i];
491                                 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
492                                         ptype = rc.BuiltinTypes.Object;
493
494                                 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
495                         }
496
497                         return delegate_arguments;
498                 }
499
500                 public override Expression CreateExpressionTree (ResolveContext ec)
501                 {
502                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
503
504                         Arguments args = new Arguments (3);
505                         args.Add (new Argument (new TypeOf (type, loc)));
506
507                         if (method_group.InstanceExpression == null)
508                                 args.Add (new Argument (new NullLiteral (loc)));
509                         else
510                                 args.Add (new Argument (method_group.InstanceExpression));
511
512                         args.Add (new Argument (method_group.CreateExpressionTree (ec)));
513                         Expression e = new Invocation (ma, args).Resolve (ec);
514                         if (e == null)
515                                 return null;
516
517                         e = Convert.ExplicitConversion (ec, e, type, loc);
518                         if (e == null)
519                                 return null;
520
521                         return e.CreateExpressionTree (ec);
522                 }
523
524                 void ResolveConditionalAccessReceiver (ResolveContext rc)
525                 {
526                         // LAMESPEC: Not sure why this is explicitly disalloed with very odd error message
527                         if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && method_group.HasConditionalAccess ()) {
528                                 Error_OperatorCannotBeApplied (rc, loc, "?", method_group.Type);
529                         }
530                 }
531
532                 protected override Expression DoResolve (ResolveContext ec)
533                 {
534                         constructor_method = Delegate.GetConstructor (type);
535
536                         var invoke_method = Delegate.GetInvokeMethod (type);
537
538                         ResolveConditionalAccessReceiver (ec);
539
540                         Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
541                         method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
542
543                         if (method_group == null)
544                                 return null;
545
546                         var delegate_method = method_group.BestCandidate;
547                         
548                         if (delegate_method.DeclaringType.IsNullableType) {
549                                 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
550                                         delegate_method.GetSignatureForError ());
551                                 return null;
552                         }               
553                         
554                         if (!AllowSpecialMethodsInvocation)
555                                 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
556
557                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
558                         if (emg != null) {
559                                 method_group.InstanceExpression = emg.ExtensionExpression;
560                                 TypeSpec e_type = emg.ExtensionExpression.Type;
561                                 if (TypeSpec.IsValueType (e_type)) {
562                                         ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
563                                                 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
564                                 }
565                         }
566
567                         TypeSpec rt = method_group.BestCandidateReturnType;
568                         if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
569                                 rt = ec.BuiltinTypes.Object;
570
571                         if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
572                                 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
573                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
574                         }
575
576                         if (method_group.IsConditionallyExcluded) {
577                                 ec.Report.SymbolRelatedToPreviousError (delegate_method);
578                                 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
579                                 if (m != null && m.IsPartialDefinition) {
580                                         ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
581                                                 delegate_method.GetSignatureForError ());
582                                 } else {
583                                         ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
584                                                 TypeManager.CSharpSignature (delegate_method));
585                                 }
586                         }
587
588                         var expr = method_group.InstanceExpression;
589                         if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
590                                 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
591
592                         eclass = ExprClass.Value;
593                         return this;
594                 }
595                 
596                 public override void Emit (EmitContext ec)
597                 {
598                         if (method_group.InstanceExpression == null) {
599                                 ec.EmitNull ();
600                         } else {
601                                 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
602                                 ie.Emit (ec, method_group.ConditionalAccess);
603                         }
604
605                         var delegate_method = method_group.BestCandidate;
606
607                         // Any delegate must be sealed
608                         if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
609                                 ec.Emit (OpCodes.Dup);
610                                 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
611                         } else {
612                                 ec.Emit (OpCodes.Ldftn, delegate_method);
613                         }
614
615                         ec.Emit (OpCodes.Newobj, constructor_method);
616                 }
617
618                 public override void FlowAnalysis (FlowAnalysisContext fc)
619                 {
620                         base.FlowAnalysis (fc);
621                         method_group.FlowAnalysis (fc);
622                 }
623
624                 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
625                 {
626                         var invoke_method = Delegate.GetInvokeMethod (type);
627                         string member_name = method_group.InstanceExpression != null ?
628                                 Delegate.FullDelegateDesc (method) :
629                                 TypeManager.GetFullNameSignature (method);
630
631                         ec.Report.SymbolRelatedToPreviousError (type);
632                         ec.Report.SymbolRelatedToPreviousError (method);
633                         if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
634                                 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",
635                                         method.ReturnType.GetSignatureForError (), member_name,
636                                         invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
637                                 return;
638                         }
639
640                         if (return_type == null) {
641                                 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
642                                         member_name, Delegate.FullDelegateDesc (invoke_method));
643                                 return;
644                         }
645
646                         ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
647                                 return_type.GetSignatureForError (), member_name,
648                                 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
649                 }
650
651                 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
652                 {
653 //                      if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
654 //                              return false;
655
656                         var invoke = Delegate.GetInvokeMethod (target_type);
657
658                         Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
659                         mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
660                         return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
661                 }
662
663                 #region IErrorHandler Members
664
665                 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
666                 {
667                         return false;
668                 }
669
670                 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
671                 {
672                         Error_ConversionFailed (rc, best as MethodSpec, null);
673                         return true;
674                 }
675
676                 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
677                 {
678                         Error_ConversionFailed (rc, best as MethodSpec, null);
679                         return true;
680                 }
681
682                 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
683                 {
684                         return false;
685                 }
686
687                 #endregion
688         }
689
690         //
691         // Created from the conversion code
692         //
693         public class ImplicitDelegateCreation : DelegateCreation
694         {
695                 Field mg_cache;
696
697                 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
698                 {
699                         type = delegateType;
700                         this.method_group = mg;
701                         this.loc = loc;
702                 }
703
704                 //
705                 // Returns true when type is MVAR or has MVAR reference
706                 //
707                 public static bool ContainsMethodTypeParameter (TypeSpec type)
708                 {
709                         var tps = type as TypeParameterSpec;
710                         if (tps != null)
711                                 return tps.IsMethodOwned;
712
713                         var ec = type as ElementTypeSpec;
714                         if (ec != null)
715                                 return ContainsMethodTypeParameter (ec.Element);
716
717                         foreach (var t in type.TypeArguments) {
718                                 if (ContainsMethodTypeParameter (t)) {
719                                         return true;
720                                 }
721                         }
722
723                         if (type.IsNested)
724                                 return ContainsMethodTypeParameter (type.DeclaringType);
725
726                         return false;
727                 }
728                 
729                 bool HasMvar ()
730                 {
731                         if (ContainsMethodTypeParameter (type))
732                                 return false;
733
734                         var best = method_group.BestCandidate;
735                         if (ContainsMethodTypeParameter (best.DeclaringType))
736                                 return false;
737
738                         if (best.TypeArguments != null) {
739                                 foreach (var ta in best.TypeArguments) {
740                                         if (ContainsMethodTypeParameter (ta))
741                                                 return false;
742                                 }
743                         }
744
745                         return true;
746                 }
747
748                 protected override Expression DoResolve (ResolveContext ec)
749                 {
750                         var expr = base.DoResolve (ec);
751                         if (expr == null)
752                                 return ErrorExpression.Instance;
753
754                         if (ec.IsInProbingMode)
755                                 return expr;
756
757                         //
758                         // Cache any static delegate creation
759                         //
760                         if (method_group.InstanceExpression != null)
761                                 return expr;
762
763                         //
764                         // Cannot easily cache types with MVAR
765                         //
766                         if (!HasMvar ())
767                                 return expr;
768
769                         //
770                         // Create type level cache for a delegate instance
771                         //
772                         var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
773                         int id = parent.MethodGroupsCounter++;
774
775                         mg_cache = new Field (parent, new TypeExpression (type, loc),
776                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
777                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
778                         mg_cache.Define ();
779                         parent.AddField (mg_cache);
780
781                         return expr;
782                 }
783
784                 public override void Emit (EmitContext ec)
785                 {
786                         Label l_initialized = ec.DefineLabel ();
787
788                         if (mg_cache != null) {
789                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
790                                 ec.Emit (OpCodes.Brtrue_S, l_initialized);
791                         }
792
793                         base.Emit (ec);
794
795                         if (mg_cache != null) {
796                                 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
797                                 ec.MarkLabel (l_initialized);
798                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
799                         }
800                 }
801         }
802         
803         //
804         // A delegate-creation-expression, invoked from the `New' class 
805         //
806         public class NewDelegate : DelegateCreation
807         {
808                 public Arguments Arguments;
809
810                 //
811                 // This constructor is invoked from the `New' expression
812                 //
813                 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
814                 {
815                         this.type = type;
816                         this.Arguments = Arguments;
817                         this.loc  = loc; 
818                 }
819
820                 protected override Expression DoResolve (ResolveContext ec)
821                 {
822                         if (Arguments == null || Arguments.Count != 1) {
823                                 ec.Report.Error (149, loc, "Method name expected");
824                                 return null;
825                         }
826
827                         Argument a = Arguments [0];
828                         if (!a.ResolveMethodGroup (ec))
829                                 return null;
830
831                         Expression e = a.Expr;
832
833                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
834                         if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
835                                 e = ame.Compatible (ec, type);
836                                 if (e == null)
837                                         return null;
838
839                                 return e.Resolve (ec);
840                         }
841
842                         method_group = e as MethodGroupExpr;
843                         if (method_group == null) {
844                                 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
845                                         e = Convert.ImplicitConversionRequired (ec, e, type, loc);
846                                 } else if (!e.Type.IsDelegate) {
847                                         e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
848                                         return null;
849                                 }
850
851                                 //
852                                 // An argument is not a method but another delegate
853                                 //
854                                 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
855                                 method_group.InstanceExpression = e;
856                         }
857
858                         return base.DoResolve (ec);
859                 }
860         }
861
862         //
863         // Invocation converted to delegate Invoke call
864         //
865         class DelegateInvocation : ExpressionStatement
866         {
867                 readonly Expression InstanceExpr;
868                 readonly bool conditionalAccessReceiver;
869                 Arguments arguments;
870                 MethodSpec method;
871                 
872                 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
873                 {
874                         this.InstanceExpr = instance_expr;
875                         this.arguments = args;
876                         this.conditionalAccessReceiver = conditionalAccessReceiver;
877                         this.loc = loc;
878                 }
879
880                 public override bool ContainsEmitWithAwait ()
881                 {
882                         return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
883                 }
884                 
885                 public override Expression CreateExpressionTree (ResolveContext ec)
886                 {
887                         Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
888                                 InstanceExpr.CreateExpressionTree (ec));
889
890                         return CreateExpressionFactoryCall (ec, "Invoke", args);
891                 }
892
893                 public override void FlowAnalysis (FlowAnalysisContext fc)
894                 {
895                         InstanceExpr.FlowAnalysis (fc);
896                         if (arguments != null)
897                                 arguments.FlowAnalysis (fc);
898                 }
899
900                 protected override Expression DoResolve (ResolveContext ec)
901                 {               
902                         TypeSpec del_type = InstanceExpr.Type;
903                         if (del_type == null)
904                                 return null;
905
906                         //
907                         // Do only core overload resolution the rest of the checks has been
908                         // done on primary expression
909                         //
910                         method = Delegate.GetInvokeMethod (del_type);
911                         var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
912                         var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
913                         if (valid == null && !res.BestCandidateIsDynamic)
914                                 return null;
915
916                         type = method.ReturnType;
917                         if (conditionalAccessReceiver)
918                                 type = LiftMemberType (ec, type);
919
920                         eclass = ExprClass.Value;
921                         return this;
922                 }
923
924                 public override void Emit (EmitContext ec)
925                 {
926                         if (conditionalAccessReceiver) {
927                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
928                         }
929
930                         //
931                         // Invocation on delegates call the virtual Invoke member
932                         // so we are always `instance' calls
933                         //
934                         var call = new CallEmitter ();
935                         call.InstanceExpression = InstanceExpr;
936                         call.Emit (ec, method, arguments, loc);
937
938                         if (conditionalAccessReceiver)
939                                 ec.CloseConditionalAccess (type.IsNullableType && type !=  method.ReturnType ? type : null);
940                 }
941
942                 public override void EmitStatement (EmitContext ec)
943                 {
944                         if (conditionalAccessReceiver) {
945                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
946                                         Statement = true
947                                 };
948                         }
949
950                         var call = new CallEmitter ();
951                         call.InstanceExpression = InstanceExpr;
952                         call.EmitStatement (ec, method, arguments, loc);
953
954                         if (conditionalAccessReceiver)
955                                 ec.CloseConditionalAccess (null);
956                 }
957
958                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
959                 {
960                         return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
961                 }
962         }
963 }