Merge pull request #1870 from saper/langinfo_h
[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                         base.FlowAnalysis (fc);
628                         method_group.FlowAnalysis (fc);
629
630                         if (conditional_access_receiver)
631                                 fc.ConditionalAccessEnd ();
632                 }
633
634                 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
635                 {
636                         var invoke_method = Delegate.GetInvokeMethod (type);
637                         string member_name = method_group.InstanceExpression != null ?
638                                 Delegate.FullDelegateDesc (method) :
639                                 TypeManager.GetFullNameSignature (method);
640
641                         ec.Report.SymbolRelatedToPreviousError (type);
642                         ec.Report.SymbolRelatedToPreviousError (method);
643                         if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
644                                 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",
645                                         method.ReturnType.GetSignatureForError (), member_name,
646                                         invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
647                                 return;
648                         }
649
650                         if (return_type == null) {
651                                 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
652                                         member_name, Delegate.FullDelegateDesc (invoke_method));
653                                 return;
654                         }
655
656                         ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
657                                 return_type.GetSignatureForError (), member_name,
658                                 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
659                 }
660
661                 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
662                 {
663 //                      if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
664 //                              return false;
665
666                         var invoke = Delegate.GetInvokeMethod (target_type);
667
668                         Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
669                         mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
670                         return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
671                 }
672
673                 #region IErrorHandler Members
674
675                 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
676                 {
677                         return false;
678                 }
679
680                 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
681                 {
682                         Error_ConversionFailed (rc, best as MethodSpec, null);
683                         return true;
684                 }
685
686                 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
687                 {
688                         Error_ConversionFailed (rc, best as MethodSpec, null);
689                         return true;
690                 }
691
692                 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
693                 {
694                         return false;
695                 }
696
697                 #endregion
698         }
699
700         //
701         // Created from the conversion code
702         //
703         public class ImplicitDelegateCreation : DelegateCreation
704         {
705                 Field mg_cache;
706
707                 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
708                 {
709                         type = delegateType;
710                         this.method_group = mg;
711                         this.loc = loc;
712                 }
713
714                 //
715                 // Returns true when type is MVAR or has MVAR reference
716                 //
717                 public static bool ContainsMethodTypeParameter (TypeSpec type)
718                 {
719                         var tps = type as TypeParameterSpec;
720                         if (tps != null)
721                                 return tps.IsMethodOwned;
722
723                         var ec = type as ElementTypeSpec;
724                         if (ec != null)
725                                 return ContainsMethodTypeParameter (ec.Element);
726
727                         foreach (var t in type.TypeArguments) {
728                                 if (ContainsMethodTypeParameter (t)) {
729                                         return true;
730                                 }
731                         }
732
733                         if (type.IsNested)
734                                 return ContainsMethodTypeParameter (type.DeclaringType);
735
736                         return false;
737                 }
738                 
739                 bool HasMvar ()
740                 {
741                         if (ContainsMethodTypeParameter (type))
742                                 return false;
743
744                         var best = method_group.BestCandidate;
745                         if (ContainsMethodTypeParameter (best.DeclaringType))
746                                 return false;
747
748                         if (best.TypeArguments != null) {
749                                 foreach (var ta in best.TypeArguments) {
750                                         if (ContainsMethodTypeParameter (ta))
751                                                 return false;
752                                 }
753                         }
754
755                         return true;
756                 }
757
758                 protected override Expression DoResolve (ResolveContext ec)
759                 {
760                         var expr = base.DoResolve (ec);
761                         if (expr == null)
762                                 return ErrorExpression.Instance;
763
764                         if (ec.IsInProbingMode)
765                                 return expr;
766
767                         //
768                         // Cache any static delegate creation
769                         //
770                         if (method_group.InstanceExpression != null)
771                                 return expr;
772
773                         //
774                         // Cannot easily cache types with MVAR
775                         //
776                         if (!HasMvar ())
777                                 return expr;
778
779                         //
780                         // Create type level cache for a delegate instance
781                         //
782                         var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
783                         int id = parent.MethodGroupsCounter++;
784
785                         mg_cache = new Field (parent, new TypeExpression (type, loc),
786                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
787                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
788                         mg_cache.Define ();
789                         parent.AddField (mg_cache);
790
791                         return expr;
792                 }
793
794                 public override void Emit (EmitContext ec)
795                 {
796                         Label l_initialized = ec.DefineLabel ();
797
798                         if (mg_cache != null) {
799                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
800                                 ec.Emit (OpCodes.Brtrue_S, l_initialized);
801                         }
802
803                         base.Emit (ec);
804
805                         if (mg_cache != null) {
806                                 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
807                                 ec.MarkLabel (l_initialized);
808                                 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
809                         }
810                 }
811         }
812         
813         //
814         // A delegate-creation-expression, invoked from the `New' class 
815         //
816         public class NewDelegate : DelegateCreation
817         {
818                 public Arguments Arguments;
819
820                 //
821                 // This constructor is invoked from the `New' expression
822                 //
823                 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
824                 {
825                         this.type = type;
826                         this.Arguments = Arguments;
827                         this.loc  = loc; 
828                 }
829
830                 protected override Expression DoResolve (ResolveContext ec)
831                 {
832                         if (Arguments == null || Arguments.Count != 1) {
833                                 ec.Report.Error (149, loc, "Method name expected");
834                                 return null;
835                         }
836
837                         Argument a = Arguments [0];
838                         if (!a.ResolveMethodGroup (ec))
839                                 return null;
840
841                         Expression e = a.Expr;
842
843                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
844                         if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
845                                 e = ame.Compatible (ec, type);
846                                 if (e == null)
847                                         return null;
848
849                                 return e.Resolve (ec);
850                         }
851
852                         method_group = e as MethodGroupExpr;
853                         if (method_group == null) {
854                                 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
855                                         e = Convert.ImplicitConversionRequired (ec, e, type, loc);
856                                 } else if (!e.Type.IsDelegate) {
857                                         e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
858                                         return null;
859                                 }
860
861                                 //
862                                 // An argument is not a method but another delegate
863                                 //
864                                 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
865                                 method_group.InstanceExpression = e;
866                         }
867
868                         return base.DoResolve (ec);
869                 }
870         }
871
872         //
873         // Invocation converted to delegate Invoke call
874         //
875         class DelegateInvocation : ExpressionStatement
876         {
877                 readonly Expression InstanceExpr;
878                 readonly bool conditionalAccessReceiver;
879                 Arguments arguments;
880                 MethodSpec method;
881                 
882                 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
883                 {
884                         this.InstanceExpr = instance_expr;
885                         this.arguments = args;
886                         this.conditionalAccessReceiver = conditionalAccessReceiver;
887                         this.loc = loc;
888                 }
889
890                 public override bool ContainsEmitWithAwait ()
891                 {
892                         return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
893                 }
894                 
895                 public override Expression CreateExpressionTree (ResolveContext ec)
896                 {
897                         Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
898                                 InstanceExpr.CreateExpressionTree (ec));
899
900                         return CreateExpressionFactoryCall (ec, "Invoke", args);
901                 }
902
903                 public override void FlowAnalysis (FlowAnalysisContext fc)
904                 {
905                         InstanceExpr.FlowAnalysis (fc);
906                         if (arguments != null)
907                                 arguments.FlowAnalysis (fc);
908                 }
909
910                 protected override Expression DoResolve (ResolveContext ec)
911                 {               
912                         TypeSpec del_type = InstanceExpr.Type;
913                         if (del_type == null)
914                                 return null;
915
916                         //
917                         // Do only core overload resolution the rest of the checks has been
918                         // done on primary expression
919                         //
920                         method = Delegate.GetInvokeMethod (del_type);
921                         var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
922                         var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
923                         if (valid == null && !res.BestCandidateIsDynamic)
924                                 return null;
925
926                         type = method.ReturnType;
927                         if (conditionalAccessReceiver)
928                                 type = LiftMemberType (ec, type);
929
930                         eclass = ExprClass.Value;
931                         return this;
932                 }
933
934                 public override void Emit (EmitContext ec)
935                 {
936                         if (conditionalAccessReceiver) {
937                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
938                         }
939
940                         //
941                         // Invocation on delegates call the virtual Invoke member
942                         // so we are always `instance' calls
943                         //
944                         var call = new CallEmitter ();
945                         call.InstanceExpression = InstanceExpr;
946                         call.Emit (ec, method, arguments, loc);
947
948                         if (conditionalAccessReceiver)
949                                 ec.CloseConditionalAccess (type.IsNullableType && type !=  method.ReturnType ? type : null);
950                 }
951
952                 public override void EmitStatement (EmitContext ec)
953                 {
954                         if (conditionalAccessReceiver) {
955                                 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
956                                         Statement = true
957                                 };
958                         }
959
960                         var call = new CallEmitter ();
961                         call.InstanceExpression = InstanceExpr;
962                         call.EmitStatement (ec, method, arguments, loc);
963
964                         if (conditionalAccessReceiver)
965                                 ec.CloseConditionalAccess (null);
966                 }
967
968                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
969                 {
970                         return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
971                 }
972         }
973 }