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