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