New tests.
[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 //
14
15 using System;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Collections.Generic;
19
20 namespace Mono.CSharp {
21
22         //
23         // Delegate container implementation
24         //
25         public class Delegate : TypeContainer
26         {
27                 FullNamedExpression ReturnType;
28                 public readonly ParametersCompiled Parameters;
29
30                 Constructor Constructor;
31                 Method InvokeBuilder;
32                 Method BeginInvokeBuilder;
33                 Method EndInvokeBuilder;
34
35                 static readonly string[] attribute_targets = new string [] { "type", "return" };
36
37                 public static readonly string InvokeMethodName = "Invoke";
38                 
39                 Expression instance_expr;
40                 ReturnParameter return_attributes;
41
42                 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
43
44                 const Modifiers AllowedModifiers =
45                         Modifiers.NEW |
46                         Modifiers.PUBLIC |
47                         Modifiers.PROTECTED |
48                         Modifiers.INTERNAL |
49                         Modifiers.UNSAFE |
50                         Modifiers.PRIVATE;
51
52                 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
53                                  Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
54                                  Attributes attrs)
55                         : base (ns, parent, name, attrs, MemberKind.Delegate)
56
57                 {
58                         this.ReturnType = type;
59                         ModFlags        = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
60                                                            IsTopLevel ? Modifiers.INTERNAL :
61                                                            Modifiers.PRIVATE, name.Location, Report);
62                         Parameters      = param_list;
63                         spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
64                 }
65
66                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
67                 {
68                         if (a.Target == AttributeTargets.ReturnValue) {
69                                 if (return_attributes == null)
70                                         return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
71
72                                 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
73                                 return;
74                         }
75
76                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
77                 }
78
79                 public override AttributeTargets AttributeTargets {
80                         get {
81                                 return AttributeTargets.Delegate;
82                         }
83                 }
84
85                 public override TypeSpec BaseType {
86                         get {
87                                 return TypeManager.multicast_delegate_type;
88                         }
89                 }
90
91                 protected override bool DoDefineMembers ()
92                 {
93                         var ctor_parameters = ParametersCompiled.CreateFullyResolved (
94                                 new [] {
95                                         new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
96                                         new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
97                                 },
98                                 new [] {
99                                         TypeManager.object_type,
100                                         TypeManager.intptr_type
101                                 }
102                         );
103
104                         Constructor = new Constructor (this, System.Reflection.ConstructorInfo.ConstructorName,
105                                 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
106                         Constructor.Define ();
107
108                         //
109                         // Here the various methods like Invoke, BeginInvoke etc are defined
110                         //
111                         // First, call the `out of band' special method for
112                         // defining recursively any types we need:
113                         //
114                         var p = Parameters;
115
116                         if (!p.Resolve (this))
117                                 return false;
118
119                         //
120                         // Invoke method
121                         //
122
123                         // Check accessibility
124                         foreach (var partype in p.Types) {
125                                 if (!IsAccessibleAs (partype)) {
126                                         Report.SymbolRelatedToPreviousError (partype);
127                                         Report.Error (59, Location,
128                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
129                                                 TypeManager.CSharpName (partype), GetSignatureForError ());
130                                 }
131                         }
132
133                         ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
134                         if (ReturnType == null)
135                                 return false;
136
137                         var ret_type = ReturnType.Type;
138
139                         //
140                         // We don't have to check any others because they are all
141                         // guaranteed to be accessible - they are standard types.
142                         //
143                         if (!IsAccessibleAs (ret_type)) {
144                                 Report.SymbolRelatedToPreviousError (ret_type);
145                                 Report.Error (58, Location,
146                                                   "Inconsistent accessibility: return type `" +
147                                                   TypeManager.CSharpName (ret_type) + "' is less " +
148                                                   "accessible than delegate `" + GetSignatureForError () + "'");
149                                 return false;
150                         }
151
152                         CheckProtectedModifier ();
153
154                         if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
155                                 Method.Error1599 (Location, ret_type, Report);
156                                 return false;
157                         }
158
159                         TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
160
161                         InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
162                         InvokeBuilder.Define ();
163
164                         //
165                         // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
166                         //
167                         if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null && !IsCompilerGenerated) {
168                                 DefineAsyncMethods (Parameters.CallingConvention);
169                         }
170
171                         return true;
172                 }
173
174                 void DefineAsyncMethods (CallingConventions cc)
175                 {
176                         //
177                         // BeginInvoke
178                         //
179                         Parameter[] compiled = new Parameter[Parameters.Count];
180                         for (int i = 0; i < compiled.Length; ++i)
181                                 compiled[i] = new Parameter (new TypeExpression (Parameters.Types[i], Location),
182                                         Parameters.FixedParameters[i].Name,
183                                         Parameters.FixedParameters[i].ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
184                                         null, Location);
185
186                         ParametersCompiled async_parameters = new ParametersCompiled (Compiler, compiled);
187
188                         async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
189                                 new Parameter[] {
190                                         new Parameter (new TypeExpression (TypeManager.asynccallback_type, Location), "callback", Parameter.Modifier.NONE, null, Location),
191                                         new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
192                                 },
193                                 new [] {
194                                         TypeManager.asynccallback_type,
195                                         TypeManager.object_type
196                                 }
197                         );
198
199                         BeginInvokeBuilder = new Method (this, null,
200                                 new TypeExpression (TypeManager.iasyncresult_type, Location), MethodModifiers,
201                                 new MemberName ("BeginInvoke"), async_parameters, null);
202                         BeginInvokeBuilder.Define ();
203
204                         //
205                         // EndInvoke is a bit more interesting, all the parameters labeled as
206                         // out or ref have to be duplicated here.
207                         //
208
209                         //
210                         // Define parameters, and count out/ref parameters
211                         //
212                         ParametersCompiled end_parameters;
213                         int out_params = 0;
214
215                         foreach (Parameter p in Parameters.FixedParameters) {
216                                 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
217                                         ++out_params;
218                         }
219
220                         if (out_params > 0) {
221                                 var end_param_types = new TypeSpec [out_params];
222                                 Parameter[] end_params = new Parameter[out_params];
223
224                                 int param = 0;
225                                 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
226                                         Parameter p = Parameters [i];
227                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
228                                                 continue;
229
230                                         end_param_types[param] = Parameters.Types[i];
231                                         end_params[param] = p;
232                                         ++param;
233                                 }
234                                 end_parameters = ParametersCompiled.CreateFullyResolved (end_params, end_param_types);
235                         } else {
236                                 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
237                         }
238
239                         end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
240                                 new Parameter (
241                                         new TypeExpression (TypeManager.iasyncresult_type, Location),
242                                         "result", Parameter.Modifier.NONE, null, Location),
243                                 TypeManager.iasyncresult_type);
244
245                         //
246                         // Create method, define parameters, register parameters with type system
247                         //
248                         EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
249                         EndInvokeBuilder.Define ();
250                 }
251
252                 public override void DefineConstants ()
253                 {
254                         if (!Parameters.IsEmpty && Parameters[Parameters.Count - 1].HasDefaultValue) {
255                                 var rc = new ResolveContext (this);
256                                 Parameters.ResolveDefaultValues (rc);
257                         }
258                 }
259
260                 public override void EmitType ()
261                 {
262                         if (ReturnType.Type == InternalType.Dynamic) {
263                                 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
264                                 PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
265                         } else {
266                                 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType.Type);
267                                 if (trans_flags != null) {
268                                         var pa = PredefinedAttributes.Get.DynamicTransform;
269                                         if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
270                                                 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
271                                                 return_attributes.Builder.SetCustomAttribute (
272                                                         new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
273                                         }
274                                 }
275                         }
276
277                         Parameters.ApplyAttributes (InvokeBuilder.MethodBuilder);
278                         
279                         Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
280                         InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
281
282                         if (BeginInvokeBuilder != null) {
283                                 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (BeginInvokeBuilder.MethodBuilder);
284
285                                 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
286                                 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
287                         }
288
289                         if (OptAttributes != null) {
290                                 OptAttributes.Emit ();
291                         }
292
293                         base.Emit ();
294                 }
295
296                 protected override TypeAttributes TypeAttr {
297                         get {
298                                 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
299                                         TypeAttributes.Class | TypeAttributes.Sealed |
300                                         base.TypeAttr;
301                         }
302                 }
303
304                 public override string[] ValidAttributeTargets {
305                         get {
306                                 return attribute_targets;
307                         }
308                 }
309
310                 //TODO: duplicate
311                 protected override bool VerifyClsCompliance ()
312                 {
313                         if (!base.VerifyClsCompliance ()) {
314                                 return false;
315                         }
316
317                         Parameters.VerifyClsCompliance (this);
318
319                         if (!ReturnType.Type.IsCLSCompliant ()) {
320                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
321                                         GetSignatureForError ());
322                         }
323                         return true;
324                 }
325
326
327                 public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
328                 {
329                         var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
330                         return (MethodSpec) ctor;
331                 }
332
333                 //
334                 // Returns the "Invoke" from a delegate type
335                 //
336                 public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
337                 {
338                         var invoke = MemberCache.FindMember (delType,
339                                 MemberFilter.Method (InvokeMethodName, 0, null, null),
340                                 BindingRestriction.DeclaredOnly);
341
342                         return (MethodSpec) invoke;
343                 }
344
345                 public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
346                 {
347                         var invoke_mb = GetInvokeMethod (ctx, delType);
348                         return invoke_mb.Parameters;
349                 }
350
351                 //
352                 // 15.2 Delegate compatibility
353                 //
354                 public static bool IsTypeCovariant (Expression a, TypeSpec b)
355                 {
356                         //
357                         // For each value parameter (a parameter with no ref or out modifier), an 
358                         // identity conversion or implicit reference conversion exists from the
359                         // parameter type in D to the corresponding parameter type in M
360                         //
361                         if (a.Type == b)
362                                 return true;
363
364                         if (RootContext.Version == LanguageVersion.ISO_1)
365                                 return false;
366
367                         return Convert.ImplicitReferenceConversionExists (a, b);
368                 }
369
370                 public static string FullDelegateDesc (MethodSpec invoke_method)
371                 {
372                         return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
373                 }
374                 
375                 public Expression InstanceExpression {
376                         get {
377                                 return instance_expr;
378                         }
379                         set {
380                                 instance_expr = value;
381                         }
382                 }
383         }
384
385         //
386         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
387         //
388         public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
389         {
390                 protected MethodSpec constructor_method;
391                 protected MethodSpec delegate_method;
392                 // We keep this to handle IsBase only
393                 protected MethodGroupExpr method_group;
394                 protected Expression delegate_instance_expression;
395
396                 // TODO: Should either cache it or use interface to abstract it
397                 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, Location loc)
398                 {
399                         Arguments delegate_arguments = new Arguments (pd.Count);
400                         for (int i = 0; i < pd.Count; ++i) {
401                                 Argument.AType atype_modifier;
402                                 TypeSpec atype = pd.Types [i];
403                                 switch (pd.FixedParameters [i].ModFlags) {
404                                 case Parameter.Modifier.REF:
405                                         atype_modifier = Argument.AType.Ref;
406                                         //atype = atype.GetElementType ();
407                                         break;
408                                 case Parameter.Modifier.OUT:
409                                         atype_modifier = Argument.AType.Out;
410                                         //atype = atype.GetElementType ();
411                                         break;
412                                 default:
413                                         atype_modifier = 0;
414                                         break;
415                                 }
416                                 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
417                         }
418                         return delegate_arguments;
419                 }
420
421                 public override Expression CreateExpressionTree (ResolveContext ec)
422                 {
423                         MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
424
425                         Arguments args = new Arguments (3);
426                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
427                         args.Add (new Argument (new NullLiteral (loc)));
428                         args.Add (new Argument (new TypeOfMethod (delegate_method, loc)));
429                         Expression e = new Invocation (ma, args).Resolve (ec);
430                         if (e == null)
431                                 return null;
432
433                         e = Convert.ExplicitConversion (ec, e, type, loc);
434                         if (e == null)
435                                 return null;
436
437                         return e.CreateExpressionTree (ec);
438                 }
439
440                 protected override Expression DoResolve (ResolveContext ec)
441                 {
442                         constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
443
444                         var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
445                         method_group.DelegateType = type;
446                         method_group.CustomErrorHandler = this;
447
448                         Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, loc);
449                         method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
450                         if (method_group == null)
451                                 return null;
452
453                         delegate_method = (MethodSpec) method_group;
454                         
455                         if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
456                                 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
457                                         TypeManager.GetFullNameSignature (delegate_method));
458                                 return null;
459                         }               
460                         
461                         Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
462
463                         ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
464                         if (emg != null) {
465                                 delegate_instance_expression = emg.ExtensionExpression;
466                                 TypeSpec e_type = delegate_instance_expression.Type;
467                                 if (TypeManager.IsValueType (e_type)) {
468                                         ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
469                                                 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
470                                 }
471                         }
472
473                         TypeSpec rt = delegate_method.ReturnType;
474                         Expression ret_expr = new TypeExpression (rt, loc);
475                         if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
476                                 Error_ConversionFailed (ec, delegate_method, ret_expr);
477                         }
478
479                         if (delegate_method.IsConditionallyExcluded (loc)) {
480                                 ec.Report.SymbolRelatedToPreviousError (delegate_method);
481                                 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
482                                 if (m != null && m.IsPartialDefinition) {
483                                         ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
484                                                 delegate_method.GetSignatureForError ());
485                                 } else {
486                                         ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
487                                                 TypeManager.CSharpSignature (delegate_method));
488                                 }
489                         }
490
491                         DoResolveInstanceExpression (ec);
492                         eclass = ExprClass.Value;
493                         return this;
494                 }
495
496                 void DoResolveInstanceExpression (ResolveContext ec)
497                 {
498                         //
499                         // Argument is another delegate
500                         //
501                         if (delegate_instance_expression != null)
502                                 return;
503
504                         if (method_group.IsStatic) {
505                                 delegate_instance_expression = null;
506                                 return;
507                         }
508
509                         Expression instance = method_group.InstanceExpression;
510                         if (instance != null && instance != EmptyExpression.Null) {
511                                 delegate_instance_expression = instance;
512                                 TypeSpec instance_type = delegate_instance_expression.Type;
513                                 if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
514                                         delegate_instance_expression = new BoxedCast (
515                                                 delegate_instance_expression, TypeManager.object_type);
516                                 }
517                         } else {
518                                 delegate_instance_expression = ec.GetThis (loc);
519                         }
520                 }
521                 
522                 public override void Emit (EmitContext ec)
523                 {
524                         if (delegate_instance_expression == null)
525                                 ec.Emit (OpCodes.Ldnull);
526                         else
527                                 delegate_instance_expression.Emit (ec);
528
529                         // Any delegate must be sealed
530                         if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
531                                 ec.Emit (OpCodes.Dup);
532                                 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
533                         } else {
534                                 ec.Emit (OpCodes.Ldftn, delegate_method);
535                         }
536
537                         ec.Emit (OpCodes.Newobj, constructor_method);
538                 }
539
540                 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
541                 {
542                         var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
543                         string member_name = delegate_instance_expression != null ?
544                                 Delegate.FullDelegateDesc (method) :
545                                 TypeManager.GetFullNameSignature (method);
546
547                         ec.Report.SymbolRelatedToPreviousError (type);
548                         ec.Report.SymbolRelatedToPreviousError (method);
549                         if (RootContext.Version == LanguageVersion.ISO_1) {
550                                 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",
551                                         TypeManager.CSharpName (method.ReturnType), member_name,
552                                         TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
553                                 return;
554                         }
555                         if (return_type == null) {
556                                 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
557                                         member_name, Delegate.FullDelegateDesc (invoke_method));
558                                 return;
559                         }
560
561                         ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
562                                 return_type.GetSignatureForError (), member_name,
563                                 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
564                 }
565
566                 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
567                 {
568                         if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
569                                 return false;
570
571                         mg.DelegateType = target_type;
572                         var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
573
574                         Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, mg.Location);
575                         return mg.OverloadResolve (ec, ref arguments, true, mg.Location) != null;
576                 }
577
578                 #region IErrorHandler Members
579
580                 public bool NoExactMatch (ResolveContext ec, MethodSpec method)
581                 {
582                         if (method.IsGeneric)
583                                 return false;
584
585                         Error_ConversionFailed (ec, method, null);
586                         return true;
587                 }
588
589                 public bool AmbiguousCall (ResolveContext ec, MethodSpec ambiguous)
590                 {
591                         return false;
592                 }
593
594                 #endregion
595         }
596
597         //
598         // Created from the conversion code
599         //
600         public class ImplicitDelegateCreation : DelegateCreation
601         {
602                 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
603                 {
604                         type = t;
605                         this.method_group = mg;
606                         loc = l;
607                 }
608
609                 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
610                                                  TypeSpec target_type, Location loc)
611                 {
612                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
613                         return d.DoResolve (ec);
614                 }
615         }
616         
617         //
618         // A delegate-creation-expression, invoked from the `New' class 
619         //
620         public class NewDelegate : DelegateCreation
621         {
622                 public Arguments Arguments;
623
624                 //
625                 // This constructor is invoked from the `New' expression
626                 //
627                 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
628                 {
629                         this.type = type;
630                         this.Arguments = Arguments;
631                         this.loc  = loc; 
632                 }
633
634                 protected override Expression DoResolve (ResolveContext ec)
635                 {
636                         if (Arguments == null || Arguments.Count != 1) {
637                                 ec.Report.Error (149, loc, "Method name expected");
638                                 return null;
639                         }
640
641                         Argument a = Arguments [0];
642                         if (!a.ResolveMethodGroup (ec))
643                                 return null;
644
645                         Expression e = a.Expr;
646
647                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
648                         if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
649                                 e = ame.Compatible (ec, type);
650                                 if (e == null)
651                                         return null;
652
653                                 return e.Resolve (ec);
654                         }
655
656                         method_group = e as MethodGroupExpr;
657                         if (method_group == null) {
658                                 if (e.Type == InternalType.Dynamic) {
659                                         e = Convert.ImplicitConversionRequired (ec, e, type, loc);
660                                 } else if (!e.Type.IsDelegate) {
661                                         e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
662                                         return null;
663                                 }
664
665                                 //
666                                 // An argument is not a method but another delegate
667                                 //
668                                 delegate_instance_expression = e;
669                                 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
670                         }
671
672                         return base.DoResolve (ec);
673                 }
674         }
675
676         //
677         // Invocation converted to delegate Invoke call
678         //
679         class DelegateInvocation : ExpressionStatement
680         {
681                 readonly Expression InstanceExpr;
682                 Arguments arguments;
683                 MethodSpec method;
684                 
685                 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
686                 {
687                         this.InstanceExpr = instance_expr;
688                         this.arguments = args;
689                         this.loc = loc;
690                 }
691                 
692                 public override Expression CreateExpressionTree (ResolveContext ec)
693                 {
694                         Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
695                                 InstanceExpr.CreateExpressionTree (ec));
696
697                         return CreateExpressionFactoryCall (ec, "Invoke", args);
698                 }
699
700                 protected override Expression DoResolve (ResolveContext ec)
701                 {
702                         if (InstanceExpr is EventExpr) {
703                                 ((EventExpr) InstanceExpr).Error_CannotAssign (ec);
704                                 return null;
705                         }
706                         
707                         TypeSpec del_type = InstanceExpr.Type;
708                         if (del_type == null)
709                                 return null;
710                         
711                         method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
712                         var mb = method;
713                         var me = new MethodGroupExpr (mb, del_type, loc);
714                         me.InstanceExpression = InstanceExpr;
715
716                         AParametersCollection pd = mb.Parameters;
717                         int pd_count = pd.Count;
718
719                         int arg_count = arguments == null ? 0 : arguments.Count;
720
721                         bool params_method = pd.HasParams;
722                         bool is_params_applicable = false;
723                         bool is_applicable = me.IsApplicable (ec, ref arguments, arg_count, ref mb, ref is_params_applicable) == 0;
724                         if (arguments != null)
725                                 arg_count = arguments.Count;
726
727                         if (!is_applicable && !params_method && arg_count != pd_count) {
728                                 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
729                                         TypeManager.CSharpName (del_type), arg_count.ToString ());
730                         } else if (arguments == null || !arguments.HasDynamic) {
731                                 me.VerifyArgumentsCompat (ec, ref arguments, arg_count, mb,
732                                         is_params_applicable || (!is_applicable && params_method), false, loc);
733                         }
734
735                         type = method.ReturnType;
736                         eclass = ExprClass.Value;
737                         return this;
738                 }
739
740                 public override void Emit (EmitContext ec)
741                 {
742                         //
743                         // Invocation on delegates call the virtual Invoke member
744                         // so we are always `instance' calls
745                         //
746                         Invocation.EmitCall (ec, false, InstanceExpr, method, arguments, loc);
747                 }
748
749                 public override void EmitStatement (EmitContext ec)
750                 {
751                         Emit (ec);
752                         // 
753                         // Pop the return value if there is one
754                         //
755                         if (type != TypeManager.void_type)
756                                 ec.Emit (OpCodes.Pop);
757                 }
758
759                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
760                 {
761                         return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
762                 }
763         }
764 }