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