2001-11-15 Ravi Pratap <ravi@ximian.com>
[mono.git] / mcs / mcs / delegate.cs
1 //\r
2 // delegate.cs: Delegate Handler\r
3 //\r
4 // Author: Ravi Pratap (ravi@ximian.com)\r
5 //\r
6 // Licensed under the terms of the GNU GPL\r
7 //\r
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)\r
9 //\r
10 //\r
11 \r
12 using System;\r
13 using System.Collections;\r
14 using System.Reflection;\r
15 using System.Reflection.Emit;\r
16 using System.Text;\r
17 \r
18 namespace CIR {\r
19         \r
20         public class Delegate {\r
21 \r
22                 public readonly string Name;\r
23                 public readonly string ReturnType;\r
24                 public int             mod_flags;\r
25                 public Parameters      Parameters;\r
26                 public Attributes      OptAttributes;\r
27                 public TypeBuilder     TypeBuilder;\r
28 \r
29                 public ConstructorBuilder ConstructorBuilder;\r
30                 public MethodBuilder      InvokeBuilder;\r
31                 public MethodBuilder      BeginInvokeBuilder;\r
32                 public MethodBuilder      EndInvokeBuilder;\r
33                 \r
34                 public readonly RootContext RootContext;\r
35 \r
36                 Type [] param_types;\r
37                 Type ret_type;\r
38                 \r
39                 Expression instance_expr;\r
40                 MethodBase delegate_method;\r
41         \r
42                 Location loc;\r
43 \r
44                 const int AllowedModifiers =\r
45                         Modifiers.NEW |\r
46                         Modifiers.PUBLIC |\r
47                         Modifiers.PROTECTED |\r
48                         Modifiers.INTERNAL |\r
49                         Modifiers.PRIVATE;\r
50 \r
51                 public Delegate (RootContext rc, string type, int mod_flags, string name, Parameters param_list,\r
52                                  Attributes attrs, Location loc)\r
53                 {\r
54                         this.RootContext = rc;\r
55                         this.Name       = name;\r
56                         this.ReturnType = type;\r
57                         this.mod_flags  = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);\r
58                         Parameters      = param_list;\r
59                         OptAttributes   = attrs;\r
60                         this.loc        = loc;\r
61                 }\r
62 \r
63                 public void DefineDelegate (object parent_builder)\r
64                 {\r
65                         TypeAttributes attr;\r
66                         \r
67                         if (parent_builder is ModuleBuilder) {\r
68                                 ModuleBuilder builder = (ModuleBuilder) parent_builder;\r
69                                 \r
70                                 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;\r
71 \r
72                                 TypeBuilder = builder.DefineType (Name, attr, TypeManager.delegate_type);\r
73                                                                   \r
74                         } else {\r
75                                 TypeBuilder builder = (TypeBuilder) parent_builder;\r
76                                 \r
77                                 attr = TypeAttributes.NestedPublic | TypeAttributes.Class | TypeAttributes.Sealed;\r
78 \r
79                                 TypeBuilder = builder.DefineNestedType (Name, attr, TypeManager.delegate_type);\r
80 \r
81                         }\r
82 \r
83                         RootContext.TypeManager.AddDelegateType (Name, TypeBuilder, this);\r
84                 }\r
85 \r
86                 public void Populate (TypeContainer parent)\r
87                 {\r
88 \r
89                         MethodAttributes mattr;\r
90                         int i;\r
91                         \r
92                         Type [] const_arg_types = new Type [2];\r
93 \r
94                         const_arg_types [0] = TypeManager.object_type;\r
95                         const_arg_types [1] = TypeManager.intptr_type;\r
96 \r
97                         mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |\r
98                                 MethodAttributes.HideBySig | MethodAttributes.Public;\r
99 \r
100                         ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,\r
101                                                                             CallingConventions.Standard,\r
102                                                                             const_arg_types);\r
103                         \r
104                         ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
105                         \r
106                         // Here the various methods like Invoke, BeginInvoke etc are defined\r
107 \r
108                         param_types = Parameters.GetParameterInfo (parent);\r
109                         ret_type = parent.LookupType (ReturnType, false);\r
110                         CallingConventions cc = Parameters.GetCallingConvention ();\r
111 \r
112                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;\r
113 \r
114                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", \r
115                                                                   mattr,                     \r
116                                                                   cc,\r
117                                                                   ret_type,                  \r
118                                                                   param_types);\r
119 \r
120                         for (i = 0 ; i < param_types.Length; i++) {\r
121                                 Parameter p = Parameters.FixedParameters [i];\r
122                                 string name = p.Name;\r
123                                 ParameterBuilder pb = InvokeBuilder.DefineParameter (i+1, p.Attributes, name); \r
124                         }\r
125                         \r
126                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
127 \r
128                         TypeContainer.RegisterParameterForBuilder (InvokeBuilder,\r
129                                                                    new InternalParameters (parent, Parameters)); \r
130 \r
131                         int params_num = param_types.Length;\r
132                         Type [] async_param_types = new Type [params_num + 2];\r
133 \r
134                         param_types.CopyTo (async_param_types, 0);\r
135 \r
136                         async_param_types [params_num] = TypeManager.asynccallback_type;\r
137                         async_param_types [params_num + 1] = TypeManager.object_type;\r
138 \r
139                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |\r
140                                 MethodAttributes.NewSlot;\r
141                         \r
142                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",\r
143                                                                        mattr,\r
144                                                                        cc,\r
145                                                                        TypeManager.iasyncresult_type,\r
146                                                                        async_param_types);\r
147 \r
148                         for (i = 0 ; i < param_types.Length; i++) {\r
149                                 Parameter p = Parameters.FixedParameters [i];\r
150                                 string name = p.Name;\r
151                                 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name); \r
152                         }\r
153                         \r
154                         BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");\r
155                         BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");\r
156                         \r
157                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
158 \r
159                         Parameter [] async_params = new Parameter [params_num + 2];\r
160                         Parameters.FixedParameters.CopyTo (async_params, 0);\r
161 \r
162                         async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",\r
163                                                                    Parameter.Modifier.NONE, null);\r
164                         async_params [params_num + 1] = new Parameter ("System.IAsyncResult", "object",\r
165                                                                    Parameter.Modifier.NONE, null);\r
166                         \r
167                         TypeContainer.RegisterParameterForBuilder (BeginInvokeBuilder,\r
168                                         new InternalParameters (parent, new Parameters (async_params, null))); \r
169 \r
170                         Type [] end_param_types = new Type [1];\r
171                         end_param_types [0] = TypeManager.iasyncresult_type;\r
172                         \r
173                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",\r
174                                                                      mattr,\r
175                                                                      cc,\r
176                                                                      ret_type,\r
177                                                                      end_param_types);\r
178                         EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");\r
179                         \r
180                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
181 \r
182                         Parameter [] end_params = new Parameter [1];\r
183                         end_params [0] = new Parameter ("System.IAsyncResult", "result",\r
184                                                         Parameter.Modifier.NONE, null);\r
185 \r
186                         TypeContainer.RegisterParameterForBuilder (EndInvokeBuilder,\r
187                                         new InternalParameters (parent, new Parameters (end_params, null))); \r
188                         \r
189                 }\r
190 \r
191                 // <summary>\r
192                 //  Verifies whether the method in question is compatible with the delegate\r
193                 //  Returns the method itself if okay and null if not.\r
194                 // </summary>\r
195                 public MethodBase VerifyMethod (MethodBase mb, Location loc)\r
196                 {\r
197                         ParameterData pd = Invocation.GetParameterData (mb);\r
198 \r
199                         bool mismatch = false;\r
200                         for (int i = param_types.Length; i > 0; ) {\r
201                                 i--;\r
202 \r
203                                 if (param_types [i] == pd.ParameterType (i))\r
204                                         continue;\r
205                                 else {\r
206                                         mismatch = true;\r
207                                         break;\r
208                                 }\r
209                         }\r
210 \r
211                         if (mismatch) {\r
212                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
213                                               "delegate '" + FullDelegateDesc () + "'");\r
214                                 return null;\r
215                         }\r
216 \r
217                         if (ret_type == ((MethodInfo) mb).ReturnType)\r
218                                 return mb;\r
219                         else\r
220                                 mismatch = true;\r
221 \r
222                         if (mismatch) {\r
223                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
224                                               "delegate '" + FullDelegateDesc () + "'");\r
225                                 return null;\r
226                         }\r
227 \r
228                         return null;\r
229                 }\r
230 \r
231                 // <summary>\r
232                 //  Verifies whether the invocation arguments are compatible with the\r
233                 //  delegate's target method\r
234                 // </summary>\r
235                 public bool VerifyApplicability (EmitContext ec, ArrayList args, Location loc)\r
236                 {\r
237                         int arg_count;\r
238 \r
239                         if (args == null)\r
240                                 arg_count = 0;\r
241                         else\r
242                                 arg_count = args.Count;\r
243                         \r
244                         if (param_types.Length != arg_count) {\r
245                                 Report.Error (1593, loc,\r
246                                               "Delegate '" + Name + "' does not take '" + arg_count + "' arguments");\r
247                                 return false;\r
248                         }\r
249 \r
250                         for (int i = arg_count; i > 0;) {\r
251                                 i--;\r
252                                 Expression conv;\r
253                                 Argument a = (Argument) args [i];\r
254                                 Expression a_expr = a.Expr;\r
255                                 \r
256                                 if (param_types [i] != a_expr.Type) {\r
257                                         \r
258                                         conv = Expression.ConvertImplicitStandard (ec, a_expr, param_types [i], loc);\r
259 \r
260                                         if (conv == null) {\r
261                                                 Report.Error (1594, loc,\r
262                                                               "Delegate '" + Name + "' has some invalid arguments.");\r
263 \r
264                                                 Report.Error (1503, loc,\r
265                                                        "Argument " + (i+1) +\r
266                                                        ": Cannot convert from '" +\r
267                                                        TypeManager.CSharpName (a_expr.Type)\r
268                                                        + "' to '" + TypeManager.CSharpName (param_types [i]) + "'");\r
269                                                 return false;\r
270                                         }\r
271 \r
272                                         if (a_expr != conv)\r
273                                                 a.Expr = conv;\r
274                                 }\r
275                         }\r
276 \r
277                         return true;\r
278                 }\r
279 \r
280                 // <summary>\r
281                 //  Verifies whether the delegate in question is compatible with this one in\r
282                 //  order to determine if instantiation from the same is possible.\r
283                 // </summary>\r
284                 public bool VerifyDelegate (Delegate del)\r
285                 {\r
286                         if (ret_type != del.TargetReturnType)\r
287                                 return false;\r
288 \r
289                         Type [] other_param_types = del.ParameterTypes;\r
290                         \r
291                         if (param_types.Length != other_param_types.Length)\r
292                                 return false;\r
293 \r
294                         for (int i = param_types.Length; i > 0; ) {\r
295                                 i--;\r
296 \r
297                                 if (param_types [i] != other_param_types [i])\r
298                                         return false;\r
299                         }\r
300 \r
301                         // FIXME : Hey, what about parameter modifiers ?\r
302 \r
303                         return true;\r
304 \r
305                 }\r
306                 \r
307                 public string FullDelegateDesc ()\r
308                 {\r
309                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (System.Type.GetType (ReturnType)));\r
310                         \r
311                         sb.Append (" " + Name);\r
312                         sb.Append (" (");\r
313 \r
314                         int length = param_types.Length;\r
315                         \r
316                         for (int i = length; i > 0; ) {\r
317                                 i--;\r
318                                 \r
319                                 sb.Append (TypeManager.CSharpName (param_types [length - i - 1]));\r
320                                 if (i != 0)\r
321                                         sb.Append (", ");\r
322                         }\r
323                         \r
324                         sb.Append (")");\r
325                         return sb.ToString ();\r
326                         \r
327                 }\r
328                 \r
329                 // Hack around System.Reflection as found everywhere else\r
330                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)\r
331                 {\r
332                         ArrayList members = new ArrayList ();\r
333 \r
334                         if ((mt & MemberTypes.Method) != 0) {\r
335                                 if (filter (ConstructorBuilder, criteria))\r
336                                         members.Add (ConstructorBuilder);\r
337 \r
338                                 if (filter (InvokeBuilder, criteria))\r
339                                         members.Add (InvokeBuilder);\r
340 \r
341                                 if (filter (BeginInvokeBuilder, criteria))\r
342                                         members.Add (BeginInvokeBuilder);\r
343 \r
344                                 if (filter (EndInvokeBuilder, criteria))\r
345                                         members.Add (EndInvokeBuilder);\r
346                         }\r
347 \r
348                         int count = members.Count;\r
349 \r
350                         if (count > 0) {\r
351                                 MemberInfo [] mi = new MemberInfo [count];\r
352                                 members.CopyTo (mi, 0);\r
353                                 return mi;\r
354                         }\r
355 \r
356                         return null;\r
357                 }\r
358                 \r
359                 public void CloseDelegate ()\r
360                 {\r
361                         TypeBuilder.CreateType ();\r
362                 }\r
363                 \r
364                 public int ModFlags {\r
365                         get {\r
366                                 return mod_flags;\r
367                         }\r
368                 }\r
369 \r
370                 public Expression InstanceExpression {\r
371                         get {\r
372                                 return instance_expr;\r
373                         }\r
374                         set {\r
375                                 instance_expr = value;\r
376                         }\r
377                 }\r
378 \r
379                 public MethodBase TargetMethod {\r
380                         get {\r
381                                 return delegate_method;\r
382                         }\r
383                         set {\r
384                                 delegate_method = value;\r
385                         }\r
386                 }\r
387 \r
388                 public Type TargetReturnType {\r
389                         get {\r
390                                 return ret_type;\r
391                         }\r
392                 }\r
393 \r
394                 public Type [] ParameterTypes {\r
395                         get {\r
396                                 return param_types;\r
397                         }\r
398                 }\r
399                 \r
400         }\r
401 \r
402         public class NewDelegate : Expression {\r
403 \r
404                 public ArrayList Arguments;\r
405 \r
406                 MethodBase constructor_method;\r
407                 MethodBase delegate_method;\r
408                 Expression delegate_instance_expr;\r
409 \r
410                 Location Location;\r
411                 \r
412                 public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
413                 {\r
414                         this.type = type;\r
415                         this.Arguments = Arguments;\r
416                         this.Location  = loc; \r
417                 }\r
418 \r
419                 public override Expression DoResolve (EmitContext ec)\r
420                 {\r
421                         Delegate del = TypeManager.LookupDelegate (type);\r
422                         constructor_method = del.ConstructorBuilder;\r
423                         \r
424                         if (Arguments == null) {\r
425                                 Report.Error (-11, Location,\r
426                                               "Delegate creation expression takes only one argument");\r
427                                 return null;\r
428                         }\r
429                         \r
430                         if (Arguments.Count != 1) {\r
431                                 Report.Error (-11, Location,\r
432                                               "Delegate creation expression takes only one argument");\r
433                                 return null;\r
434                         }\r
435                         \r
436                         Argument a = (Argument) Arguments [0];\r
437                         \r
438                         if (!a.Resolve (ec, Location))\r
439                                 return null;\r
440                         \r
441                         Expression e = a.Expr;\r
442                         \r
443                         if (e is MethodGroupExpr) {\r
444                                 MethodGroupExpr mg = (MethodGroupExpr) e;\r
445                                 \r
446                                 delegate_method  = del.VerifyMethod (mg.Methods [0], Location);\r
447                                 \r
448                                 if (delegate_method == null)\r
449                                         return null;\r
450                                 \r
451                                 if (mg.InstanceExpression != null)\r
452                                         delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\r
453                                 else\r
454                                         delegate_instance_expr = null;\r
455                                 \r
456                                 if (delegate_instance_expr != null)\r
457                                         if (delegate_instance_expr.Type.IsValueType)\r
458                                                 delegate_instance_expr = new BoxedCast (delegate_instance_expr);\r
459                                 \r
460                                 \r
461                                 del.InstanceExpression = delegate_instance_expr;\r
462                                 del.TargetMethod = delegate_method;\r
463                                 \r
464                                 eclass = ExprClass.Value;\r
465                                 return this;\r
466                         }\r
467 \r
468                         Type e_type = e.Type;\r
469 \r
470                         Delegate d = TypeManager.LookupDelegate (e_type);\r
471 \r
472                         if (d == null) {\r
473                                 Report.Error (-12, Location, "Cannot create a delegate from something " +\r
474                                               "not a delegate or a method.");\r
475                                 return null;\r
476                         }\r
477 \r
478                         // This is what MS's compiler reports. We could always choose\r
479                         // to be more verbose and actually give delegate-level specifics\r
480                         \r
481                         if (!d.VerifyDelegate (del)) {\r
482                                 Report.Error (29, Location, "Cannot implicitly convert type '" + d.Name + "' " +\r
483                                               "to type '" + del.Name + "'");\r
484                                 return null;\r
485                         }\r
486 \r
487                         delegate_instance_expr = d.InstanceExpression;\r
488                         delegate_method        = d.TargetMethod;\r
489                         \r
490                         del.InstanceExpression = d.InstanceExpression;\r
491                         del.TargetMethod       = d.TargetMethod;\r
492                         \r
493                         eclass = ExprClass.Value;\r
494                         return this;\r
495                 }\r
496                 \r
497                 public override void Emit (EmitContext ec)\r
498                 {\r
499                         if (delegate_instance_expr == null)\r
500                                 ec.ig.Emit (OpCodes.Ldnull);\r
501                         else\r
502                                 delegate_instance_expr.Emit (ec);\r
503                         \r
504                         ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);\r
505                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);\r
506                 }\r
507         }\r
508 \r
509         public class DelegateInvocation : ExpressionStatement {\r
510 \r
511                 public Expression InstanceExpr;\r
512                 public ArrayList  Arguments;\r
513                 public Location   Location;\r
514 \r
515                 MethodBase method;\r
516                 \r
517                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)\r
518                 {\r
519                         this.InstanceExpr = instance_expr;\r
520                         this.Arguments = args;\r
521                         this.Location = loc;\r
522                 }\r
523 \r
524                 public override Expression DoResolve (EmitContext ec)\r
525                 {\r
526                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
527 \r
528                         if (del == null)\r
529                                 return null;\r
530 \r
531                         if (del.TargetMethod == null)\r
532                                 return null;\r
533                         \r
534                         if (Arguments != null){\r
535                                 for (int i = Arguments.Count; i > 0;){\r
536                                         --i;\r
537                                         Argument a = (Argument) Arguments [i];\r
538                                         \r
539                                         if (!a.Resolve (ec, Location))\r
540                                                 return null;\r
541                                 }\r
542                         }\r
543                         \r
544                         if (!del.VerifyApplicability (ec, Arguments, Location))\r
545                                 return null;\r
546                         \r
547                         method = del.InvokeBuilder;\r
548                         type = ((MethodInfo) method).ReturnType;\r
549                         \r
550                         eclass = ExprClass.Value;\r
551                         \r
552                         return this;\r
553                 }\r
554 \r
555                 public override void Emit (EmitContext ec)\r
556                 {\r
557                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
558 \r
559                         //\r
560                         // Invocation on delegates call the virtual Invoke member\r
561                         // so we are always `instance' calls\r
562                         //\r
563                         Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments);\r
564                 }\r
565 \r
566                 public override void EmitStatement (EmitContext ec)\r
567                 {\r
568                         Emit (ec);\r
569                         // \r
570                         // Pop the return value if there is one\r
571                         //\r
572                         if (method is MethodInfo){\r
573                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)\r
574                                         ec.ig.Emit (OpCodes.Pop);\r
575                         }\r
576                 }\r
577 \r
578         }\r
579 }\r