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