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