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