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