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