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