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