2006-08-15 Marek Safar <marek.safar@seznam.cz>
[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                         // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0
258                         if (a.Type == TypeManager.default_parameter_value_attribute_type) {
259                                 object val = a.GetParameterDefaultValue ();
260                                 if (val != null) {
261                                         Type t = val.GetType ();
262                                         if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
263                                                 if (parameter_type == TypeManager.object_type) {
264                                                         if (!t.IsArray)
265                                                                 t = TypeManager.type_type;
266
267                                                         Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
268                                                                 TypeManager.CSharpName (t));
269                                                 } else {
270                                                         Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
271                                                                 TypeManager.CSharpName (parameter_type)); ;
272                                                 }
273                                                 return;
274                                         }
275                                 }
276
277                                 if (parameter_type == TypeManager.object_type ||
278                                     (val == null && !TypeManager.IsValueType (parameter_type)) ||
279                                     (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
280                                         builder.SetConstant (val);
281                                 else
282                                         Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
283                                 return;
284                         }
285
286                         base.ApplyAttributeBuilder (a, cb);
287                 }
288
289                 public override IResolveContext ResolveContext {
290                         get {
291                                 return resolve_context;
292                         }
293                 }
294
295                 // <summary>
296                 //   Resolve is used in method definitions
297                 // </summary>
298                 public virtual bool Resolve (IResolveContext ec)
299                 {
300                         if (parameter_type != null)
301                                 return true;
302
303                         this.resolve_context = ec;
304
305                         TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
306                         if (texpr == null)
307                                 return false;
308
309                         parameter_type = texpr.Type;
310                         
311                         if (parameter_type.IsAbstract && parameter_type.IsSealed) {
312                                 Report.Error (721, Location, "`{0}': static types cannot be used as parameters", GetSignatureForError ());
313                                 return false;
314                         }
315
316                         if (parameter_type == TypeManager.void_type){
317                                 Report.Error (1536, Location, "Invalid parameter type 'void'");
318                                 return false;
319                         }
320
321                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0){
322                                 if (parameter_type == TypeManager.typed_reference_type ||
323                                     parameter_type == TypeManager.arg_iterator_type){
324                                         Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
325                                                 GetSignatureForError ());
326                                         return false;
327                                 }
328                         }
329                         
330                         return true;
331                 }
332
333                 public Type ExternalType ()
334                 {
335                         if ((ModFlags & Parameter.Modifier.ISBYREF) != 0)
336                                 return TypeManager.GetReferenceType (parameter_type);
337                         
338                         return parameter_type;
339                 }
340
341                 public Type ParameterType {
342                         get {
343                                 return parameter_type;
344                         }
345                 }
346                 
347                 public ParameterAttributes Attributes {
348                         get {
349                                 switch (ModFlags) {
350                                 case Modifier.NONE:
351                                         return ParameterAttributes.None;
352                                 case Modifier.REF:
353                                         return ParameterAttributes.None;
354                                 case Modifier.OUT:
355                                         return ParameterAttributes.Out;
356                                 case Modifier.PARAMS:
357                                         return 0;
358                                 }
359                                 
360                                 return ParameterAttributes.None;
361                         }
362                 }
363                 
364                 public override AttributeTargets AttributeTargets {
365                         get {
366                                 return AttributeTargets.Parameter;
367                         }
368                 }
369
370                 public virtual string GetSignatureForError ()
371                 {
372                         string type_name;
373                         if (parameter_type != null)
374                                 type_name = TypeManager.CSharpName (parameter_type);
375                         else
376                                 type_name = TypeName.GetSignatureForError ();
377
378                         string mod = GetModifierSignature (ModFlags);
379                         if (mod.Length > 0)
380                                 return String.Concat (mod, ' ', type_name);
381
382                         return type_name;
383                 }
384
385                 public static string GetModifierSignature (Modifier mod)
386                 {
387                         switch (mod) {
388                                 case Modifier.OUT:
389                                         return "out";
390                                 case Modifier.PARAMS:
391                                         return "params";
392                                 case Modifier.REF:
393                                         return "ref";
394                                 case Modifier.ARGLIST:
395                                         return "__arglist";
396                                 default:
397                                         return "";
398                         }
399                 }
400
401                 public void IsClsCompliant ()
402                 {
403                         if (AttributeTester.IsClsCompliant (ExternalType ()))
404                                 return;
405
406                         Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
407                 }
408
409                 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
410                 {
411                         if (mb == null)
412                                 builder = cb.DefineParameter (index, Attributes, Name);
413                         else 
414                                 builder = mb.DefineParameter (index, Attributes, Name);
415                 
416                         if (OptAttributes != null)
417                                 OptAttributes.Emit ();
418                 }
419
420                 public override string[] ValidAttributeTargets {
421                         get {
422                                 return attribute_targets;
423                         }
424                 }
425         }
426
427         /// <summary>
428         ///   Represents the methods parameters
429         /// </summary>
430         public class Parameters : ParameterData {
431                 // Null object pattern
432                 public Parameter [] FixedParameters;
433                 public readonly bool HasArglist;
434                 Type [] types;
435                 int count;
436
437                 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
438                 static readonly Parameter ArgList = new ArglistParameter ();
439
440                 private Parameters ()
441                 {
442                         FixedParameters = new Parameter[0];
443                         types = new Type [0];
444                 }
445
446                 public Parameters (Parameter[] parameters, Type[] types)
447                 {
448                         FixedParameters = parameters;
449                         this.types = types;
450                         count = types.Length;
451                 }
452                 
453                 public Parameters (Parameter[] parameters)
454                 {
455                         if (parameters == null)
456                                 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
457
458                         FixedParameters = parameters;
459                         count = parameters.Length;
460                 }
461
462                 public Parameters (Parameter[] parameters, bool has_arglist):
463                         this (parameters)
464                 {
465                         HasArglist = has_arglist;
466                 }
467
468                 /// <summary>
469                 /// Use this method when you merge compiler generated argument with user arguments
470                 /// </summary>
471                 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
472                 {
473                         Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
474                         Type[] all_types = new Type[all_params.Length];
475                         userParams.FixedParameters.CopyTo(all_params, 0);
476                         userParams.Types.CopyTo (all_types, 0);
477
478                         int last_filled = userParams.Count;
479                         foreach (Parameter p in compilerParams) {
480                                 for (int i = 0; i < last_filled; ++i) {
481                                         while (p.Name == all_params [i].Name) {
482                                                 p.Name = '_' + p.Name;
483                                         }
484                                 }
485                                 all_params [last_filled] = p;
486                                 all_types [last_filled] = p.ParameterType;
487                                 ++last_filled;
488                         }
489                         
490                         return new Parameters (all_params, all_types);
491                 }
492
493                 public bool Empty {
494                         get {
495                                 return count == 0;
496                         }
497                 }
498
499                 public int Count {
500                         get {
501                                 return HasArglist ? count + 1 : count;
502                         }
503                 }
504
505                 bool VerifyArgs ()
506                 {
507                         if (count < 2)
508                                 return true;
509
510                         for (int i = 0; i < count; i++){
511                                 string base_name = FixedParameters [i].Name;
512                                 for (int j = i + 1; j < count; j++){
513                                         if (base_name != FixedParameters [j].Name)
514                                                 continue;
515
516                                         Report.Error (100, FixedParameters [i].Location,
517                                                 "The parameter name `{0}' is a duplicate", base_name);
518                                         return false;
519                                 }
520                         }
521                         return true;
522                 }
523                 
524                 
525                 /// <summary>
526                 ///    Returns the paramenter information based on the name
527                 /// </summary>
528                 public Parameter GetParameterByName (string name, out int idx)
529                 {
530                         idx = 0;
531
532                         if (count == 0)
533                                 return null;
534
535                         int i = 0;
536
537                         foreach (Parameter par in FixedParameters){
538                                 if (par.Name == name){
539                                         idx = i;
540                                         return par;
541                                 }
542                                 i++;
543                         }
544                         return null;
545                 }
546
547                 public Parameter GetParameterByName (string name)
548                 {
549                         int idx;
550
551                         return GetParameterByName (name, out idx);
552                 }
553                 
554                 public bool Resolve (IResolveContext ec)
555                 {
556                         if (types != null)
557                                 return true;
558
559                         types = new Type [count];
560                         
561                         if (!VerifyArgs ())
562                                 return false;
563
564                         bool ok = true;
565                         Parameter p;
566                         for (int i = 0; i < FixedParameters.Length; ++i) {
567                                 p = FixedParameters [i];
568                                 if (!p.Resolve (ec)) {
569                                         ok = false;
570                                         continue;
571                                 }
572                                 types [i] = p.ExternalType ();
573                         }
574
575                         return ok;
576                 }
577
578                 public CallingConventions CallingConvention
579                 {
580                         get {
581                                 if (HasArglist)
582                                         return CallingConventions.VarArgs;
583                                 else
584                                         return CallingConventions.Standard;
585                         }
586                 }
587
588                 // Define each type attribute (in/out/ref) and
589                 // the argument names.
590                 public void ApplyAttributes (MethodBase builder)
591                 {
592                         if (count == 0)
593                                 return;
594
595                         MethodBuilder mb = builder as MethodBuilder;
596                         ConstructorBuilder cb = builder as ConstructorBuilder;
597
598                         for (int i = 0; i < FixedParameters.Length; i++) {
599                                 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
600                         }
601                 }
602
603                 public void VerifyClsCompliance ()
604                 {
605                         foreach (Parameter p in FixedParameters)
606                                 p.IsClsCompliant ();
607                 }
608
609                 public string GetSignatureForError ()
610                 {
611                         StringBuilder sb = new StringBuilder ("(");
612                         if (count > 0) {
613                                 for (int i = 0; i < FixedParameters.Length; ++i) {
614                                         sb.Append (FixedParameters[i].GetSignatureForError ());
615                                         if (i < FixedParameters.Length - 1)
616                                                 sb.Append (", ");
617                                 }
618                         }
619
620                         if (HasArglist) {
621                                 if (sb.Length > 1)
622                                         sb.Append (", ");
623                                 sb.Append ("__arglist");
624                         }
625
626                         sb.Append (')');
627                         return sb.ToString ();
628                 }
629
630                 public Type[] Types {
631                         get {
632                                 return types;
633                         }
634                 }
635
636                 Parameter this [int pos]
637                 {
638                         get {
639                                 if (pos >= count && (HasArglist || HasParams)) {
640                                         if (HasArglist && (pos == 0 || pos >= count))
641                                                 return ArgList;
642                                         pos = count - 1;
643                                 }
644
645                                 return FixedParameters [pos];
646                         }
647                 }
648
649                 #region ParameterData Members
650
651                 public Type ParameterType (int pos)
652                 {
653                         return this [pos].ExternalType ();
654                 }
655
656                 public bool HasParams {
657                         get {
658                                 if (count == 0)
659                                         return false;
660
661                                 return FixedParameters [count - 1] is ParamsParameter;
662                         }
663                 }
664
665                 public string ParameterName (int pos)
666                 {
667                         return this [pos].Name;
668                 }
669
670                 public string ParameterDesc (int pos)
671                 {
672                         return this [pos].GetSignatureForError ();
673                 }
674
675                 public Parameter.Modifier ParameterModifier (int pos)
676                 {
677                         return this [pos].ModFlags;
678                 }
679
680                 #endregion
681         }
682 }