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