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