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