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