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