2001-10-31 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                         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                 public void CloseDelegate ()\r
310                 {\r
311                         TypeBuilder.CreateType ();\r
312                 }\r
313                 \r
314                 public int ModFlags {\r
315                         get {\r
316                                 return mod_flags;\r
317                         }\r
318                 }\r
319 \r
320                 public Expression InstanceExpression {\r
321                         get {\r
322                                 return instance_expr;\r
323                         }\r
324                         set {\r
325                                 instance_expr = value;\r
326                         }\r
327                 }\r
328 \r
329                 public MethodBase TargetMethod {\r
330                         get {\r
331                                 return delegate_method;\r
332                         }\r
333                         set {\r
334                                 delegate_method = value;\r
335                         }\r
336                 }\r
337 \r
338                 public Type TargetReturnType {\r
339                         get {\r
340                                 return ret_type;\r
341                         }\r
342                 }\r
343 \r
344                 public Type [] ParameterTypes {\r
345                         get {\r
346                                 return param_types;\r
347                         }\r
348                 }\r
349                 \r
350         }\r
351 \r
352         public class NewDelegate : Expression {\r
353 \r
354                 public ArrayList Arguments;\r
355 \r
356                 MethodBase constructor_method;\r
357                 MethodBase delegate_method;\r
358                 Expression delegate_instance_expr;\r
359 \r
360                 Location Location;\r
361                 \r
362                 public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
363                 {\r
364                         this.type = type;\r
365                         this.Arguments = Arguments;\r
366                         this.Location  = loc; \r
367                 }\r
368 \r
369                 public override Expression DoResolve (EmitContext ec)\r
370                 {\r
371                         Delegate del = TypeManager.LookupDelegate (type);\r
372                         constructor_method = del.ConstructorBuilder;\r
373                         \r
374                         if (Arguments == null) {\r
375                                 Report.Error (-11, Location,\r
376                                               "Delegate creation expression takes only one argument");\r
377                                 return null;\r
378                         }\r
379                         \r
380                         if (Arguments.Count != 1) {\r
381                                 Report.Error (-11, Location,\r
382                                               "Delegate creation expression takes only one argument");\r
383                                 return null;\r
384                         }\r
385                         \r
386                         Argument a = (Argument) Arguments [0];\r
387                         \r
388                         if (!a.Resolve (ec))\r
389                                 return null;\r
390                         \r
391                         Expression e = a.Expr;\r
392                         \r
393                         if (e is MethodGroupExpr) {\r
394                                 MethodGroupExpr mg = (MethodGroupExpr) e;\r
395                                 \r
396                                 delegate_method  = del.VerifyMethod (mg.Methods [0], Location);\r
397                                 \r
398                                 if (delegate_method == null)\r
399                                         return null;\r
400                                 \r
401                                 if (mg.InstanceExpression != null)\r
402                                         delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\r
403                                 else\r
404                                         delegate_instance_expr = null;\r
405                                 \r
406                                 if (delegate_instance_expr != null)\r
407                                         if (delegate_instance_expr.Type.IsValueType)\r
408                                                 delegate_instance_expr = new BoxedCast (delegate_instance_expr);\r
409                                 \r
410                                 \r
411                                 del.InstanceExpression = delegate_instance_expr;\r
412                                 del.TargetMethod = delegate_method;\r
413                                 \r
414                                 eclass = ExprClass.Value;\r
415                                 return this;\r
416                         }\r
417 \r
418                         Type e_type = e.Type;\r
419 \r
420                         Delegate d = TypeManager.LookupDelegate (e_type);\r
421 \r
422                         if (d == null) {\r
423                                 Report.Error (-12, Location, "Cannot create a delegate from something " +\r
424                                               "not a delegate or a method.");\r
425                                 return null;\r
426                         }\r
427 \r
428                         // This is what MS's compiler reports. We could always choose\r
429                         // to be more verbose and actually give delegate-level specifics\r
430                         \r
431                         if (!d.VerifyDelegate (del)) {\r
432                                 Report.Error (29, Location, "Cannot implicitly convert type '" + d.Name + "' " +\r
433                                               "to type '" + del.Name + "'");\r
434                                 return null;\r
435                         }\r
436 \r
437                         delegate_instance_expr = d.InstanceExpression;\r
438                         delegate_method        = d.TargetMethod;\r
439                         \r
440                         del.InstanceExpression = d.InstanceExpression;\r
441                         del.TargetMethod       = d.TargetMethod;\r
442                         \r
443                         eclass = ExprClass.Value;\r
444                         return this;\r
445                 }\r
446                 \r
447                 public override void Emit (EmitContext ec)\r
448                 {\r
449                         if (delegate_instance_expr == null)\r
450                                 ec.ig.Emit (OpCodes.Ldnull);\r
451                         else\r
452                                 delegate_instance_expr.Emit (ec);\r
453                         \r
454                         ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);\r
455                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);\r
456                 }\r
457         }\r
458 \r
459         public class DelegateInvocation : ExpressionStatement {\r
460 \r
461                 public Expression InstanceExpr;\r
462                 public ArrayList  Arguments;\r
463                 public Location   Location;\r
464 \r
465                 MethodBase method;\r
466                 \r
467                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)\r
468                 {\r
469                         this.InstanceExpr = instance_expr;\r
470                         this.Arguments = args;\r
471                         this.Location = loc;\r
472                 }\r
473 \r
474                 public override Expression DoResolve (EmitContext ec)\r
475                 {\r
476                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
477 \r
478                         if (del == null)\r
479                                 return null;\r
480 \r
481                         if (del.TargetMethod == null)\r
482                                 return null;\r
483                         \r
484                         if (Arguments != null){\r
485                                 for (int i = Arguments.Count; i > 0;){\r
486                                         --i;\r
487                                         Argument a = (Argument) Arguments [i];\r
488                                         \r
489                                         if (!a.Resolve (ec))\r
490                                                 return null;\r
491                                 }\r
492                         }\r
493                         \r
494                         if (!del.VerifyApplicability (ec, Arguments, Location))\r
495                                 return null;\r
496                         \r
497                         method = del.InvokeBuilder;\r
498                         type = ((MethodInfo) method).ReturnType;\r
499                         \r
500                         eclass = ExprClass.Value;\r
501                         \r
502                         return this;\r
503                 }\r
504 \r
505                 public override void Emit (EmitContext ec)\r
506                 {\r
507                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
508                         Invocation.EmitCall (ec, del.TargetMethod.IsStatic, InstanceExpr, method, Arguments);\r
509                 }\r
510 \r
511                 public override void EmitStatement (EmitContext ec)\r
512                 {\r
513                         Emit (ec);\r
514                         // \r
515                         // Pop the return value if there is one\r
516                         //\r
517                         if (method is MethodInfo){\r
518                                 if (((MethodInfo) method).ReturnType != TypeManager.void_type)\r
519                                         ec.ig.Emit (OpCodes.Pop);\r
520                         }\r
521                 }\r
522 \r
523         }\r
524 }\r