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