2006-03-13 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / mcs / parameter.cs
1 //
2 // parameter.cs: Parameter definition.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Marek Safar (marek.safar@seznam.cz)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11 //
12 //
13 using System;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
17 using System.Text;
18
19 namespace Mono.CSharp {
20
21         /// <summary>
22         ///   Abstract Base class for parameters of a method.
23         /// </summary>
24         public abstract class ParameterBase : Attributable {
25
26                 protected ParameterBuilder builder;
27
28                 protected ParameterBase (Attributes attrs)
29                         : base (attrs)
30                 {
31                 }
32
33                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
34                 {
35                         if (a.Type == TypeManager.marshal_as_attr_type) {
36                                 UnmanagedMarshal marshal = a.GetMarshal (this);
37                                 if (marshal != null) {
38                                         builder.SetMarshal (marshal);
39                                 }
40                                 return;
41                         }
42
43                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
44                                 a.Error_InvalidSecurityParent ();
45                                 return;
46                         }
47
48                         builder.SetCustomAttribute (cb);
49                 }
50
51                 public override bool IsClsComplianceRequired()
52                 {
53                         return false;
54                 }
55         }
56
57         /// <summary>
58         /// Class for applying custom attributes on the return type
59         /// </summary>
60         public class ReturnParameter : ParameterBase {
61                 public ReturnParameter (MethodBuilder mb, Location location):
62                         base (null)
63                 {
64                         try {
65                                 builder = mb.DefineParameter (0, ParameterAttributes.None, "");                 
66                         }
67                         catch (ArgumentOutOfRangeException) {
68                                 Report.RuntimeMissingSupport (location, "custom attributes on the return type");
69                         }
70                 }
71
72                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
73                 {
74                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
75                                 Report.Warning (3023, 1, a.Location, "CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead");
76                         }
77
78                         // This occurs after Warning -28
79                         if (builder == null)
80                                 return;
81
82                         base.ApplyAttributeBuilder (a, cb);
83                 }
84
85                 public override AttributeTargets AttributeTargets {
86                         get {
87                                 return AttributeTargets.ReturnValue;
88                         }
89                 }
90
91                 public override IResolveContext ResolveContext {
92                         get {
93                                 throw new NotSupportedException ();
94                         }
95                 }
96
97                 /// <summary>
98                 /// Is never called
99                 /// </summary>
100                 public override string[] ValidAttributeTargets {
101                         get {
102                                 return null;
103                         }
104                 }
105         }
106
107         /// <summary>
108         /// Class for applying custom attributes on the implicit parameter type
109         /// of the 'set' method in properties, and the 'add' and 'remove' methods in events.
110         /// </summary>
111         /// 
112         // TODO: should use more code from Parameter.ApplyAttributeBuilder
113         public class ImplicitParameter : ParameterBase {
114                 public ImplicitParameter (MethodBuilder mb):
115                         base (null)
116                 {
117                         builder = mb.DefineParameter (1, ParameterAttributes.None, "");                 
118                 }
119
120                 public override AttributeTargets AttributeTargets {
121                         get {
122                                 return AttributeTargets.Parameter;
123                         }
124                 }
125
126                 public override IResolveContext ResolveContext {
127                         get {
128                                 throw new NotSupportedException ();
129                         }
130                 }
131
132                 /// <summary>
133                 /// Is never called
134                 /// </summary>
135                 public override string[] ValidAttributeTargets {
136                         get {
137                                 return null;
138                         }
139                 }
140         }
141
142         public class ParamsParameter : Parameter {
143                 public ParamsParameter (Expression type, string name, Attributes attrs, Location loc):
144                         base (type, name, Parameter.Modifier.PARAMS, attrs, loc)
145                 {
146                 }
147
148                 public override bool Resolve (IResolveContext ec)
149                 {
150                         if (!base.Resolve (ec))
151                                 return false;
152
153                         if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
154                                 Report.Error (225, Location, "The params parameter must be a single dimensional array");
155                                 return false;
156                         }
157                         return true;
158                 }
159
160                 public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
161                 {
162                         base.ApplyAttributes (mb, cb, index);
163
164                         CustomAttributeBuilder a = new CustomAttributeBuilder (
165                                 TypeManager.ConsParamArrayAttribute, new object [0]);
166                                 
167                         builder.SetCustomAttribute (a);
168                 }
169         }
170
171         public class ArglistParameter : Parameter {
172                 // Doesn't have proper type because it's never choosed for better conversion
173                 public ArglistParameter () :
174                         base (typeof (ArglistParameter), "", Parameter.Modifier.ARGLIST, null, Location.Null)
175                 {
176                 }
177
178                 public override bool Resolve (IResolveContext ec)
179                 {
180                         return true;
181                 }
182
183                 public override string GetSignatureForError ()
184                 {
185                         return "__arglist";
186                 }
187         }
188
189         /// <summary>
190         ///   Represents a single method parameter
191         /// </summary>
192         public class Parameter : ParameterBase {
193                 [Flags]
194                 public enum Modifier : byte {
195                         NONE    = 0,
196                         REF     = REFMASK | ISBYREF,
197                         OUT     = OUTMASK | ISBYREF,
198                         PARAMS  = 4,
199                         // This is a flag which says that it's either REF or OUT.
200                         ISBYREF = 8,
201                         ARGLIST = 16,
202                         REFMASK = 32,
203                         OUTMASK = 64
204                 }
205
206                 static string[] attribute_targets = new string [] { "param" };
207
208                 public Expression TypeName;
209                 public readonly Modifier ModFlags;
210                 public string Name;
211                 protected Type parameter_type;
212                 public readonly Location Location;
213
214                 IResolveContext resolve_context;
215                 
216                 public Parameter (Expression type, string name, Modifier mod, Attributes attrs, Location loc)
217                         : base (attrs)
218                 {
219                         Name = name;
220                         ModFlags = mod;
221                         TypeName = type;
222                         Location = loc;
223                 }
224
225                 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
226                         : base (attrs)
227                 {
228                         Name = name;
229                         ModFlags = mod;
230                         parameter_type = type;
231                         Location = loc;
232                 }
233
234                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
235                 {
236                         if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
237                                 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
238                                 return;
239                         }
240
241                         if (a.Type == TypeManager.param_array_type) {
242                                 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
243                                 return;
244                         }
245
246                         if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
247                             !OptAttributes.Contains (TypeManager.in_attribute_type)) {
248                                 Report.Error (662, a.Location,
249                                         "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
250                                 return;
251                         }
252
253                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
254                                 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
255                         }
256
257                         base.ApplyAttributeBuilder (a, cb);
258                 }
259
260                 public override IResolveContext ResolveContext {
261                         get {
262                                 return resolve_context;
263                         }
264                 }
265
266                 // <summary>
267                 //   Resolve is used in method definitions
268                 // </summary>
269                 public virtual bool Resolve (IResolveContext ec)
270                 {
271                         if (parameter_type != null)
272                                 return true;
273
274                         this.resolve_context = ec;
275
276                         TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
277                         if (texpr == null)
278                                 return false;
279
280                         parameter_type = texpr.Type;
281                         
282                         if (parameter_type.IsAbstract && parameter_type.IsSealed) {
283                                 Report.Error (721, Location, "`{0}': static types cannot be used as parameters", GetSignatureForError ());
284                                 return false;
285                         }
286
287                         if (parameter_type == TypeManager.void_type){
288                                 Report.Error (1536, Location, "Invalid parameter type 'void'");
289                                 return false;
290                         }
291
292                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0){
293                                 if (parameter_type == TypeManager.typed_reference_type ||
294                                     parameter_type == TypeManager.arg_iterator_type){
295                                         Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
296                                                 GetSignatureForError ());
297                                         return false;
298                                 }
299                         }
300                         
301                         return true;
302                 }
303
304                 public Type ExternalType ()
305                 {
306                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0)
307                                 return TypeManager.GetReferenceType (parameter_type);
308                         
309                         return parameter_type;
310                 }
311
312                 public Type ParameterType {
313                         get {
314                                 return parameter_type;
315                         }
316                 }
317                 
318                 public ParameterAttributes Attributes {
319                         get {
320                                 switch (ModFlags) {
321                                 case Modifier.NONE:
322                                         return ParameterAttributes.None;
323                                 case Modifier.REF:
324                                         return ParameterAttributes.None;
325                                 case Modifier.OUT:
326                                         return ParameterAttributes.Out;
327                                 case Modifier.PARAMS:
328                                         return 0;
329                                 }
330                                 
331                                 return ParameterAttributes.None;
332                         }
333                 }
334                 
335                 public override AttributeTargets AttributeTargets {
336                         get {
337                                 return AttributeTargets.Parameter;
338                         }
339                 }
340
341                 public virtual string GetSignatureForError ()
342                 {
343                         string type_name;
344                         if (parameter_type != null)
345                                 type_name = TypeManager.CSharpName (parameter_type);
346                         else
347                                 type_name = TypeName.GetSignatureForError ();
348
349                         string mod = GetModifierSignature (ModFlags);
350                         if (mod.Length > 0)
351                                 return String.Concat (mod, ' ', type_name);
352
353                         return type_name;
354                 }
355
356                 public static string GetModifierSignature (Modifier mod)
357                 {
358                         switch (mod) {
359                                 case Modifier.OUT:
360                                         return "out";
361                                 case Modifier.PARAMS:
362                                         return "params";
363                                 case Modifier.REF:
364                                         return "ref";
365                                 case Modifier.ARGLIST:
366                                         return "__arglist";
367                                 default:
368                                         return "";
369                         }
370                 }
371
372                 public void IsClsCompliant ()
373                 {
374                         if (AttributeTester.IsClsCompliant (ExternalType ()))
375                                 return;
376
377                         Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
378                 }
379
380                 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
381                 {
382                         if (mb == null)
383                                 builder = cb.DefineParameter (index, Attributes, Name);
384                         else 
385                                 builder = mb.DefineParameter (index, Attributes, Name);
386                 
387                         if (OptAttributes != null)
388                                 OptAttributes.Emit ();
389                 }
390
391                 public override string[] ValidAttributeTargets {
392                         get {
393                                 return attribute_targets;
394                         }
395                 }
396         }
397
398         /// <summary>
399         ///   Represents the methods parameters
400         /// </summary>
401         public class Parameters : ParameterData {
402                 // Null object pattern
403                 public Parameter [] FixedParameters;
404                 public readonly bool HasArglist;
405                 Type [] types;
406                 int count;
407
408                 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
409                 static readonly Parameter ArgList = new ArglistParameter ();
410
411                 private Parameters ()
412                 {
413                         FixedParameters = new Parameter[0];
414                         types = new Type [0];
415                 }
416
417                 public Parameters (Parameter[] parameters, Type[] types)
418                 {
419                         FixedParameters = parameters;
420                         this.types = types;
421                         count = types.Length;
422                 }
423                 
424                 public Parameters (Parameter[] parameters)
425                 {
426                         if (parameters == null)
427                                 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
428
429                         FixedParameters = parameters;
430                         count = parameters.Length;
431                 }
432
433                 public Parameters (Parameter[] parameters, bool has_arglist):
434                         this (parameters)
435                 {
436                         HasArglist = has_arglist;
437                 }
438
439                 /// <summary>
440                 /// Use this method when you merge compiler generated argument with user arguments
441                 /// </summary>
442                 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
443                 {
444                         Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
445                         Type[] all_types = new Type[all_params.Length];
446                         userParams.FixedParameters.CopyTo(all_params, 0);
447                         userParams.Types.CopyTo (all_types, 0);
448
449                         int last_filled = userParams.Count;
450                         foreach (Parameter p in compilerParams) {
451                                 for (int i = 0; i < last_filled; ++i) {
452                                         while (p.Name == all_params [i].Name) {
453                                                 p.Name = '_' + p.Name;
454                                         }
455                                 }
456                                 all_params [last_filled] = p;
457                                 all_types [last_filled] = p.ParameterType;
458                                 ++last_filled;
459                         }
460                         
461                         return new Parameters (all_params, all_types);
462                 }
463
464                 public bool Empty {
465                         get {
466                                 return count == 0;
467                         }
468                 }
469
470                 public int Count {
471                         get {
472                                 return HasArglist ? count + 1 : count;
473                         }
474                 }
475
476                 bool VerifyArgs ()
477                 {
478                         if (count < 2)
479                                 return true;
480
481                         for (int i = 0; i < count; i++){
482                                 string base_name = FixedParameters [i].Name;
483                                 for (int j = i + 1; j < count; j++){
484                                         if (base_name != FixedParameters [j].Name)
485                                                 continue;
486
487                                         Report.Error (100, FixedParameters [i].Location,
488                                                 "The parameter name `{0}' is a duplicate", base_name);
489                                         return false;
490                                 }
491                         }
492                         return true;
493                 }
494                 
495                 
496                 /// <summary>
497                 ///    Returns the paramenter information based on the name
498                 /// </summary>
499                 public Parameter GetParameterByName (string name, out int idx)
500                 {
501                         idx = 0;
502
503                         if (count == 0)
504                                 return null;
505
506                         int i = 0;
507
508                         foreach (Parameter par in FixedParameters){
509                                 if (par.Name == name){
510                                         idx = i;
511                                         return par;
512                                 }
513                                 i++;
514                         }
515                         return null;
516                 }
517
518                 public Parameter GetParameterByName (string name)
519                 {
520                         int idx;
521
522                         return GetParameterByName (name, out idx);
523                 }
524                 
525                 public bool Resolve (IResolveContext ec)
526                 {
527                         if (types != null)
528                                 return true;
529
530                         types = new Type [count];
531                         
532                         if (!VerifyArgs ())
533                                 return false;
534
535                         bool ok = true;
536                         Parameter p;
537                         for (int i = 0; i < FixedParameters.Length; ++i) {
538                                 p = FixedParameters [i];
539                                 if (!p.Resolve (ec)) {
540                                         ok = false;
541                                         continue;
542                                 }
543                                 types [i] = p.ExternalType ();
544                         }
545
546                         return ok;
547                 }
548
549                 public CallingConventions CallingConvention
550                 {
551                         get {
552                                 if (HasArglist)
553                                         return CallingConventions.VarArgs;
554                                 else
555                                         return CallingConventions.Standard;
556                         }
557                 }
558
559                 // Define each type attribute (in/out/ref) and
560                 // the argument names.
561                 public void ApplyAttributes (MethodBase builder)
562                 {
563                         if (count == 0)
564                                 return;
565
566                         MethodBuilder mb = builder as MethodBuilder;
567                         ConstructorBuilder cb = builder as ConstructorBuilder;
568
569                         for (int i = 0; i < FixedParameters.Length; i++) {
570                                 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
571                         }
572                 }
573
574                 public void VerifyClsCompliance ()
575                 {
576                         foreach (Parameter p in FixedParameters)
577                                 p.IsClsCompliant ();
578                 }
579
580                 public string GetSignatureForError ()
581                 {
582                         StringBuilder sb = new StringBuilder ("(");
583                         if (count > 0) {
584                                 for (int i = 0; i < FixedParameters.Length; ++i) {
585                                         sb.Append (FixedParameters[i].GetSignatureForError ());
586                                         if (i < FixedParameters.Length - 1)
587                                                 sb.Append (", ");
588                                 }
589                         }
590
591                         if (HasArglist) {
592                                 if (HasArglist) {
593                                         if (sb.Length > 1)
594                                                 sb.Append (", ");
595                                         sb.Append ("__arglist");
596                                 }
597                         }
598
599                         sb.Append (')');
600                         return sb.ToString ();
601                 }
602
603                 public Type[] Types {
604                         get {
605                                 return types;
606                         }
607                 }
608
609                 Parameter this [int pos]
610                 {
611                         get {
612                                 if (pos >= count && (HasArglist || HasParams)) {
613                                         if (HasArglist && (pos == 0 || pos >= count))
614                                                 return ArgList;
615                                         pos = count - 1;
616                                 }
617
618                                 return FixedParameters [pos];
619                         }
620                 }
621
622                 #region ParameterData Members
623
624                 public Type ParameterType (int pos)
625                 {
626                         return this [pos].ExternalType ();
627                 }
628
629                 public bool HasParams {
630                         get {
631                                 if (count == 0)
632                                         return false;
633
634                                 return FixedParameters [count - 1] is ParamsParameter;
635                         }
636                 }
637
638                 public string ParameterName (int pos)
639                 {
640                         return this [pos].Name;
641                 }
642
643                 public string ParameterDesc (int pos)
644                 {
645                         return this [pos].GetSignatureForError ();
646                 }
647
648                 public Parameter.Modifier ParameterModifier (int pos)
649                 {
650                         return this [pos].ModFlags;
651                 }
652
653                 #endregion
654         }
655 }