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