Merged into mcs.
[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 //
8 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 //
12 //
13
14 using System;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Text;
19
20 namespace Mono.CSharp {
21
22         /// <summary>
23         ///   Holds Delegates
24         /// </summary>
25         public class Delegate : DeclSpace {
26                 public Expression ReturnType;
27                 public Parameters      Parameters;
28
29                 public ConstructorBuilder ConstructorBuilder;
30                 public MethodBuilder      InvokeBuilder;
31                 public MethodBuilder      BeginInvokeBuilder;
32                 public MethodBuilder      EndInvokeBuilder;
33                 
34                 Type ret_type;
35
36                 static string[] attribute_targets = new string [] { "type", "return" };
37                 
38                 Expression instance_expr;
39                 MethodBase delegate_method;
40                 ReturnParameter return_attributes;
41         
42                 const int AllowedModifiers =
43                         Modifiers.NEW |
44                         Modifiers.PUBLIC |
45                         Modifiers.PROTECTED |
46                         Modifiers.INTERNAL |
47                         Modifiers.UNSAFE |
48                         Modifiers.PRIVATE;
49
50                 public Delegate (NamespaceEntry ns, DeclSpace parent, Expression type,
51                                  int mod_flags, MemberName name, Parameters param_list,
52                                  Attributes attrs)
53                         : base (ns, parent, name, attrs)
54
55                 {
56                         this.ReturnType = type;
57                         ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,
58                                                            IsTopLevel ? Modifiers.INTERNAL :
59                                                            Modifiers.PRIVATE, name.Location);
60                         Parameters      = param_list;
61                 }
62
63                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
64                 {
65                         if (a.Target == AttributeTargets.ReturnValue) {
66                                 if (return_attributes == null)
67                                         return_attributes = new ReturnParameter (InvokeBuilder, Location);
68
69                                 return_attributes.ApplyAttributeBuilder (a, cb);
70                                 return;
71                         }
72
73                         base.ApplyAttributeBuilder (a, cb);
74                 }
75
76                 public override TypeBuilder DefineType ()
77                 {
78                         if (TypeBuilder != null)
79                                 return TypeBuilder;
80
81 #if GMCS_SOURCE
82                         if (IsGeneric) {
83                                 foreach (TypeParameter type_param in TypeParameters)
84                                         if (!type_param.Resolve (this))
85                                                 return null;
86                         }
87 #endif
88                         
89                         if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
90                                 Namespace system = RootNamespace.Global.GetNamespace ("System", true);
91                                 TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
92                                 TypeManager.multicast_delegate_type = expr.Type;
93                         }
94
95                         if (TypeManager.multicast_delegate_type == null)
96                                 Report.Error (-100, Location, "Internal error: delegate used before " +
97                                               "System.MulticastDelegate is resolved.  This can only " +
98                                               "happen during corlib compilation, when using a delegate " +
99                                               "in any of the `core' classes.  See bug #72015 for details.");
100
101                         if (IsTopLevel) {
102                                 if (TypeManager.NamespaceClash (Name, Location))
103                                         return null;
104                                 
105                                 ModuleBuilder builder = CodeGen.Module.Builder;
106
107                                 TypeBuilder = builder.DefineType (
108                                         Name, TypeAttr, TypeManager.multicast_delegate_type);
109                         } else {
110                                 TypeBuilder builder = Parent.TypeBuilder;
111
112                                 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
113                                 TypeBuilder = builder.DefineNestedType (
114                                         name, TypeAttr, TypeManager.multicast_delegate_type);
115                         }
116
117                         TypeManager.AddUserType (this);
118
119 #if GMCS_SOURCE
120                         if (IsGeneric) {
121                                 string[] param_names = new string [TypeParameters.Length];
122                                 for (int i = 0; i < TypeParameters.Length; i++)
123                                         param_names [i] = TypeParameters [i].Name;
124
125                                 GenericTypeParameterBuilder[] gen_params;
126                                 gen_params = TypeBuilder.DefineGenericParameters (param_names);
127
128                                 int offset = CountTypeParameters - CurrentTypeParameters.Length;
129                                 for (int i = offset; i < gen_params.Length; i++)
130                                         CurrentTypeParameters [i - offset].Define (gen_params [i]);
131
132                                 foreach (TypeParameter type_param in CurrentTypeParameters) {
133                                         if (!type_param.Resolve (this))
134                                                 return null;
135                                 }
136
137                                 Expression current = new SimpleName (
138                                         MemberName.Basename, TypeParameters, Location);
139                                 current = current.ResolveAsTypeTerminal (this, false);
140                                 if (current == null)
141                                         return null;
142
143                                 CurrentType = current.Type;
144                         }
145 #endif
146
147                         return TypeBuilder;
148                 }
149
150                 public override bool Define ()
151                 {
152 #if GMCS_SOURCE
153                         if (IsGeneric) {
154                                 foreach (TypeParameter type_param in TypeParameters)
155                                         type_param.DefineType (this);
156                         }
157 #endif
158
159                         // FIXME: POSSIBLY make this static, as it is always constant
160                         //
161                         Type [] const_arg_types = new Type [2];
162                         const_arg_types [0] = TypeManager.object_type;
163                         const_arg_types [1] = TypeManager.intptr_type;
164
165                         const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
166                                 MethodAttributes.HideBySig | MethodAttributes.Public;
167
168                         ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
169                                                                             CallingConventions.Standard,
170                                                                             const_arg_types);
171
172                         ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
173                         ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
174                         //
175                         // HACK because System.Reflection.Emit is lame
176                         //
177                         Parameter [] fixed_pars = new Parameter [2];
178                         fixed_pars [0] = new Parameter (TypeManager.object_type, "object",
179                                                         Parameter.Modifier.NONE, null, Location);
180                         fixed_pars [1] = new Parameter (TypeManager.intptr_type, "method", 
181                                                         Parameter.Modifier.NONE, null, Location);
182                         Parameters const_parameters = new Parameters (fixed_pars);
183                         const_parameters.Resolve (null);
184                         
185                         TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
186                                 
187                         
188                         ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
189
190                         //
191                         // Here the various methods like Invoke, BeginInvoke etc are defined
192                         //
193                         // First, call the `out of band' special method for
194                         // defining recursively any types we need:
195                         
196                         if (!Parameters.Resolve (this))
197                                 return false;
198
199                         //
200                         // Invoke method
201                         //
202
203                         // Check accessibility
204                         foreach (Type partype in Parameters.Types){
205                                 if (!Parent.AsAccessible (partype, ModFlags)) {
206                                         Report.Error (59, Location,
207                                                       "Inconsistent accessibility: parameter type `" +
208                                                       TypeManager.CSharpName (partype) + "' is less " +
209                                                       "accessible than delegate `" + Name + "'");
210                                         return false;
211                                 }
212                         }
213                         
214                         ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
215                         if (ReturnType == null)
216                                 return false;
217
218                         ret_type = ReturnType.Type;
219             
220                         if (!Parent.AsAccessible (ret_type, ModFlags)) {
221                                 Report.Error (58, Location,
222                                               "Inconsistent accessibility: return type `" +
223                                               TypeManager.CSharpName (ret_type) + "' is less " +
224                                               "accessible than delegate `" + Name + "'");
225                                 return false;
226                         }
227
228                         if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
229                                 Method.Error1599 (Location, ret_type);
230                                 return false;
231                         }
232
233                         //
234                         // We don't have to check any others because they are all
235                         // guaranteed to be accessible - they are standard types.
236                         //
237                         
238                         CallingConventions cc = Parameters.CallingConvention;
239
240                         const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
241
242                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
243                                                                   mattr,                     
244                                                                   cc,
245                                                                   ret_type,                  
246                                                                   Parameters.Types);
247                         
248                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
249
250                         TypeManager.RegisterMethod (InvokeBuilder, Parameters);
251
252                         //
253                         // BeginInvoke
254                         //
255                         
256                         Parameters async_parameters = Parameters.MergeGenerated (Parameters, 
257                                 new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
258                                 new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
259                         
260                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
261                                 mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
262
263                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
264                         async_parameters.ApplyAttributes (BeginInvokeBuilder);
265                         TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
266
267                         //
268                         // EndInvoke is a bit more interesting, all the parameters labeled as
269                         // out or ref have to be duplicated here.
270                         //
271
272                         //
273                         // Define parameters, and count out/ref parameters
274                         //
275                         Parameters end_parameters;
276                         int out_params = 0;
277
278                         foreach (Parameter p in Parameters.FixedParameters) {
279                                 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
280                                         ++out_params;
281                         }
282
283                         if (out_params > 0) {
284                                 Type [] end_param_types = new Type [out_params];
285                                 Parameter [] end_params = new Parameter [out_params ];
286
287                                 int param = 0; 
288                                 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
289                                         Parameter p = Parameters.FixedParameters [i];
290                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
291                                                 continue;
292
293                                         end_param_types [param] = p.ExternalType();
294                                         end_params [param] = p;
295                                         ++param;
296                                 }
297                                 end_parameters = new Parameters (end_params, end_param_types);
298                         }
299                         else {
300                                 end_parameters = Parameters.EmptyReadOnlyParameters;
301                         }
302
303                         end_parameters = Parameters.MergeGenerated (end_parameters,
304                                 new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
305                         
306                         //
307                         // Create method, define parameters, register parameters with type system
308                         //
309                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.Types);
310                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
311
312                         end_parameters.ApplyAttributes (EndInvokeBuilder);
313                         TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
314
315                         return true;
316                 }
317
318                 public override void Emit ()
319                 {
320                         Parameters.ApplyAttributes (InvokeBuilder);
321
322                         if (OptAttributes != null) {
323                                 OptAttributes.Emit ();
324                         }
325
326                         base.Emit ();
327                 }
328
329                 protected override TypeAttributes TypeAttr {
330                         get {
331                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
332                                         TypeAttributes.Class | TypeAttributes.Sealed |
333                                         base.TypeAttr;
334                         }
335                 }
336
337                 public override string[] ValidAttributeTargets {
338                         get {
339                                 return attribute_targets;
340                         }
341                 }
342
343                 //TODO: duplicate
344                 protected override bool VerifyClsCompliance ()
345                 {
346                         if (!base.VerifyClsCompliance ()) {
347                                 return false;
348                         }
349
350                         Parameters.VerifyClsCompliance ();
351
352                         if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
353                                 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
354                         }
355                         return true;
356                 }
357
358                 //
359                 // Returns the MethodBase for "Invoke" from a delegate type, this is used
360                 // to extract the signature of a delegate.
361                 //
362                 public static MethodGroupExpr GetInvokeMethod (Type container_type, Type delegate_type, Location loc)
363                 {
364                         Expression ml = Expression.MemberLookup (container_type, null, delegate_type,
365                                 "Invoke", loc);
366
367                         MethodGroupExpr mg = ml as MethodGroupExpr;
368                         if (mg == null) {
369                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
370                                 return null;
371                         }
372
373                         return mg;
374                 }
375                 
376                 /// <summary>
377                 ///  Verifies whether the method in question is compatible with the delegate
378                 ///  Returns the method itself if okay and null if not.
379                 /// </summary>
380                 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
381                                                        MethodGroupExpr old_mg, MethodBase mb,
382                                                        Location loc)
383                 {
384                         MethodGroupExpr mg = GetInvokeMethod (container_type, delegate_type, loc);
385                         if (mg == null)
386                                 return null;
387
388                         if (old_mg.HasTypeArguments)
389                                 mg.HasTypeArguments = true;
390
391                         MethodBase invoke_mb = mg.Methods [0];
392                         ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
393
394 #if GMCS_SOURCE
395                         if (!mg.HasTypeArguments &&
396                             !TypeManager.InferTypeArguments (invoke_pd, ref mb))
397                                 return null;
398 #endif
399
400                         ParameterData pd = TypeManager.GetParameterData (mb);
401
402                         if (invoke_pd.Count != pd.Count)
403                                 return null;
404
405                         for (int i = pd.Count; i > 0; ) {
406                                 i--;
407
408                                 Type invoke_pd_type = invoke_pd.ParameterType (i);
409                                 Type pd_type = pd.ParameterType (i);
410                                 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
411                                 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
412
413                                 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
414                                 pd_type_mod &= ~Parameter.Modifier.PARAMS;
415
416                                 if (invoke_pd_type == pd_type &&
417                                     invoke_pd_type_mod == pd_type_mod)
418                                         continue;
419                                 
420                                 if (invoke_pd_type.IsSubclassOf (pd_type) && 
421                                     invoke_pd_type_mod == pd_type_mod)
422                                         if (RootContext.Version == LanguageVersion.ISO_1) {
423                                                 Report.FeatureIsNotStandardized (loc, "contravariance");
424                                                 return null;
425                                         } else
426                                                 continue;
427
428                                 return null;
429                         }
430
431                         Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
432                         Type mb_retval = ((MethodInfo) mb).ReturnType;
433                         if (invoke_mb_retval == mb_retval)
434                                 return mb;
435                         
436                         if (mb_retval.IsSubclassOf (invoke_mb_retval))
437                                 if (RootContext.Version == LanguageVersion.ISO_1) {
438                                         Report.FeatureIsNotStandardized (loc, "covariance");
439                                         return null;
440                                 }
441                                 else
442                                         return mb;
443                         
444                         return null;
445                 }
446
447                 // <summary>
448                 //  Verifies whether the invocation arguments are compatible with the
449                 //  delegate's target method
450                 // </summary>
451                 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
452                                                         ArrayList args, Location loc)
453                 {
454                         int arg_count;
455
456                         if (args == null)
457                                 arg_count = 0;
458                         else
459                                 arg_count = args.Count;
460
461                         Expression ml = Expression.MemberLookup (
462                                 ec.ContainerType, delegate_type, "Invoke", loc);
463
464                         MethodGroupExpr me = ml as MethodGroupExpr;
465                         if (me == null) {
466                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
467                                 return false;
468                         }
469                         
470                         MethodBase mb = me.Methods [0];
471                         ParameterData pd = TypeManager.GetParameterData (mb);
472
473                         int pd_count = pd.Count;
474
475                         bool params_method = pd.HasParams;
476                         bool is_params_applicable = false;
477                         bool is_applicable = Invocation.IsApplicable (ec, me, args, arg_count, ref mb);
478
479                         if (!is_applicable && params_method &&
480                             Invocation.IsParamsMethodApplicable (ec, me, args, arg_count, ref mb))
481                                 is_applicable = is_params_applicable = true;
482
483                         if (!is_applicable && !params_method && arg_count != pd_count) {
484                                 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
485                                         TypeManager.CSharpName (delegate_type), arg_count.ToString ());
486                                 return false;
487                         }
488
489                         return Invocation.VerifyArgumentsCompat (
490                                         ec, args, arg_count, mb, 
491                                         is_params_applicable || (!is_applicable && params_method),
492                                         delegate_type, false, loc);
493                 }
494                 
495                 /// <summary>
496                 ///  Verifies whether the delegate in question is compatible with this one in
497                 ///  order to determine if instantiation from the same is possible.
498                 /// </summary>
499                 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Location loc)
500                 {
501                         Expression ml = Expression.MemberLookup (
502                                 ec.ContainerType, delegate_type, "Invoke", loc);
503                         
504                         if (!(ml is MethodGroupExpr)) {
505                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
506                                 return false;
507                         }
508                         
509                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
510                         ParameterData pd = TypeManager.GetParameterData (mb);
511
512                         Expression probe_ml = Expression.MemberLookup (
513                                 ec.ContainerType, delegate_type, "Invoke", loc);
514                         
515                         if (!(probe_ml is MethodGroupExpr)) {
516                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
517                                 return false;
518                         }
519                         
520                         MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
521                         ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
522                         
523                         if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
524                                 return false;
525
526                         if (pd.Count != probe_pd.Count)
527                                 return false;
528
529                         for (int i = pd.Count; i > 0; ) {
530                                 i--;
531
532                                 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
533                                     pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
534                                         return false;
535                         }
536                         
537                         return true;
538                 }
539                 
540                 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
541                 {
542                         StringBuilder sb = new StringBuilder ();
543                         sb.Append (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
544                         sb.Append (" ");
545                         sb.Append (TypeManager.CSharpName (del_type));
546                         sb.Append (pd.GetSignatureForError ());
547                         return sb.ToString ();                  
548                 }
549                 
550                 // Hack around System.Reflection as found everywhere else
551                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
552                                                         MemberFilter filter, object criteria)
553                 {
554                         ArrayList members = new ArrayList (2);
555
556                         if ((mt & MemberTypes.Constructor) != 0) {
557                                 if (ConstructorBuilder != null && filter (ConstructorBuilder, criteria))
558                                         members.Add (ConstructorBuilder);
559                         }
560
561                         if ((mt & MemberTypes.Method) != 0) {
562                                 if (InvokeBuilder != null)
563                                 if (filter (InvokeBuilder, criteria))
564                                         members.Add (InvokeBuilder);
565
566                                 if (BeginInvokeBuilder != null)
567                                 if (filter (BeginInvokeBuilder, criteria))
568                                         members.Add (BeginInvokeBuilder);
569
570                                 if (EndInvokeBuilder != null)
571                                 if (filter (EndInvokeBuilder, criteria))
572                                         members.Add (EndInvokeBuilder);
573                         }
574
575                         return new MemberList (members);
576                 }
577
578                 public override MemberCache MemberCache {
579                         get {
580                                 return null;
581                         }
582                 }
583
584                 public Expression InstanceExpression {
585                         get {
586                                 return instance_expr;
587                         }
588                         set {
589                                 instance_expr = value;
590                         }
591                 }
592
593                 public MethodBase TargetMethod {
594                         get {
595                                 return delegate_method;
596                         }
597                         set {
598                                 delegate_method = value;
599                         }
600                 }
601
602                 public Type TargetReturnType {
603                         get {
604                                 return ret_type;
605                         }
606                 }
607
608                 public override AttributeTargets AttributeTargets {
609                         get {
610                                 return AttributeTargets.Delegate;
611                         }
612                 }
613
614                 //
615                 //   Represents header string for documentation comment.
616                 //
617                 public override string DocCommentHeader {
618                         get { return "T:"; }
619                 }
620
621         }
622
623         //
624         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
625         //
626         public abstract class DelegateCreation : Expression {
627                 protected MethodBase constructor_method;
628                 protected MethodBase delegate_method;
629                 protected MethodGroupExpr method_group;
630                 protected Expression delegate_instance_expression;
631
632                 protected DelegateCreation () {}
633
634                 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
635                 {
636                         string method_desc;
637                         MethodBase found_method = mg.Methods [0];
638
639                         if (mg.Methods.Length > 1)
640                                 method_desc = found_method.Name;
641                         else
642                                 method_desc = Invocation.FullMethodDesc (found_method);
643
644                         Expression invoke_method = Expression.MemberLookup (
645                                 ec.ContainerType, type, "Invoke", MemberTypes.Method,
646                                 Expression.AllBindingFlags, loc);
647                         MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
648
649                         ParameterData param = TypeManager.GetParameterData (method);
650                         string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
651
652 #if GMCS_SOURCE
653                         if (!mg.HasTypeArguments &&
654                             !TypeManager.InferTypeArguments (param, ref found_method)) {
655                                 Report.Error (411, loc, "The type arguments for " +
656                                               "method `{0}' cannot be infered from " +
657                                               "the usage. Try specifying the type " +
658                                               "arguments explicitly.", method_desc);
659                                 return;
660                         }
661 #endif
662                         if (method.ReturnType != ((MethodInfo) found_method).ReturnType) {
663                                 Report.Error (407, loc, "`{0}' has the wrong return type to match the delegate `{1}'", method_desc, delegate_desc);
664                         } else {
665                                 Report.Error (123, loc, "Method `{0}' does not match delegate `{1}'", method_desc, delegate_desc);
666                         }
667                 }
668                 
669                 public override void Emit (EmitContext ec)
670                 {
671                         if (delegate_instance_expression == null || delegate_method.IsStatic)
672                                 ec.ig.Emit (OpCodes.Ldnull);
673                         else
674                                 delegate_instance_expression.Emit (ec);
675                         
676                         if (delegate_method.IsVirtual && !method_group.IsBase) {
677                                 ec.ig.Emit (OpCodes.Dup);
678                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
679                         } else
680                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
681                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
682                 }
683
684                 protected bool ResolveConstructorMethod (EmitContext ec)
685                 {
686                         Expression ml = Expression.MemberLookupFinal(ec, 
687                                 null, type, ".ctor", MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
688
689                         if (!(ml is MethodGroupExpr)) {
690                                 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
691                                 return false;
692                         }
693
694                         constructor_method = ((MethodGroupExpr) ml).Methods [0];
695                         return true;
696                 }
697
698                 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type targetType)
699                 {
700                         foreach (MethodInfo mi in mg.Methods){
701                                 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, targetType, mg, mi, Location.Null);
702                                 if (mb != null)
703                                         return mb;
704                         }
705                         return null;
706                 }
707
708                 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
709                 {
710                         delegate_method = ImplicitStandardConversionExists (mg, type);
711
712                         if (delegate_method == null) {
713                                 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
714                                 return null;
715                         }
716                         
717                         //
718                         // Check safe/unsafe of the delegate
719                         //
720                         if (!ec.InUnsafe){
721                                 ParameterData param = TypeManager.GetParameterData (delegate_method);
722                                 int count = param.Count;
723                                 
724                                 for (int i = 0; i < count; i++){
725                                         if (param.ParameterType (i).IsPointer){
726                                                 Expression.UnsafeError (loc);
727                                                 return null;
728                                         }
729                                 }
730                         }
731                                                 
732                         //TODO: implement caching when performance will be low
733                         IMethodData md = TypeManager.GetMethod (delegate_method);
734                         if (md == null) {
735                                 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
736                                         Report.SymbolRelatedToPreviousError (delegate_method);
737                                         Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
738                                         return null;
739                                 }
740                         } else {
741                                 md.SetMemberIsUsed ();
742                                 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type) != null) {
743                                         Report.SymbolRelatedToPreviousError (delegate_method);
744                                         Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
745                                         return null;
746                                 }
747                         }
748                         
749                         if (mg.InstanceExpression != null)
750                                 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
751                         else if (ec.IsStatic) {
752                                 if (!delegate_method.IsStatic) {
753                                         Report.Error (120, loc, "`{0}': An object reference is required for the nonstatic field, method or property",
754                                                       TypeManager.CSharpSignature (delegate_method));
755                                         return null;
756                                 }
757                                 delegate_instance_expression = null;
758                         } else
759                                 delegate_instance_expression = ec.GetThis (loc);
760
761                         if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
762                                 delegate_instance_expression = new BoxedCast (
763                                         delegate_instance_expression, TypeManager.object_type);
764
765                         method_group = mg;
766                         eclass = ExprClass.Value;
767                         return this;
768                 }
769         }
770
771         //
772         // Created from the conversion code
773         //
774         public class ImplicitDelegateCreation : DelegateCreation {
775
776                 ImplicitDelegateCreation (Type t, Location l)
777                 {
778                         type = t;
779                         loc = l;
780                 }
781
782                 public override Expression DoResolve (EmitContext ec)
783                 {
784                         return this;
785                 }
786
787                 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
788                                                  Type target_type, Location loc)
789                 {
790                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
791                         if (!d.ResolveConstructorMethod (ec))
792                                 return null;
793
794                         return d.ResolveMethodGroupExpr (ec, mge);
795                 }
796         }
797         
798         //
799         // A delegate-creation-expression, invoked from the `New' class 
800         //
801         public class NewDelegate : DelegateCreation {
802                 public ArrayList Arguments;
803
804                 //
805                 // This constructor is invoked from the `New' expression
806                 //
807                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
808                 {
809                         this.type = type;
810                         this.Arguments = Arguments;
811                         this.loc  = loc; 
812                 }
813
814                 public override Expression DoResolve (EmitContext ec)
815                 {
816                         if (Arguments == null || Arguments.Count != 1) {
817                                 Report.Error (149, loc,
818                                               "Method name expected");
819                                 return null;
820                         }
821
822                         if (!ResolveConstructorMethod (ec))
823                                 return null;
824
825                         Argument a = (Argument) Arguments [0];
826                         
827                         if (!a.ResolveMethodGroup (ec))
828                                 return null;
829                         
830                         Expression e = a.Expr;
831
832                         if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1)
833                                 return ((AnonymousMethodExpression) e).Compatible (ec, type);
834
835                         MethodGroupExpr mg = e as MethodGroupExpr;
836                         if (mg != null)
837                                 return ResolveMethodGroupExpr (ec, mg);
838
839                         if (!TypeManager.IsDelegateType (e.Type)) {
840                                 Report.Error (149, loc, "Method name expected");
841                                 return null;
842                         }
843
844                         method_group = Expression.MemberLookup (
845                                 ec.ContainerType, type, "Invoke", MemberTypes.Method,
846                                 Expression.AllBindingFlags, loc) as MethodGroupExpr;
847
848                         if (method_group == null) {
849                                 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
850                                 return null;
851                         }
852
853                         // This is what MS' compiler reports. We could always choose
854                         // to be more verbose and actually give delegate-level specifics
855                         if (!Delegate.VerifyDelegate (ec, type, loc)) {
856                                 Report.Error (29, loc, "Cannot implicitly convert type '" + e.Type + "' " +
857                                               "to type '" + type + "'");
858                                 return null;
859                         }
860                                 
861                         delegate_instance_expression = e;
862                         delegate_method = method_group.Methods [0];
863                         
864                         eclass = ExprClass.Value;
865                         return this;
866                 }
867         }
868
869         public class DelegateInvocation : ExpressionStatement {
870
871                 public Expression InstanceExpr;
872                 public ArrayList  Arguments;
873
874                 MethodBase method;
875                 
876                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
877                 {
878                         this.InstanceExpr = instance_expr;
879                         this.Arguments = args;
880                         this.loc = loc;
881                 }
882
883                 public override Expression DoResolve (EmitContext ec)
884                 {
885                         if (InstanceExpr is EventExpr) {
886                                 
887                                 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
888                                 
889                                 Expression ml = MemberLookup (
890                                         ec.ContainerType, ec.ContainerType, ei.Name,
891                                         MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
892
893                                 if (ml == null) {
894                                         //
895                                         // If this is the case, then the Event does not belong 
896                                         // to this Type and so, according to the spec
897                                         // cannot be accessed directly
898                                         //
899                                         // Note that target will not appear as an EventExpr
900                                         // in the case it is being referenced within the same type container;
901                                         // it will appear as a FieldExpr in that case.
902                                         //
903                                         
904                                         Assign.error70 (ei, loc);
905                                         return null;
906                                 }
907                         }
908                         
909                         
910                         Type del_type = InstanceExpr.Type;
911                         if (del_type == null)
912                                 return null;
913                         
914                         if (Arguments != null){
915                                 foreach (Argument a in Arguments){
916                                         if (!a.Resolve (ec, loc))
917                                                 return null;
918                                 }
919                         }
920                         
921                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
922                                 return null;
923
924                         Expression lookup = Expression.MemberLookup (ec.ContainerType, del_type, "Invoke", loc);
925                         if (!(lookup is MethodGroupExpr)) {
926                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
927                                 return null;
928                         }
929                         
930                         method = ((MethodGroupExpr) lookup).Methods [0];
931                         type = ((MethodInfo) method).ReturnType;
932                         eclass = ExprClass.Value;
933                         
934                         return this;
935                 }
936
937                 public override void Emit (EmitContext ec)
938                 {
939                         //
940                         // Invocation on delegates call the virtual Invoke member
941                         // so we are always `instance' calls
942                         //
943                         Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
944                 }
945
946                 public override void EmitStatement (EmitContext ec)
947                 {
948                         Emit (ec);
949                         // 
950                         // Pop the return value if there is one
951                         //
952                         if (method is MethodInfo){
953                                 Type ret = ((MethodInfo)method).ReturnType;
954                                 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
955                                         ec.ig.Emit (OpCodes.Pop);
956                         }
957                 }
958
959         }
960 }