2004-12-11 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / parameter.cs
1 //
2 // parameter.cs: Parameter definition.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10 //
11 //
12 using System;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Collections;
16
17 namespace Mono.CSharp {
18
19         /// <summary>
20         ///   Abstract Base class for parameters of a method.
21         /// </summary>
22         public abstract class ParameterBase : Attributable {
23
24                 protected ParameterBuilder builder;
25
26                 public ParameterBase (Attributes attrs)
27                         : base (attrs)
28                 {
29                 }
30
31                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
32                 {
33                         if (a.Type == TypeManager.marshal_as_attr_type) {
34                                 UnmanagedMarshal marshal = a.GetMarshal (this);
35                                 if (marshal != null) {
36                                         builder.SetMarshal (marshal);
37                                 }
38                                         return;
39                         }
40
41                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
42                                 a.Error_InvalidSecurityParent ();
43                                 return;
44                         }
45
46                         builder.SetCustomAttribute (cb);
47                 }
48
49                 public override bool IsClsCompliaceRequired(DeclSpace ds)
50                 {
51                         return false;
52                                 }
53         }
54
55         /// <summary>
56         /// Class for applying custom attributes on the return type
57         /// </summary>
58         public class ReturnParameter: ParameterBase {
59                 public ReturnParameter (MethodBuilder mb, Location location):
60                         base (null)
61                 {
62                         try {
63                                 builder = mb.DefineParameter (0, ParameterAttributes.None, "");                 
64                         }
65                         catch (ArgumentOutOfRangeException) {
66                                 Report.Warning (-28, location, "The Microsoft .NET Runtime 1.x does not permit setting custom attributes on the return type");
67                         }
68                 }
69
70                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
71                 {
72                         // This occurs after Warning -28
73                         if (builder == null)
74                                 return;
75
76                         base.ApplyAttributeBuilder (a, cb);
77                 }
78
79                 public override AttributeTargets AttributeTargets {
80                         get {
81                                 return AttributeTargets.ReturnValue;
82                         }
83                 }
84
85                 /// <summary>
86                 /// Is never called
87                 /// </summary>
88                 public override string[] ValidAttributeTargets {
89                         get {
90                                 return null;
91                         }
92                 }
93         }
94
95         /// <summary>
96        /// Class for applying custom attributes on the implicit parameter type
97        /// of the 'set' method in properties, and the 'add' and 'remove' methods in events.
98         /// </summary>
99        public class ImplicitParameter: ParameterBase {
100                public ImplicitParameter (MethodBuilder mb):
101                         base (null)
102                 {
103                         builder = mb.DefineParameter (1, ParameterAttributes.None, "");                 
104                 }
105
106                 public override AttributeTargets AttributeTargets {
107                         get {
108                                 return AttributeTargets.Parameter;
109                         }
110                 }
111
112                 /// <summary>
113                 /// Is never called
114                 /// </summary>
115                 public override string[] ValidAttributeTargets {
116                         get {
117                                 return null;
118                         }
119         }
120         }
121
122
123         /// <summary>
124         ///   Represents a single method parameter
125         /// </summary>
126
127         //TODO: Add location member to this or base class for better error location and all methods simplification.
128         public class Parameter : ParameterBase {
129                 [Flags]
130                 public enum Modifier : byte {
131                         NONE    = 0,
132                         REF     = 1,
133                         OUT     = 2,
134                         PARAMS  = 4,
135                         // This is a flag which says that it's either REF or OUT.
136                         ISBYREF = 8,
137                         ARGLIST = 16
138                 }
139
140                 static string[] attribute_targets = new string [] { "param" };
141
142                 public Expression TypeName;
143                 public readonly Modifier ModFlags;
144                 public readonly string Name;
145                 GenericConstraints constraints;
146                 Type parameter_type;
147                 
148                 public Parameter (Expression type, string name, Modifier mod, Attributes attrs)
149                         : base (attrs)
150                 {
151                         Name = name;
152                         ModFlags = mod;
153                         TypeName = type;
154                 }
155
156                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
157                 {
158                         if (a.Type == TypeManager.param_array_type) {
159                                 Report.Error (674, a.Location, "Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead");
160                                 return;
161                         }
162                         base.ApplyAttributeBuilder (a, cb);
163                 }
164
165                 // <summary>
166                 //   Resolve is used in method definitions
167                 // </summary>
168                 public bool Resolve (EmitContext ec, Location l)
169                 {
170                         TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec);
171                         if (texpr == null)
172                                 return false;
173
174                         TypeParameterExpr tparam = texpr as TypeParameterExpr;
175                         if (tparam != null)
176                                 constraints = tparam.TypeParameter.Constraints;
177
178                         parameter_type = texpr.Type;
179
180                         if (parameter_type.IsAbstract && parameter_type.IsSealed) {
181                                 Report.Error (721, l, "'{0}': static types cannot be used as parameters", GetSignatureForError ());
182                                 return false;
183                         }
184
185                         if (parameter_type == TypeManager.void_type){
186                                 Report.Error (1536, l, "`void' parameter is not permitted");
187                                 return false;
188                         }
189
190                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0){
191                                 if (parameter_type == TypeManager.typed_reference_type ||
192                                     parameter_type == TypeManager.arg_iterator_type){
193                                         Report.Error (1601, l,
194                                                       "out or ref parameter can not be of type TypedReference or ArgIterator");
195                                         return false;
196                                 }
197                         }
198                         
199                         return parameter_type != null;
200                 }
201
202                 public Type ExternalType ()
203                 {
204                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0)
205                                 return TypeManager.GetReferenceType (parameter_type);
206                         
207                         return parameter_type;
208                 }
209
210                 public Type ParameterType {
211                         get {
212                                 return parameter_type;
213                         }
214                 }
215
216                 public GenericConstraints GenericConstraints {
217                         get {
218                                 return constraints;
219                         }
220                 }
221                 
222                 public ParameterAttributes Attributes {
223                         get {
224                                 int flags = ((int) ModFlags) & ~((int) Parameter.Modifier.ISBYREF);
225                                 switch ((Modifier) flags) {
226                                 case Modifier.NONE:
227                                         return ParameterAttributes.None;
228                                 case Modifier.REF:
229                                         return ParameterAttributes.None;
230                                 case Modifier.OUT:
231                                         return ParameterAttributes.Out;
232                                 case Modifier.PARAMS:
233                                         return 0;
234                                 }
235                                 
236                                 return ParameterAttributes.None;
237                         }
238                 }
239
240                 public static ParameterAttributes GetParameterAttributes (Modifier mod)
241                 {
242                         int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
243                         switch ((Modifier) flags) {
244                         case Modifier.NONE:
245                                 return ParameterAttributes.None;
246                         case Modifier.REF:
247                                 return ParameterAttributes.None;
248                         case Modifier.OUT:
249                                 return ParameterAttributes.Out;
250                         case Modifier.PARAMS:
251                                 return 0;
252                         }
253                                 
254                         return ParameterAttributes.None;
255                 }
256                 
257                 public override AttributeTargets AttributeTargets {
258                         get {
259                                 return AttributeTargets.Parameter;
260                         }
261                 }
262
263                 /// <summary>
264                 ///   Returns the signature for this parameter evaluating it on the
265                 ///   @tc context
266                 /// </summary>
267                 public string GetSignature (EmitContext ec, Location loc)
268                 {
269                         if (parameter_type == null){
270                                 if (!Resolve (ec, loc))
271                                         return null;
272                         }
273
274                         return ExternalType ().FullName;
275                 }
276
277                 public string GetSignatureForError ()
278                 {
279                         string typeName;
280                         if (parameter_type != null)
281                                 typeName = TypeManager.CSharpName (parameter_type);
282                         else if (TypeName.Type != null)
283                                 typeName = TypeManager.CSharpName (TypeName.Type);
284                         else
285                                 typeName = TypeName.ToString ();
286
287                         switch (ModFlags & unchecked (~Modifier.ISBYREF)) {
288                                 case Modifier.OUT:
289                                         return "out " + typeName;
290                                 case Modifier.PARAMS:
291                                         return "params " + typeName;
292                                 case Modifier.REF:
293                                         return "ref " + typeName;
294                         }
295                         return typeName;
296                 }
297
298                 public void DefineParameter (EmitContext ec, MethodBuilder mb, ConstructorBuilder cb, int index, Location loc)
299                 {
300                         ParameterAttributes par_attr = Attributes;
301                                         
302                         if (mb == null)
303                                 builder = cb.DefineParameter (index, par_attr, Name);
304                         else 
305                                 builder = mb.DefineParameter (index, par_attr, Name);
306                                         
307                         if (OptAttributes != null) {
308                                 OptAttributes.Emit (ec, this);
309         
310                                 if (par_attr == ParameterAttributes.Out){
311                                         if (OptAttributes.Contains (TypeManager.in_attribute_type, ec))
312                                                 Report.Error (36, loc,  "Can not use [In] attribute on out parameter");
313                                 }
314                         }
315                 }
316
317                 public override string[] ValidAttributeTargets {
318                         get {
319                                 return attribute_targets;
320                         }
321                 }
322         }
323
324         /// <summary>
325         ///   Represents the methods parameters
326         /// </summary>
327         public class Parameters {
328                 public Parameter [] FixedParameters;
329                 public readonly Parameter ArrayParameter;
330                 public readonly bool HasArglist;
331                 string signature;
332                 Type [] types;
333                 Location loc;
334                 
335                 static Parameters empty_parameters;
336                 
337                 public Parameters (Parameter [] fixed_parameters, Parameter array_parameter, Location l)
338                 {
339                         FixedParameters = fixed_parameters;
340                         ArrayParameter  = array_parameter;
341                         loc = l;
342                 }
343
344                 public Parameters (Parameter [] fixed_parameters, bool has_arglist, Location l)
345                 {
346                         FixedParameters = fixed_parameters;
347                         HasArglist = has_arglist;
348                         loc = l;
349                 }
350
351                 /// <summary>
352                 ///   This is used to reuse a set of empty parameters, because they
353                 ///   are common
354                 /// </summary>
355                 public static Parameters EmptyReadOnlyParameters {
356                         get {
357                                 if (empty_parameters == null)
358                                         empty_parameters = new Parameters (null, null, Location.Null);
359                         
360                                 return empty_parameters;
361                         }
362                 }
363                 
364                 public bool Empty {
365                         get {
366                                 return (FixedParameters == null) && (ArrayParameter == null);
367                         }
368                 }
369                 
370                 public void ComputeSignature (EmitContext ec)
371                 {
372                         signature = "";
373                         if (FixedParameters != null){
374                                 for (int i = 0; i < FixedParameters.Length; i++){
375                                         Parameter par = FixedParameters [i];
376                                         
377                                         signature += par.GetSignature (ec, loc);
378                                 }
379                         }
380                         //
381                         // Note: as per the spec, the `params' arguments (ArrayParameter)
382                         // are not used in the signature computation for a method
383                         //
384                 }
385
386                 void Error_DuplicateParameterName (string name)
387                 {
388                         Report.Error (
389                                 100, loc, "The parameter name `" + name + "' is a duplicate");
390                 }
391                 
392                 public bool VerifyArgs ()
393                 {
394                         int count;
395                         int i, j;
396
397                         if (FixedParameters == null)
398                                 return true;
399                         
400                         count = FixedParameters.Length;
401                         string array_par_name = ArrayParameter != null ? ArrayParameter.Name : null;
402
403                         for (i = 0; i < count; i++){
404                                 string base_name = FixedParameters [i].Name;
405                                 for (j = i + 1; j < count; j++){
406                                         if (base_name != FixedParameters [j].Name)
407                                                 continue;
408                                         Error_DuplicateParameterName (base_name);
409                                         return false;
410                                 }
411
412                                 if (base_name == array_par_name){
413                                         Error_DuplicateParameterName (base_name);
414                                         return false;
415                                 }
416                         }
417                         return true;
418                 }
419                 
420                 /// <summary>
421                 ///    Returns the signature of the Parameters evaluated in
422                 ///    the @ec EmitContext
423                 /// </summary>
424                 public string GetSignature (EmitContext ec)
425                 {
426                         if (signature == null){
427                                 VerifyArgs ();
428                                 ComputeSignature (ec);
429                         }
430                         
431                         return signature;
432                 }
433                 
434                 /// <summary>
435                 ///    Returns the paramenter information based on the name
436                 /// </summary>
437                 public Parameter GetParameterByName (string name, out int idx)
438                 {
439                         idx = 0;
440                         int i = 0;
441
442                         if (FixedParameters != null){
443                                 foreach (Parameter par in FixedParameters){
444                                         if (par.Name == name){
445                                                 idx = i;
446                                                 return par;
447                                         }
448                                         i++;
449                                 }
450                         }
451
452                         if (ArrayParameter != null){
453                                 if (name == ArrayParameter.Name){
454                                         idx = i;
455                                         return ArrayParameter;
456                                 }
457                         }
458                         
459                         return null;
460                 }
461
462                 public Parameter GetParameterByName (string name)
463                 {
464                         int idx;
465
466                         return GetParameterByName (name, out idx);
467                 }
468                 
469                 bool ComputeParameterTypes (EmitContext ec)
470                 {
471                         int extra = (ArrayParameter != null) ? 1 : 0;
472                         int i = 0;
473                         int pc;
474
475                         if (FixedParameters == null)
476                                 pc = extra;
477                         else
478                                 pc = extra + FixedParameters.Length;
479
480                         types = new Type [pc];
481                         
482                         if (!VerifyArgs ()){
483                                 FixedParameters = null;
484                                 return false;
485                         }
486
487                         bool failed = false;
488                         if (FixedParameters != null){
489                                 foreach (Parameter p in FixedParameters){
490                                         Type t = null;
491                                         
492                                         if (p.Resolve (ec, loc))
493                                                 t = p.ExternalType ();
494                                         else
495                                                 failed = true;
496
497                                         types [i] = t;
498                                         i++;
499                                 }
500                         }
501                         
502                         if (extra > 0){
503                                 if (ArrayParameter.Resolve (ec, loc))
504                                         types [i] = ArrayParameter.ExternalType ();
505                                 else 
506                                         failed = true;
507                         }
508
509                         if (failed){
510                                 types = null;
511                                 return false;
512                         }
513
514                         return true;
515                 }
516
517                 //
518                 // This variant is used by Delegates, because they need to
519                 // resolve/define names, instead of the plain LookupType
520                 //
521                 public bool ComputeAndDefineParameterTypes (EmitContext ec)
522                 {
523                         bool old_type_resolving = ec.ResolvingTypeTree;
524                         ec.ResolvingTypeTree = true;
525                         bool retval = ComputeParameterTypes (ec);
526                         ec.ResolvingTypeTree = old_type_resolving;
527                         return retval;
528                 }
529                 
530                 /// <summary>
531                 ///   Returns the argument types as an array
532                 /// </summary>
533                 static Type [] no_types = new Type [0];
534                 
535                 public Type [] GetParameterInfo (EmitContext ec)
536                 {
537                         if (types != null)
538                                 return types;
539                         
540                         if (FixedParameters == null && ArrayParameter == null)
541                                 return no_types;
542
543                         if (ComputeParameterTypes (ec) == false){
544                                 types = null;
545                                 return null;
546                         }
547
548                         return types;
549                 }
550
551                 /// <summary>
552                 ///   Returns the type of a given parameter, and stores in the `is_out'
553                 ///   boolean whether this is an out or ref parameter.
554                 ///
555                 ///   Note that the returned type will not contain any dereference in this
556                 ///   case (ie, you get "int" for a ref int instead of "int&"
557                 /// </summary>
558                 public Type GetParameterInfo (EmitContext ec, int idx, out Parameter.Modifier mod)
559                 {
560                         mod = Parameter.Modifier.NONE;
561                         
562                         if (!VerifyArgs ()){
563                                 FixedParameters = null;
564                                 return null;
565                         }
566
567                         if (FixedParameters == null && ArrayParameter == null)
568                                 return null;
569                         
570                         if (types == null)
571                                 if (ComputeParameterTypes (ec) == false)
572                                         return null;
573
574                         //
575                         // If this is a request for the variable lenght arg.
576                         //
577                         int array_idx = (FixedParameters != null ? FixedParameters.Length : 0);
578                         if (idx == array_idx)
579                                 return types [idx];
580
581                         //
582                         // Otherwise, it is a fixed parameter
583                         //
584                         Parameter p = FixedParameters [idx];
585                         mod = p.ModFlags;
586
587                         if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
588                                 mod |= Parameter.Modifier.ISBYREF;
589
590                         return p.ParameterType;
591                 }
592
593                 public CallingConventions GetCallingConvention ()
594                 {
595                         if (HasArglist)
596                                 return CallingConventions.VarArgs;
597                         else
598                         return CallingConventions.Standard;
599                 }
600
601                 //
602                 // The method's attributes are passed in because we need to extract
603                 // the "return:" attribute from there to apply on the return type
604                 //
605                 public void LabelParameters (EmitContext ec,
606                         MethodBase builder,
607                         Location loc) {
608                         //
609                         // Define each type attribute (in/out/ref) and
610                         // the argument names.
611                         //
612                         int i = 0;
613                         
614                         MethodBuilder mb = builder as MethodBuilder;
615                         ConstructorBuilder cb = builder as ConstructorBuilder;
616
617                         if (FixedParameters != null) {
618                                 for (i = 0; i < FixedParameters.Length; i++) {
619                                         FixedParameters [i].DefineParameter (ec, mb, cb, i + 1, loc);
620                                 }
621                         }
622
623                         if (ArrayParameter != null){
624                                 ParameterBuilder pb;
625                                 Parameter array_param = ArrayParameter;
626
627                                 if (mb == null)
628                                         pb = cb.DefineParameter (
629                                                 i + 1, array_param.Attributes,
630                                                 array_param.Name);
631                                 else
632                                         pb = mb.DefineParameter (
633                                                 i + 1, array_param.Attributes,
634                                                 array_param.Name);
635                                         
636                                 CustomAttributeBuilder a = new CustomAttributeBuilder (
637                                         TypeManager.cons_param_array_attribute, new object [0]);
638                                 
639                                 pb.SetCustomAttribute (a);
640                         }
641                 }
642         }
643 }