* First cut changes for suporting Binary Operators. All changes
[mono.git] / mcs / bmcs / delegate.cs
1 //
2 // delegate.cs: Delegate Handler
3 //
4 // Authors:
5 //     Ravi Pratap (ravi@ximian.com)
6 //     Miguel de Icaza (miguel@ximian.com)
7 //
8 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 //
12 //
13
14 using System;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Text;
19
20 namespace Mono.CSharp {
21
22         /// <summary>
23         ///   Holds Delegates
24         /// </summary>
25         public class Delegate : DeclSpace {
26                 public Expression ReturnType;
27                 public Parameters      Parameters;
28
29                 public ConstructorBuilder ConstructorBuilder;
30                 public MethodBuilder      InvokeBuilder;
31                 public MethodBuilder      BeginInvokeBuilder;
32                 public MethodBuilder      EndInvokeBuilder;
33                 
34                 Type [] param_types;
35                 Type ret_type;
36
37                 static string[] attribute_targets = new string [] { "type", "return" };
38                 
39                 Expression instance_expr;
40                 MethodBase delegate_method;
41                 ReturnParameter return_attributes;
42         
43                 const int AllowedModifiers =
44                         Modifiers.NEW |
45                         Modifiers.PUBLIC |
46                         Modifiers.PROTECTED |
47                         Modifiers.INTERNAL |
48                         Modifiers.UNSAFE |
49                         Modifiers.PRIVATE;
50
51                 public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
52                                  int mod_flags, MemberName name, Parameters param_list,
53                                  Attributes attrs, Location l)
54                         : base (ns, parent, name, attrs, l)
55
56                 {
57                         this.ReturnType = type;
58                         ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,
59                                                            IsTopLevel ? Modifiers.INTERNAL :
60                                                            Modifiers.PRIVATE, l);
61                         Parameters      = param_list;
62                 }
63
64                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
65                 {
66                         if (a.Target == AttributeTargets.ReturnValue) {
67                                 if (return_attributes == null)
68                                         return_attributes = new ReturnParameter (InvokeBuilder, Location);
69
70                                 return_attributes.ApplyAttributeBuilder (a, cb);
71                                 return;
72                         }
73
74                         base.ApplyAttributeBuilder (a, cb);
75                 }
76
77                 public override TypeBuilder DefineType ()
78                 {
79                         if (TypeBuilder != null)
80                                 return TypeBuilder;
81
82                         ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
83
84                         if (IsGeneric) {
85                                 foreach (TypeParameter type_param in TypeParameters)
86                                         if (!type_param.Resolve (this))
87                                                 return null;
88                         }
89                         
90                         TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel) |
91                                 TypeAttributes.Class | TypeAttributes.Sealed;
92
93                         if (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                         //
256                         // We don't have to check any others because they are all
257                         // guaranteed to be accessible - they are standard types.
258                         //
259                         
260                         CallingConventions cc = Parameters.GetCallingConvention ();
261
262                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
263
264                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
265                                                                   mattr,                     
266                                                                   cc,
267                                                                   ret_type,                  
268                                                                   param_types);
269
270                         //
271                         // Define parameters, and count out/ref parameters
272                         //
273                         int out_params = 0;
274                         i = 0;
275                         if (Parameters.FixedParameters != null){
276                                 int top = Parameters.FixedParameters.Length;
277                                 Parameter p;
278                                 
279                                 for (; i < top; i++) {
280                                         p = Parameters.FixedParameters [i];
281                                         p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
282
283                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
284                                                 out_params++;
285                                 }
286                         }
287                         if (Parameters.ArrayParameter != null){
288                                 Parameter p = Parameters.ArrayParameter;
289                                 p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
290                         }
291                         
292                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
293
294                         TypeManager.RegisterMethod (InvokeBuilder,
295                                                     new InternalParameters (param_types, Parameters),
296                                                     param_types);
297
298                         //
299                         // BeginInvoke
300                         //
301                         int params_num = param_types.Length;
302                         Type [] async_param_types = new Type [params_num + 2];
303
304                         param_types.CopyTo (async_param_types, 0);
305
306                         async_param_types [params_num] = TypeManager.asynccallback_type;
307                         async_param_types [params_num + 1] = TypeManager.object_type;
308
309                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
310                                 MethodAttributes.Virtual | MethodAttributes.NewSlot;
311                         
312                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
313                                                                        mattr,
314                                                                        cc,
315                                                                        TypeManager.iasyncresult_type,
316                                                                        async_param_types);
317
318                         i = 0;
319                         if (Parameters.FixedParameters != null){
320                                 int top = Parameters.FixedParameters.Length;
321                                 Parameter p;
322                                 
323                                 for (i = 0 ; i < top; i++) {
324                                         p = Parameters.FixedParameters [i];
325
326                                         p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
327                                 }
328                         }
329                         if (Parameters.ArrayParameter != null){
330                                 Parameter p = Parameters.ArrayParameter;
331                                 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
332
333                                 i++;
334                         }
335
336                         BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
337                         BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
338                         
339                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
340
341                         Parameter [] async_params = new Parameter [params_num + 2];
342                         int n = 0;
343                         if (Parameters.FixedParameters != null){
344                                 Parameters.FixedParameters.CopyTo (async_params, 0);
345                                 n = Parameters.FixedParameters.Length;
346                         }
347                         if (Parameters.ArrayParameter != null)
348                                 async_params [n] = Parameters.ArrayParameter;
349                         
350                         async_params [params_num] = new Parameter (
351                                 TypeManager.system_asynccallback_expr, "callback",
352                                                                    Parameter.Modifier.NONE, null);
353                         async_params [params_num + 1] = new Parameter (
354                                 TypeManager.system_object_expr, "object",
355                                                                    Parameter.Modifier.NONE, null);
356
357                         Parameters async_parameters = new Parameters (async_params, null, Location);
358                         async_parameters.ComputeAndDefineParameterTypes (ec);
359                         
360                         TypeManager.RegisterMethod (BeginInvokeBuilder,
361                                                     new InternalParameters (async_param_types, async_parameters),
362                                                     async_param_types);
363
364                         //
365                         // EndInvoke is a bit more interesting, all the parameters labeled as
366                         // out or ref have to be duplicated here.
367                         //
368                         
369                         Type [] end_param_types = new Type [out_params + 1];
370                         Parameter [] end_params = new Parameter [out_params + 1];
371                         int param = 0; 
372                         if (out_params > 0){
373                                 int top = Parameters.FixedParameters.Length;
374                                 for (i = 0; i < top; i++){
375                                         Parameter p = Parameters.FixedParameters [i];
376                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
377                                                 continue;
378
379                                         end_param_types [param] = param_types [i];
380                                         end_params [param] = p;
381                                         param++;
382                                 }
383                         }
384                         end_param_types [out_params] = TypeManager.iasyncresult_type;
385                         end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null);
386
387                         //
388                         // Create method, define parameters, register parameters with type system
389                         //
390                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
391                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
392
393                         //
394                         // EndInvoke: Label the parameters
395                         //
396                         EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
397                         for (i = 0; i < end_params.Length-1; i++){
398                                 EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
399                         }
400
401                         Parameters end_parameters = new Parameters (end_params, null, Location);
402                         end_parameters.ComputeAndDefineParameterTypes (ec);
403
404                         TypeManager.RegisterMethod (
405                                 EndInvokeBuilder,
406                                 new InternalParameters (end_param_types, 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 = Invocation.GetParameterData (invoke_mb);
475
476                         if (!mg.HasTypeArguments &&
477                             !TypeManager.InferTypeArguments (ec, invoke_pd, ref mb))
478                                 return null;
479
480                         ParameterData pd = Invocation.GetParameterData (mb);
481                         int pd_count = pd.Count;
482
483                         if (invoke_pd.Count != pd_count)
484                                 return null;
485
486                         for (int i = pd_count; i > 0; ) {
487                                 i--;
488
489                                 Type invoke_pd_type = invoke_pd.ParameterType (i);
490                                 Type pd_type = pd.ParameterType (i);
491                                 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
492                                 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
493
494                                 if (invoke_pd_type == pd_type &&
495                                     invoke_pd_type_mod == pd_type_mod)
496                                         continue;
497                                 
498                                 if (invoke_pd_type.IsSubclassOf (pd_type) && 
499                                                 invoke_pd_type_mod == pd_type_mod)
500                                         if (RootContext.Version == LanguageVersion.ISO_1) {
501                                                 Report.FeatureIsNotStandardized (loc, "contravariance");
502                                                 return null;
503                                         } else
504                                                 continue;
505                                         
506                                 return null;
507                         }
508
509                         Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
510                         Type mb_retval = ((MethodInfo) mb).ReturnType;
511                         if (invoke_mb_retval == mb_retval)
512                                 return mb;
513                         
514                         if (mb_retval.IsSubclassOf (invoke_mb_retval))
515                                 if (RootContext.Version == LanguageVersion.ISO_1) {
516                                         Report.FeatureIsNotStandardized (loc, "covariance");
517                                         return null;
518                                 }
519                                 else
520                                         return mb;
521                         
522                         return null;
523                 }
524
525                 // <summary>
526                 //  Verifies whether the invocation arguments are compatible with the
527                 //  delegate's target method
528                 // </summary>
529                 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
530                                                         ArrayList args, Location loc)
531                 {
532                         int arg_count;
533
534                         if (args == null)
535                                 arg_count = 0;
536                         else
537                                 arg_count = args.Count;
538
539                         Expression ml = Expression.MemberLookup (
540                                 ec, delegate_type, "Invoke", loc);
541
542                         if (!(ml is MethodGroupExpr)) {
543                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
544                                 return false;
545                         }
546                         
547                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
548                         ParameterData pd = Invocation.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                         if (!params_method && pd_count != arg_count) {
556                                 Report.Error (1593, loc,
557                                               "Delegate '{0}' does not take {1} arguments",
558                                               delegate_type.ToString (), arg_count);
559                                 return false;
560                         }
561
562                         //
563                         // Consider the case:
564                         //   delegate void FOO(param object[] args);
565                         //   FOO f = new FOO(...);
566                         //   f(new object[] {1, 2, 3});
567                         //
568                         // This should be treated like f(1,2,3).  This is done by ignoring the 
569                         // 'param' modifier for that invocation.  If that fails, then the
570                         // 'param' modifier is considered.
571                         //
572                         // One issue is that 'VerifyArgumentsCompat' modifies the elements of
573                         // the 'args' array.  However, the modifications appear idempotent.
574                         // Normal 'Invocation's also have the same behaviour, implicitly.
575                         //
576
577                         bool ans = false;
578                         if (arg_count == pd_count)
579                                 ans = Invocation.VerifyArgumentsCompat (
580                                         ec, args, arg_count, mb, false,
581                                         delegate_type, false, loc);
582                         if (!ans && params_method)
583                                 ans = Invocation.VerifyArgumentsCompat (
584                                         ec, args, arg_count, mb, true,
585                                         delegate_type, false, loc);
586                         return ans;
587                 }
588                 
589                 /// <summary>
590                 ///  Verifies whether the delegate in question is compatible with this one in
591                 ///  order to determine if instantiation from the same is possible.
592                 /// </summary>
593                 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
594                 {
595                         Expression ml = Expression.MemberLookup (
596                                 ec, delegate_type, "Invoke", loc);
597                         
598                         if (!(ml is MethodGroupExpr)) {
599                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
600                                 return false;
601                         }
602                         
603                         MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
604                         ParameterData pd = Invocation.GetParameterData (mb);
605
606                         Expression probe_ml = Expression.MemberLookup (
607                                 ec, delegate_type, "Invoke", loc);
608                         
609                         if (!(probe_ml is MethodGroupExpr)) {
610                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
611                                 return false;
612                         }
613                         
614                         MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
615                         ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
616                         
617                         if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
618                                 return false;
619
620                         if (pd.Count != probe_pd.Count)
621                                 return false;
622
623                         for (int i = pd.Count; i > 0; ) {
624                                 i--;
625
626                                 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
627                                     pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
628                                         return false;
629                         }
630                         
631                         return true;
632                 }
633                 
634                 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
635                 {
636                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
637                         
638                         sb.Append (" " + del_type.ToString ());
639                         sb.Append (" (");
640
641                         int length = pd.Count;
642                         
643                         for (int i = length; i > 0; ) {
644                                 i--;
645
646                                 sb.Append (pd.ParameterDesc (length - i - 1));
647                                 if (i != 0)
648                                         sb.Append (", ");
649                         }
650                         
651                         sb.Append (")");
652                         return sb.ToString ();
653                         
654                 }
655                 
656                 // Hack around System.Reflection as found everywhere else
657                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
658                                                         MemberFilter filter, object criteria)
659                 {
660                         ArrayList members = new ArrayList ();
661
662                         if ((mt & MemberTypes.Method) != 0) {
663                                 if (ConstructorBuilder != null)
664                                 if (filter (ConstructorBuilder, criteria))
665                                         members.Add (ConstructorBuilder);
666
667                                 if (InvokeBuilder != null)
668                                 if (filter (InvokeBuilder, criteria))
669                                         members.Add (InvokeBuilder);
670
671                                 if (BeginInvokeBuilder != null)
672                                 if (filter (BeginInvokeBuilder, criteria))
673                                         members.Add (BeginInvokeBuilder);
674
675                                 if (EndInvokeBuilder != null)
676                                 if (filter (EndInvokeBuilder, criteria))
677                                         members.Add (EndInvokeBuilder);
678                         }
679
680                         return new MemberList (members);
681                 }
682
683                 public override MemberCache MemberCache {
684                         get {
685                                 return null;
686                         }
687                 }
688
689                 public Expression InstanceExpression {
690                         get {
691                                 return instance_expr;
692                         }
693                         set {
694                                 instance_expr = value;
695                         }
696                 }
697
698                 public MethodBase TargetMethod {
699                         get {
700                                 return delegate_method;
701                         }
702                         set {
703                                 delegate_method = value;
704                         }
705                 }
706
707                 public Type TargetReturnType {
708                         get {
709                                 return ret_type;
710                         }
711                 }
712
713                 public Type [] ParameterTypes {
714                         get {
715                                 return param_types;
716                         }
717                 }
718
719                 public override AttributeTargets AttributeTargets {
720                         get {
721                                 return AttributeTargets.Delegate;
722                         }
723                 }
724
725                 //
726                 //   Represents header string for documentation comment.
727                 //
728                 public override string DocCommentHeader {
729                         get { return "T:"; }
730                 }
731
732                 protected override void VerifyObsoleteAttribute()
733                 {
734                         CheckUsageOfObsoleteAttribute (ret_type);
735
736                         foreach (Type type in param_types) {
737                                 CheckUsageOfObsoleteAttribute (type);
738                         }
739                 }
740         }
741
742         //
743         // Base class for `NewDelegate' and `ImplicitDelegateCreation'
744         //
745         public abstract class DelegateCreation : Expression {
746                 protected MethodBase constructor_method;
747                 protected MethodBase delegate_method;
748                 protected MethodGroupExpr method_group;
749                 protected Expression delegate_instance_expression;
750
751                 public DelegateCreation () {}
752
753                 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
754                 {
755                         string method_desc;
756
757                         MethodBase candidate = mg.Methods [0];
758                         if (mg.Methods.Length > 1)
759                                 method_desc = candidate.Name;
760                         else
761                                 method_desc = Invocation.FullMethodDesc (candidate);
762
763                         Expression invoke_method = Expression.MemberLookup (
764                                 ec, type, "Invoke", MemberTypes.Method,
765                                 Expression.AllBindingFlags, loc);
766                         MethodBase method = ((MethodGroupExpr) invoke_method).Methods [0];
767                         ParameterData param = Invocation.GetParameterData (method);
768                         string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
769
770                         if (!mg.HasTypeArguments &&
771                             !TypeManager.InferTypeArguments (ec, param, ref candidate))
772                                 Report.Error (411, loc, "The type arguments for " +
773                                               "method `{0}' cannot be infered from " +
774                                               "the usage. Try specifying the type " +
775                                               "arguments explicitly.", method_desc);
776                         else
777                                 Report.Error (123, loc, "Method '{0}' does not " +
778                                               "match delegate '{1}'", method_desc,
779                                               delegate_desc);
780                 }
781                 
782                 public override void Emit (EmitContext ec)
783                 {
784                         if (delegate_instance_expression == null || delegate_method.IsStatic)
785                                 ec.ig.Emit (OpCodes.Ldnull);
786                         else
787                                 delegate_instance_expression.Emit (ec);
788                         
789                         if (delegate_method.IsVirtual && !method_group.IsBase) {
790                                 ec.ig.Emit (OpCodes.Dup);
791                                 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
792                         } else
793                                 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
794                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
795                 }
796
797                 protected bool ResolveConstructorMethod (EmitContext ec)
798                 {
799                         Expression ml = Expression.MemberLookup (
800                                 ec, type, ".ctor", loc);
801
802                         if (!(ml is MethodGroupExpr)) {
803                                 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
804                                 return false;
805                         }
806
807                         constructor_method = ((MethodGroupExpr) ml).Methods [0];
808                         return true;
809                 }
810
811                 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
812                 {
813                                 foreach (MethodInfo mi in mg.Methods){
814                                         delegate_method = Delegate.VerifyMethod (
815                                                 ec, type, mi, loc);
816
817                                         if (delegate_method != null)
818                                                 break;
819                                 }
820                                         
821                                 if (delegate_method == null) {
822                                         Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
823                                         return null;
824                                 }
825
826                                 //
827                                 // Check safe/unsafe of the delegate
828                                 //
829                                 if (!ec.InUnsafe){
830                                         ParameterData param = Invocation.GetParameterData (delegate_method);
831                                         int count = param.Count;
832                                         
833                                         for (int i = 0; i < count; i++){
834                                                 if (param.ParameterType (i).IsPointer){
835                                                         Expression.UnsafeError (loc);
836                                                         return null;
837                                                 }
838                                         }
839                                 }
840                                                 
841                         //TODO: implement caching when performance will be low
842                         IMethodData md = TypeManager.GetMethod (delegate_method);
843                         if (md == null) {
844                                 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
845                                         Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
846                                 }
847                         } else {
848                                 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
849                                         Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
850                                 }
851                         }
852                         
853                         if (mg.InstanceExpression != null)
854                                 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
855                         else if (ec.IsStatic) {
856                                 if (!delegate_method.IsStatic) {
857                                         Report.Error (120, loc,
858                                                       "An object reference is required for the non-static method " +
859                                                       delegate_method.Name);
860                                         return null;
861                                 }
862                                 delegate_instance_expression = null;
863                         } else
864                                 delegate_instance_expression = ec.GetThis (loc);
865
866                         if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
867                                 delegate_instance_expression = new BoxedCast (delegate_instance_expression);
868
869                         method_group = mg;
870                         eclass = ExprClass.Value;
871                         return this;
872                 }
873         }
874
875         //
876         // Created from the conversion code
877         //
878         public class ImplicitDelegateCreation : DelegateCreation {
879
880                 ImplicitDelegateCreation (Type t, Location l)
881                 {
882                         type = t;
883                         loc = l;
884                 }
885
886                 public override Expression DoResolve (EmitContext ec)
887                 {
888                         return this;
889                 }
890                 
891                 static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
892                 {
893                         ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
894                         if (d.ResolveConstructorMethod (ec))
895                                 return d.ResolveMethodGroupExpr (ec, mge);
896                         else
897                                 return null;
898                 }
899         }
900         
901         //
902         // A delegate-creation-expression, invoked from the `New' class 
903         //
904         public class NewDelegate : DelegateCreation {
905                 public ArrayList Arguments;
906
907                 //
908                 // This constructor is invoked from the `New' expression
909                 //
910                 public NewDelegate (Type type, ArrayList Arguments, Location loc)
911                 {
912                         this.type = type;
913                         this.Arguments = Arguments;
914                         this.loc  = loc; 
915                 }
916
917                 public override Expression DoResolve (EmitContext ec)
918                 {
919                         if (Arguments == null || Arguments.Count != 1) {
920                                 Report.Error (149, loc,
921                                               "Method name expected");
922                                 return null;
923                         }
924
925                         if (!ResolveConstructorMethod (ec))
926                                 return null;
927
928                         Argument a = (Argument) Arguments [0];
929                         
930                         if (!a.ResolveMethodGroup (ec, loc))
931                                 return null;
932                         
933                         Expression e = a.Expr;
934
935                         if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
936                                 return ((AnonymousMethod) e).Compatible (ec, type, false);
937
938                         MethodGroupExpr mg = e as MethodGroupExpr;
939                         if (mg != null)
940                                 return ResolveMethodGroupExpr (ec, mg);
941
942                         Type e_type = e.Type;
943
944                         if (!TypeManager.IsDelegateType (e_type)) {
945                                 Report.Error (149, loc, "Method name expected");
946                                 return null;
947                         }
948
949                         method_group = Expression.MemberLookup (
950                                 ec, type, "Invoke", MemberTypes.Method,
951                                 Expression.AllBindingFlags, loc) as MethodGroupExpr;
952
953                         if (method_group == null) {
954                                 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
955                                 return null;
956                         }
957
958                         // This is what MS' compiler reports. We could always choose
959                         // to be more verbose and actually give delegate-level specifics
960                         if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
961                                 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
962                                               "to type '" + type + "'");
963                                 return null;
964                         }
965                                 
966                         delegate_instance_expression = e;
967                         delegate_method = method_group.Methods [0];
968                         
969                         eclass = ExprClass.Value;
970                         return this;
971                 }
972         }
973
974         public class DelegateInvocation : ExpressionStatement {
975
976                 public Expression InstanceExpr;
977                 public ArrayList  Arguments;
978
979                 MethodBase method;
980                 
981                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
982                 {
983                         this.InstanceExpr = instance_expr;
984                         this.Arguments = args;
985                         this.loc = loc;
986                 }
987
988                 public override Expression DoResolve (EmitContext ec)
989                 {
990                         if (InstanceExpr is EventExpr) {
991                                 
992                                 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
993                                 
994                                 Expression ml = MemberLookup (
995                                         ec, ec.ContainerType, ei.Name,
996                                         MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
997
998                                 if (ml == null) {
999                                         //
1000                                         // If this is the case, then the Event does not belong 
1001                                         // to this Type and so, according to the spec
1002                                         // cannot be accessed directly
1003                                         //
1004                                         // Note that target will not appear as an EventExpr
1005                                         // in the case it is being referenced within the same type container;
1006                                         // it will appear as a FieldExpr in that case.
1007                                         //
1008                                         
1009                                         Assign.error70 (ei, loc);
1010                                         return null;
1011                                 }
1012                         }
1013                         
1014                         
1015                         Type del_type = InstanceExpr.Type;
1016                         if (del_type == null)
1017                                 return null;
1018                         
1019                         if (Arguments != null){
1020                                 foreach (Argument a in Arguments){
1021                                         if (!a.Resolve (ec, loc))
1022                                                 return null;
1023                                 }
1024                         }
1025                         
1026                         if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1027                                 return null;
1028
1029                         Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
1030                         if (!(lookup is MethodGroupExpr)) {
1031                                 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
1032                                 return null;
1033                         }
1034                         
1035                         method = ((MethodGroupExpr) lookup).Methods [0];
1036                         type = ((MethodInfo) method).ReturnType;
1037                         eclass = ExprClass.Value;
1038                         
1039                         return this;
1040                 }
1041
1042                 public override void Emit (EmitContext ec)
1043                 {
1044                         //
1045                         // Invocation on delegates call the virtual Invoke member
1046                         // so we are always `instance' calls
1047                         //
1048                         Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
1049                 }
1050
1051                 public override void EmitStatement (EmitContext ec)
1052                 {
1053                         Emit (ec);
1054                         // 
1055                         // Pop the return value if there is one
1056                         //
1057                         if (method is MethodInfo){
1058                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
1059                                         ec.ig.Emit (OpCodes.Pop);
1060                         }
1061                 }
1062
1063         }
1064 }