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