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