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