2001-11-14 Miguel de Icaza <miguel@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                         int params_num = param_types.Length;\r
129                         Type [] async_param_types = new Type [params_num + 2];\r
130 \r
131                         param_types.CopyTo (async_param_types, 0);\r
132 \r
133                         async_param_types [params_num] = TypeManager.asynccallback_type;\r
134                         async_param_types [params_num + 1] = TypeManager.object_type;\r
135 \r
136                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |\r
137                                 MethodAttributes.NewSlot;\r
138                         \r
139                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",\r
140                                                                        mattr,\r
141                                                                        cc,\r
142                                                                        TypeManager.iasyncresult_type,\r
143                                                                        async_param_types);\r
144 \r
145                         for (i = 0 ; i < param_types.Length; i++) {\r
146                                 Parameter p = Parameters.FixedParameters [i];\r
147                                 string name = p.Name;\r
148                                 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name); \r
149                         }\r
150                         \r
151                         BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");\r
152                         BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");\r
153                         \r
154                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
155 \r
156                         Type [] end_param_types = new Type [1];\r
157 \r
158                         end_param_types [0] = TypeManager.iasyncresult_type;\r
159                         \r
160                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",\r
161                                                                      mattr,\r
162                                                                      cc,\r
163                                                                      ret_type,\r
164                                                                      end_param_types);\r
165                         EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");\r
166                         \r
167                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
168                         \r
169                 }\r
170 \r
171                 // <summary>\r
172                 //  Verifies whether the method in question is compatible with the delegate\r
173                 //  Returns the method itself if okay and null if not.\r
174                 // </summary>\r
175                 public MethodBase VerifyMethod (MethodBase mb, Location loc)\r
176                 {\r
177                         ParameterData pd = Invocation.GetParameterData (mb);\r
178 \r
179                         bool mismatch = false;\r
180                         for (int i = param_types.Length; i > 0; ) {\r
181                                 i--;\r
182 \r
183                                 if (param_types [i] == pd.ParameterType (i))\r
184                                         continue;\r
185                                 else {\r
186                                         mismatch = true;\r
187                                         break;\r
188                                 }\r
189                         }\r
190 \r
191                         if (mismatch) {\r
192                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
193                                               "delegate '" + FullDelegateDesc () + "'");\r
194                                 return null;\r
195                         }\r
196 \r
197                         if (ret_type == ((MethodInfo) mb).ReturnType)\r
198                                 return mb;\r
199                         else\r
200                                 mismatch = true;\r
201 \r
202                         if (mismatch) {\r
203                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
204                                               "delegate '" + FullDelegateDesc () + "'");\r
205                                 return null;\r
206                         }\r
207 \r
208                         return null;\r
209                 }\r
210 \r
211                 // <summary>\r
212                 //  Verifies whether the invocation arguments are compatible with the\r
213                 //  delegate's target method\r
214                 // </summary>\r
215                 public bool VerifyApplicability (EmitContext ec, ArrayList args, Location loc)\r
216                 {\r
217                         int arg_count;\r
218 \r
219                         if (args == null)\r
220                                 arg_count = 0;\r
221                         else\r
222                                 arg_count = args.Count;\r
223                         \r
224                         if (param_types.Length != arg_count) {\r
225                                 Report.Error (1593, loc,\r
226                                               "Delegate '" + Name + "' does not take '" + arg_count + "' arguments");\r
227                                 return false;\r
228                         }\r
229 \r
230                         for (int i = arg_count; i > 0;) {\r
231                                 i--;\r
232                                 Expression conv;\r
233                                 Argument a = (Argument) args [i];\r
234                                 Expression a_expr = a.Expr;\r
235                                 \r
236                                 if (param_types [i] != a_expr.Type) {\r
237                                         \r
238                                         conv = Expression.ConvertImplicitStandard (ec, a_expr, param_types [i], loc);\r
239 \r
240                                         if (conv == null) {\r
241                                                 Report.Error (1594, loc,\r
242                                                               "Delegate '" + Name + "' has some invalid arguments.");\r
243 \r
244                                                 Report.Error (1503, loc,\r
245                                                        "Argument " + (i+1) +\r
246                                                        ": Cannot convert from '" +\r
247                                                        TypeManager.CSharpName (a_expr.Type)\r
248                                                        + "' to '" + TypeManager.CSharpName (param_types [i]) + "'");\r
249                                                 return false;\r
250                                         }\r
251 \r
252                                         if (a_expr != conv)\r
253                                                 a.Expr = conv;\r
254                                 }\r
255                         }\r
256 \r
257                         return true;\r
258                 }\r
259 \r
260                 // <summary>\r
261                 //  Verifies whether the delegate in question is compatible with this one in\r
262                 //  order to determine if instantiation from the same is possible.\r
263                 // </summary>\r
264                 public bool VerifyDelegate (Delegate del)\r
265                 {\r
266                         if (ret_type != del.TargetReturnType)\r
267                                 return false;\r
268 \r
269                         Type [] other_param_types = del.ParameterTypes;\r
270                         \r
271                         if (param_types.Length != other_param_types.Length)\r
272                                 return false;\r
273 \r
274                         for (int i = param_types.Length; i > 0; ) {\r
275                                 i--;\r
276 \r
277                                 if (param_types [i] != other_param_types [i])\r
278                                         return false;\r
279                         }\r
280 \r
281                         // FIXME : Hey, what about parameter modifiers ?\r
282 \r
283                         return true;\r
284 \r
285                 }\r
286                 \r
287                 public string FullDelegateDesc ()\r
288                 {\r
289                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (System.Type.GetType (ReturnType)));\r
290                         \r
291                         sb.Append (" " + Name);\r
292                         sb.Append (" (");\r
293 \r
294                         int length = param_types.Length;\r
295                         \r
296                         for (int i = length; i > 0; ) {\r
297                                 i--;\r
298                                 \r
299                                 sb.Append (TypeManager.CSharpName (param_types [length - i - 1]));\r
300                                 if (i != 0)\r
301                                         sb.Append (", ");\r
302                         }\r
303                         \r
304                         sb.Append (")");\r
305                         return sb.ToString ();\r
306                         \r
307                 }\r
308                 \r
309                 // Hack around System.Reflection as found everywhere else\r
310                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)\r
311                 {\r
312                         ArrayList members = new ArrayList ();\r
313 \r
314                         if ((mt & MemberTypes.Method) != 0) {\r
315                                 if (filter (ConstructorBuilder, criteria))\r
316                                         members.Add (ConstructorBuilder);\r
317 \r
318                                 if (filter (InvokeBuilder, criteria))\r
319                                         members.Add (InvokeBuilder);\r
320 \r
321                                 if (filter (BeginInvokeBuilder, criteria))\r
322                                         members.Add (BeginInvokeBuilder);\r
323 \r
324                                 if (filter (EndInvokeBuilder, criteria))\r
325                                         members.Add (EndInvokeBuilder);\r
326                         }\r
327 \r
328                         int count = members.Count;\r
329 \r
330                         if (count > 0) {\r
331                                 MemberInfo [] mi = new MemberInfo [count];\r
332                                 members.CopyTo (mi, 0);\r
333                                 return mi;\r
334                         }\r
335 \r
336                         return null;\r
337                 }\r
338                 \r
339                 public void CloseDelegate ()\r
340                 {\r
341                         TypeBuilder.CreateType ();\r
342                 }\r
343                 \r
344                 public int ModFlags {\r
345                         get {\r
346                                 return mod_flags;\r
347                         }\r
348                 }\r
349 \r
350                 public Expression InstanceExpression {\r
351                         get {\r
352                                 return instance_expr;\r
353                         }\r
354                         set {\r
355                                 instance_expr = value;\r
356                         }\r
357                 }\r
358 \r
359                 public MethodBase TargetMethod {\r
360                         get {\r
361                                 return delegate_method;\r
362                         }\r
363                         set {\r
364                                 delegate_method = value;\r
365                         }\r
366                 }\r
367 \r
368                 public Type TargetReturnType {\r
369                         get {\r
370                                 return ret_type;\r
371                         }\r
372                 }\r
373 \r
374                 public Type [] ParameterTypes {\r
375                         get {\r
376                                 return param_types;\r
377                         }\r
378                 }\r
379                 \r
380         }\r
381 \r
382         public class NewDelegate : Expression {\r
383 \r
384                 public ArrayList Arguments;\r
385 \r
386                 MethodBase constructor_method;\r
387                 MethodBase delegate_method;\r
388                 Expression delegate_instance_expr;\r
389 \r
390                 Location Location;\r
391                 \r
392                 public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
393                 {\r
394                         this.type = type;\r
395                         this.Arguments = Arguments;\r
396                         this.Location  = loc; \r
397                 }\r
398 \r
399                 public override Expression DoResolve (EmitContext ec)\r
400                 {\r
401                         Delegate del = TypeManager.LookupDelegate (type);\r
402                         constructor_method = del.ConstructorBuilder;\r
403                         \r
404                         if (Arguments == null) {\r
405                                 Report.Error (-11, Location,\r
406                                               "Delegate creation expression takes only one argument");\r
407                                 return null;\r
408                         }\r
409                         \r
410                         if (Arguments.Count != 1) {\r
411                                 Report.Error (-11, Location,\r
412                                               "Delegate creation expression takes only one argument");\r
413                                 return null;\r
414                         }\r
415                         \r
416                         Argument a = (Argument) Arguments [0];\r
417                         \r
418                         if (!a.Resolve (ec))\r
419                                 return null;\r
420                         \r
421                         Expression e = a.Expr;\r
422                         \r
423                         if (e is MethodGroupExpr) {\r
424                                 MethodGroupExpr mg = (MethodGroupExpr) e;\r
425                                 \r
426                                 delegate_method  = del.VerifyMethod (mg.Methods [0], Location);\r
427                                 \r
428                                 if (delegate_method == null)\r
429                                         return null;\r
430                                 \r
431                                 if (mg.InstanceExpression != null)\r
432                                         delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\r
433                                 else\r
434                                         delegate_instance_expr = null;\r
435                                 \r
436                                 if (delegate_instance_expr != null)\r
437                                         if (delegate_instance_expr.Type.IsValueType)\r
438                                                 delegate_instance_expr = new BoxedCast (delegate_instance_expr);\r
439                                 \r
440                                 \r
441                                 del.InstanceExpression = delegate_instance_expr;\r
442                                 del.TargetMethod = delegate_method;\r
443                                 \r
444                                 eclass = ExprClass.Value;\r
445                                 return this;\r
446                         }\r
447 \r
448                         Type e_type = e.Type;\r
449 \r
450                         Delegate d = TypeManager.LookupDelegate (e_type);\r
451 \r
452                         if (d == null) {\r
453                                 Report.Error (-12, Location, "Cannot create a delegate from something " +\r
454                                               "not a delegate or a method.");\r
455                                 return null;\r
456                         }\r
457 \r
458                         // This is what MS's compiler reports. We could always choose\r
459                         // to be more verbose and actually give delegate-level specifics\r
460                         \r
461                         if (!d.VerifyDelegate (del)) {\r
462                                 Report.Error (29, Location, "Cannot implicitly convert type '" + d.Name + "' " +\r
463                                               "to type '" + del.Name + "'");\r
464                                 return null;\r
465                         }\r
466 \r
467                         delegate_instance_expr = d.InstanceExpression;\r
468                         delegate_method        = d.TargetMethod;\r
469                         \r
470                         del.InstanceExpression = d.InstanceExpression;\r
471                         del.TargetMethod       = d.TargetMethod;\r
472                         \r
473                         eclass = ExprClass.Value;\r
474                         return this;\r
475                 }\r
476                 \r
477                 public override void Emit (EmitContext ec)\r
478                 {\r
479                         if (delegate_instance_expr == null)\r
480                                 ec.ig.Emit (OpCodes.Ldnull);\r
481                         else\r
482                                 delegate_instance_expr.Emit (ec);\r
483                         \r
484                         ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);\r
485                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);\r
486                 }\r
487         }\r
488 \r
489         public class DelegateInvocation : ExpressionStatement {\r
490 \r
491                 public Expression InstanceExpr;\r
492                 public ArrayList  Arguments;\r
493                 public Location   Location;\r
494 \r
495                 MethodBase method;\r
496                 \r
497                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)\r
498                 {\r
499                         this.InstanceExpr = instance_expr;\r
500                         this.Arguments = args;\r
501                         this.Location = loc;\r
502                 }\r
503 \r
504                 public override Expression DoResolve (EmitContext ec)\r
505                 {\r
506                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
507 \r
508                         if (del == null)\r
509                                 return null;\r
510 \r
511                         if (del.TargetMethod == null)\r
512                                 return null;\r
513                         \r
514                         if (Arguments != null){\r
515                                 for (int i = Arguments.Count; i > 0;){\r
516                                         --i;\r
517                                         Argument a = (Argument) Arguments [i];\r
518                                         \r
519                                         if (!a.Resolve (ec))\r
520                                                 return null;\r
521                                 }\r
522                         }\r
523                         \r
524                         if (!del.VerifyApplicability (ec, Arguments, Location))\r
525                                 return null;\r
526                         \r
527                         method = del.InvokeBuilder;\r
528                         type = ((MethodInfo) method).ReturnType;\r
529                         \r
530                         eclass = ExprClass.Value;\r
531                         \r
532                         return this;\r
533                 }\r
534 \r
535                 public override void Emit (EmitContext ec)\r
536                 {\r
537                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
538 \r
539                         //\r
540                         // Invocation on delegates call the virtual Invoke member\r
541                         // so we are always `instance' calls\r
542                         //\r
543                         Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments);\r
544                 }\r
545 \r
546                 public override void EmitStatement (EmitContext ec)\r
547                 {\r
548                         Emit (ec);\r
549                         // \r
550                         // Pop the return value if there is one\r
551                         //\r
552                         if (method is MethodInfo){\r
553                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)\r
554                                         ec.ig.Emit (OpCodes.Pop);\r
555                         }\r
556                 }\r
557 \r
558         }\r
559 }\r