2001-10-17 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                         \r
91                         Type [] const_arg_types = new Type [2];\r
92 \r
93                         const_arg_types [0] = TypeManager.object_type;\r
94                         const_arg_types [1] = TypeManager.intptr_type;\r
95 \r
96                         mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |\r
97                                 MethodAttributes.HideBySig | MethodAttributes.Public;\r
98 \r
99                         ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,\r
100                                                                             CallingConventions.Standard,\r
101                                                                             const_arg_types);\r
102                         \r
103                         ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
104                         \r
105                         // Here the various methods like Invoke, BeginInvoke etc are defined\r
106 \r
107                         param_types = Parameters.GetParameterInfo (parent);\r
108                         ret_type = parent.LookupType (ReturnType, false);\r
109                         CallingConventions cc = Parameters.GetCallingConvention ();\r
110 \r
111                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;\r
112 \r
113                         InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", \r
114                                                                   mattr,                     \r
115                                                                   cc,\r
116                                                                   ret_type,                  \r
117                                                                   param_types);\r
118                         \r
119                         InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
120 \r
121                         int params_num = param_types.Length;\r
122                         Type [] async_param_types = new Type [params_num + 2];\r
123 \r
124                         param_types.CopyTo (async_param_types, 0);\r
125 \r
126                         async_param_types [params_num] = TypeManager.asynccallback_type;\r
127                         async_param_types [params_num + 1] = TypeManager.object_type;\r
128 \r
129                         mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |\r
130                                 MethodAttributes.NewSlot;\r
131                         \r
132                         BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",\r
133                                                                        mattr,\r
134                                                                        cc,\r
135                                                                        TypeManager.iasyncresult_type,\r
136                                                                        async_param_types);\r
137                         \r
138                         BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
139 \r
140                         Type [] end_param_types = new Type [1];\r
141 \r
142                         end_param_types [0] = TypeManager.iasyncresult_type;\r
143                         \r
144                         EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",\r
145                                                                      mattr,\r
146                                                                      cc,\r
147                                                                      ret_type,\r
148                                                                      end_param_types);\r
149 \r
150                         EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
151                         \r
152                 }\r
153 \r
154                 // <summary>\r
155                 //  Verifies whether the method in question is compatible with the delegate\r
156                 //  Returns the method itself if okay and null if not.\r
157                 // </summary>\r
158                 public MethodBase VerifyMethod (MethodBase mb, Location loc)\r
159                 {\r
160                         ParameterData pd = Invocation.GetParameterData (mb);\r
161 \r
162                         bool mismatch = false;\r
163                         for (int i = param_types.Length; i > 0; ) {\r
164                                 i--;\r
165 \r
166                                 if (param_types [i] == pd.ParameterType (i))\r
167                                         continue;\r
168                                 else {\r
169                                         mismatch = true;\r
170                                         break;\r
171                                 }\r
172                         }\r
173 \r
174                         if (mismatch) {\r
175                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
176                                               "delegate '" + FullDelegateDesc () + "'");\r
177                                 return null;\r
178                         }\r
179 \r
180                         if (ret_type == ((MethodInfo) mb).ReturnType)\r
181                                 return mb;\r
182                         else\r
183                                 mismatch = true;\r
184 \r
185                         if (mismatch) {\r
186                                 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
187                                               "delegate '" + FullDelegateDesc () + "'");\r
188                                 return null;\r
189                         }\r
190 \r
191                         return null;\r
192                 }\r
193 \r
194                 // <summary>\r
195                 //  Verifies whether the invocation arguments are compatible with the\r
196                 //  delegate's target method\r
197                 // </summary>\r
198                 public bool VerifyApplicability (EmitContext ec, ArrayList args, Location loc)\r
199                 {\r
200                         int arg_count;\r
201 \r
202                         if (args == null)\r
203                                 arg_count = 0;\r
204                         else\r
205                                 arg_count = args.Count;\r
206                         \r
207                         if (param_types.Length != arg_count) {\r
208                                 Report.Error (1593, loc,\r
209                                               "Delegate '" + Name + "' does not take '" + arg_count + "' arguments");\r
210                                 return false;\r
211                         }\r
212 \r
213                         for (int i = arg_count; i > 0;) {\r
214                                 i--;\r
215                                 Expression conv;\r
216                                 Argument a = (Argument) args [i];\r
217                                 Expression a_expr = a.Expr;\r
218                                 \r
219                                 if (param_types [i] != a_expr.Type) {\r
220                                         \r
221                                         conv = Expression.ConvertImplicitStandard (ec, a_expr, param_types [i], loc);\r
222 \r
223                                         if (conv == null) {\r
224                                                 Report.Error (1594, loc,\r
225                                                               "Delegate '" + Name + "' has some invalid arguments.");\r
226 \r
227                                                 Report.Error (1503, loc,\r
228                                                        "Argument " + (i+1) +\r
229                                                        ": Cannot convert from '" +\r
230                                                        TypeManager.CSharpName (a_expr.Type)\r
231                                                        + "' to '" + TypeManager.CSharpName (param_types [i]) + "'");\r
232                                                 return false;\r
233                                         }\r
234 \r
235                                         if (a_expr != conv)\r
236                                                 a.Expr = conv;\r
237                                 }\r
238                         }\r
239 \r
240                         return true;\r
241                 }\r
242 \r
243                 // <summary>\r
244                 //  Verifies whether the delegate in question is compatible with this one in\r
245                 //  order to determine if instantiation from the same is possible.\r
246                 // </summary>\r
247                 public bool VerifyDelegate (Delegate del)\r
248                 {\r
249                         if (ret_type != del.TargetReturnType)\r
250                                 return false;\r
251 \r
252                         Type [] other_param_types = del.ParameterTypes;\r
253                         \r
254                         if (param_types.Length != other_param_types.Length)\r
255                                 return false;\r
256 \r
257                         for (int i = param_types.Length; i > 0; ) {\r
258                                 i--;\r
259 \r
260                                 if (param_types [i] != other_param_types [i])\r
261                                         return false;\r
262                         }\r
263 \r
264                         // FIXME : Hey, what about parameter modifiers ?\r
265 \r
266                         return true;\r
267 \r
268                 }\r
269                 \r
270                 public string FullDelegateDesc ()\r
271                 {\r
272                         StringBuilder sb = new StringBuilder (TypeManager.CSharpName (System.Type.GetType (ReturnType)));\r
273                         \r
274                         sb.Append (" " + Name);\r
275                         sb.Append (" (");\r
276 \r
277                         int length = param_types.Length;\r
278                         \r
279                         for (int i = length; i > 0; ) {\r
280                                 i--;\r
281                                 \r
282                                 sb.Append (TypeManager.CSharpName (param_types [length - i - 1]));\r
283                                 if (i != 0)\r
284                                         sb.Append (", ");\r
285                         }\r
286                         \r
287                         sb.Append (")");\r
288                         return sb.ToString ();\r
289                         \r
290                 }\r
291                 \r
292                 public void CloseDelegate ()\r
293                 {\r
294                         TypeBuilder.CreateType ();\r
295                 }\r
296                 \r
297                 public int ModFlags {\r
298                         get {\r
299                                 return mod_flags;\r
300                         }\r
301                 }\r
302 \r
303                 public Expression InstanceExpression {\r
304                         get {\r
305                                 return instance_expr;\r
306                         }\r
307                         set {\r
308                                 instance_expr = value;\r
309                         }\r
310                 }\r
311 \r
312                 public MethodBase TargetMethod {\r
313                         get {\r
314                                 return delegate_method;\r
315                         }\r
316                         set {\r
317                                 delegate_method = value;\r
318                         }\r
319                 }\r
320 \r
321                 public Type TargetReturnType {\r
322                         get {\r
323                                 return ret_type;\r
324                         }\r
325                 }\r
326 \r
327                 public Type [] ParameterTypes {\r
328                         get {\r
329                                 return param_types;\r
330                         }\r
331                 }\r
332                 \r
333         }\r
334 \r
335         public class NewDelegate : Expression {\r
336 \r
337                 public ArrayList Arguments;\r
338 \r
339                 MethodBase constructor_method;\r
340                 MethodBase delegate_method;\r
341                 Expression delegate_instance_expr;\r
342 \r
343                 Location Location;\r
344                 \r
345                 public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
346                 {\r
347                         this.type = type;\r
348                         this.Arguments = Arguments;\r
349                         this.Location  = loc; \r
350                 }\r
351 \r
352                 public override Expression DoResolve (EmitContext ec)\r
353                 {\r
354                         Delegate del = TypeManager.LookupDelegate (type);\r
355                         constructor_method = del.ConstructorBuilder;\r
356                         \r
357                         if (Arguments == null) {\r
358                                 Report.Error (-11, Location,\r
359                                               "Delegate creation expression takes only one argument");\r
360                                 return null;\r
361                         }\r
362                         \r
363                         if (Arguments.Count != 1) {\r
364                                 Report.Error (-11, Location,\r
365                                               "Delegate creation expression takes only one argument");\r
366                                 return null;\r
367                         }\r
368                         \r
369                         Argument a = (Argument) Arguments [0];\r
370                         \r
371                         if (!a.Resolve (ec))\r
372                                 return null;\r
373                         \r
374                         Expression e = a.Expr;\r
375                         \r
376                         if (e is MethodGroupExpr) {\r
377                                 MethodGroupExpr mg = (MethodGroupExpr) e;\r
378                                 \r
379                                 delegate_method  = del.VerifyMethod (mg.Methods [0], Location);\r
380                                 \r
381                                 if (delegate_method == null)\r
382                                         return null;\r
383                                 \r
384                                 if (mg.InstanceExpression != null)\r
385                                         delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\r
386                                 else\r
387                                         delegate_instance_expr = null;\r
388                                 \r
389                                 if (delegate_instance_expr != null)\r
390                                         if (delegate_instance_expr.Type.IsValueType)\r
391                                                 delegate_instance_expr = new BoxedCast (delegate_instance_expr);\r
392                                 \r
393                                 \r
394                                 del.InstanceExpression = delegate_instance_expr;\r
395                                 del.TargetMethod = delegate_method;\r
396                                 \r
397                                 eclass = ExprClass.Value;\r
398                                 return this;\r
399                         }\r
400 \r
401                         Type e_type = e.Type;\r
402 \r
403                         Delegate d = TypeManager.LookupDelegate (e_type);\r
404 \r
405                         if (d == null) {\r
406                                 Report.Error (-12, Location, "Cannot create a delegate from something " +\r
407                                               "not a delegate or a method.");\r
408                                 return null;\r
409                         }\r
410 \r
411                         // This is what MS's compiler reports. We could always choose\r
412                         // to be more verbose and actually give delegate-level specifics\r
413                         \r
414                         if (!d.VerifyDelegate (del)) {\r
415                                 Report.Error (29, Location, "Cannot implicitly convert type '" + d.Name + "' " +\r
416                                               "to type '" + del.Name + "'");\r
417                                 return null;\r
418                         }\r
419 \r
420                         delegate_instance_expr = d.InstanceExpression;\r
421                         delegate_method        = d.TargetMethod;\r
422                         \r
423                         del.InstanceExpression = d.InstanceExpression;\r
424                         del.TargetMethod       = d.TargetMethod;\r
425                         \r
426                         eclass = ExprClass.Value;\r
427                         return this;\r
428                 }\r
429                 \r
430                 public override void Emit (EmitContext ec)\r
431                 {\r
432                         if (delegate_instance_expr == null)\r
433                                 ec.ig.Emit (OpCodes.Ldnull);\r
434                         else\r
435                                 delegate_instance_expr.Emit (ec);\r
436                         \r
437                         ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);\r
438                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);\r
439                 }\r
440         }\r
441 \r
442         public class DelegateInvocation : Expression {\r
443 \r
444                 public Expression InstanceExpr;\r
445                 public ArrayList  Arguments;\r
446                 public Location   Location;\r
447 \r
448                 MethodBase method;\r
449                 \r
450                 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)\r
451                 {\r
452                         this.InstanceExpr = instance_expr;\r
453                         this.Arguments = args;\r
454                         this.Location = loc;\r
455                 }\r
456 \r
457                 public override Expression DoResolve (EmitContext ec)\r
458                 {\r
459                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
460 \r
461                         if (del == null)\r
462                                 return null;\r
463 \r
464                         if (del.TargetMethod == null)\r
465                                 return null;\r
466                         \r
467                         if (Arguments != null){\r
468                                 for (int i = Arguments.Count; i > 0;){\r
469                                         --i;\r
470                                         Argument a = (Argument) Arguments [i];\r
471                                         \r
472                                         if (!a.Resolve (ec))\r
473                                                 return null;\r
474                                 }\r
475                         }\r
476                         \r
477                         if (!del.VerifyApplicability (ec, Arguments, Location))\r
478                                 return null;\r
479                         \r
480                         method = del.InvokeBuilder;\r
481                         type = ((MethodInfo) method).ReturnType;\r
482                         \r
483                         eclass = ExprClass.Value;\r
484                         \r
485                         return this;\r
486                 }\r
487 \r
488                 public override void Emit (EmitContext ec)\r
489                 {\r
490                         Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
491                         Invocation.EmitCall (ec, del.TargetMethod.IsStatic, InstanceExpr, method, Arguments);\r
492                 }\r
493 \r
494         }\r
495 }\r