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