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