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