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