c707298220cecc94cd1565dccac0648040c715dd
[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 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc. 
11 // Copyright 2011 Xamarin Inc
12 //
13 //
14 using System;
15 using System.Text;
16
17 #if STATIC
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
25 #endif
26
27 namespace Mono.CSharp {
28
29         /// <summary>
30         ///   Abstract Base class for parameters of a method.
31         /// </summary>
32         public abstract class ParameterBase : Attributable
33         {
34                 protected ParameterBuilder builder;
35
36                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
37                 {
38 #if false
39                         if (a.Type == pa.MarshalAs) {
40                                 UnmanagedMarshal marshal = a.GetMarshal (this);
41                                 if (marshal != null) {
42                                         builder.SetMarshal (marshal);
43                                 }
44                                 return;
45                         }
46 #endif
47                         if (a.HasSecurityAttribute) {
48                                 a.Error_InvalidSecurityParent ();
49                                 return;
50                         }
51
52                         if (a.Type == pa.Dynamic) {
53                                 a.Error_MisusedDynamicAttribute ();
54                                 return;
55                         }
56
57                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
58                 }
59
60                 public ParameterBuilder Builder {
61                         get {
62                                 return builder;
63                         }
64                 }
65
66                 public override bool IsClsComplianceRequired()
67                 {
68                         return false;
69                 }
70         }
71
72         /// <summary>
73         /// Class for applying custom attributes on the return type
74         /// </summary>
75         public class ReturnParameter : ParameterBase
76         {
77                 MemberCore method;
78
79                 // TODO: merge method and mb
80                 public ReturnParameter (MemberCore method, MethodBuilder mb, Location location)
81                 {
82                         this.method = method;
83                         try {
84                                 builder = mb.DefineParameter (0, ParameterAttributes.None, "");                 
85                         }
86                         catch (ArgumentOutOfRangeException) {
87                                 method.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type");
88                         }
89                 }
90
91                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
92                 {
93                         if (a.Type == pa.CLSCompliant) {
94                                 method.Compiler.Report.Warning (3023, 1, a.Location,
95                                         "CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead");
96                         }
97
98                         // This occurs after Warning -28
99                         if (builder == null)
100                                 return;
101
102                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
103                 }
104
105                 public override AttributeTargets AttributeTargets {
106                         get {
107                                 return AttributeTargets.ReturnValue;
108                         }
109                 }
110
111                 /// <summary>
112                 /// Is never called
113                 /// </summary>
114                 public override string[] ValidAttributeTargets {
115                         get {
116                                 return null;
117                         }
118                 }
119         }
120
121         public class ImplicitLambdaParameter : Parameter
122         {
123                 public ImplicitLambdaParameter (string name, Location loc)
124                         : base (null, name, Modifier.NONE, null, loc)
125                 {
126                 }
127
128                 public override TypeSpec Resolve (IMemberContext ec, int index)
129                 {
130                         if (parameter_type == null)
131                                 throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set",
132                                         Name);
133
134                         base.idx = index;
135                         return parameter_type;
136                 }
137
138                 public void SetParameterType (TypeSpec type)
139                 {
140                         parameter_type = type;
141                 }
142         }
143
144         public class ParamsParameter : Parameter {
145                 public ParamsParameter (FullNamedExpression type, string name, Attributes attrs, Location loc):
146                         base (type, name, Parameter.Modifier.PARAMS, attrs, loc)
147                 {
148                 }
149
150                 public override TypeSpec Resolve (IMemberContext ec, int index)
151                 {
152                         if (base.Resolve (ec, index) == null)
153                                 return null;
154
155                         var ac = parameter_type as ArrayContainer;
156                         if (ac == null || ac.Rank != 1) {
157                                 ec.Module.Compiler.Report.Error (225, Location, "The params parameter must be a single dimensional array");
158                                 return null;
159                         }
160
161                         return parameter_type;
162                 }
163
164                 public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
165                 {
166                         base.ApplyAttributes (mb, cb, index, pa);
167                         pa.ParamArray.EmitAttribute (builder);
168                 }
169         }
170
171         public class ArglistParameter : Parameter {
172                 // Doesn't have proper type because it's never chosen for better conversion
173                 public ArglistParameter (Location loc) :
174                         base (null, String.Empty, Parameter.Modifier.NONE, null, loc)
175                 {
176                         parameter_type = InternalType.Arglist;
177                 }
178
179                 public override void  ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
180                 {
181                         // Nothing to do
182                 }
183
184                 public override bool CheckAccessibility (InterfaceMemberBase member)
185                 {
186                         return true;
187                 }
188
189                 public override TypeSpec Resolve (IMemberContext ec, int index)
190                 {
191                         return parameter_type;
192                 }
193         }
194
195         public interface IParameterData
196         {
197                 Expression DefaultValue { get; }
198                 bool HasExtensionMethodModifier { get; }
199                 bool HasDefaultValue { get; }
200                 Parameter.Modifier ModFlags { get; }
201                 string Name { get; }
202         }
203
204         //
205         // Parameter information created by parser
206         //
207         public class Parameter : ParameterBase, IParameterData, ILocalVariable // TODO: INamedBlockVariable
208         {
209                 [Flags]
210                 public enum Modifier : byte {
211                         NONE    = 0,
212                         REF     = REFMASK | ISBYREF,
213                         OUT     = OUTMASK | ISBYREF,
214                         PARAMS  = 4,
215                         // This is a flag which says that it's either REF or OUT.
216                         ISBYREF = 8,
217                         REFMASK = 32,
218                         OUTMASK = 64,
219                         SignatureMask = REFMASK | OUTMASK,
220                         This    = 128
221                 }
222
223                 static readonly string[] attribute_targets = new string[] { "param" };
224
225                 FullNamedExpression texpr;
226                 readonly Modifier modFlags;
227                 string name;
228                 Expression default_expr;
229                 protected TypeSpec parameter_type;
230                 readonly Location loc;
231                 protected int idx;
232                 public bool HasAddressTaken;
233
234                 TemporaryVariableReference expr_tree_variable;
235
236                 HoistedVariable hoisted_variant;
237
238                 public Parameter (FullNamedExpression type, string name, Modifier mod, Attributes attrs, Location loc)
239                 {
240                         this.name = name;
241                         modFlags = mod;
242                         this.loc = loc;
243                         texpr = type;
244
245                         // Only assign, attributes will be attached during resolve
246                         base.attributes = attrs;
247                 }
248
249                 #region Properties
250
251                 public DefaultParameterValueExpression DefaultValue {
252                         get {
253                                 return default_expr as DefaultParameterValueExpression;
254                         }
255                         set {
256                                 default_expr = value;
257                         }
258                 }
259
260                 Expression IParameterData.DefaultValue {
261                         get {
262                                 var expr = default_expr as DefaultParameterValueExpression;
263                                 return expr == null ? default_expr : expr.Child;
264                         }
265                 }
266
267                 bool HasOptionalExpression {
268                         get {
269                                 return default_expr is DefaultParameterValueExpression;
270                         }
271                 }
272
273                 public Location Location {
274                         get {
275                                 return loc;
276                         }
277                 }
278
279                 public TypeSpec Type {
280                         get {
281                                 return parameter_type;
282                         }
283                         set {
284                                 parameter_type = value;
285                         }
286                 }
287
288                 public FullNamedExpression TypeExpression  {
289                         get {
290                                 return texpr;
291                         }
292                 }
293
294                 public override string[] ValidAttributeTargets {
295                         get {
296                                 return attribute_targets;
297                         }
298                 }
299
300                 #endregion
301
302                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
303                 {
304                         if (a.Type == pa.In && ModFlags == Modifier.OUT) {
305                                 a.Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
306                                 return;
307                         }
308
309                         if (a.Type == pa.ParamArray) {
310                                 a.Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
311                                 return;
312                         }
313
314                         if (a.Type == pa.Out && (ModFlags & Modifier.REF) == Modifier.REF &&
315                             !OptAttributes.Contains (pa.In)) {
316                                 a.Report.Error (662, a.Location,
317                                         "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
318                                 return;
319                         }
320
321                         if (a.Type == pa.CLSCompliant) {
322                                 a.Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
323                         }
324
325                         if (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter) {
326                                 if (HasOptionalExpression) {
327                                         a.Report.Error (1745, a.Location,
328                                                 "Cannot specify `{0}' attribute on optional parameter `{1}'",
329                                                 TypeManager.CSharpName (a.Type).Replace ("Attribute", ""), Name);
330                                 }
331
332                                 if (a.Type == pa.DefaultParameterValue)
333                                         return;
334                         }
335
336                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
337                 }
338                 
339                 public virtual bool CheckAccessibility (InterfaceMemberBase member)
340                 {
341                         if (parameter_type == null)
342                                 return true;
343
344                         return member.IsAccessibleAs (parameter_type);
345                 }
346
347                 // <summary>
348                 //   Resolve is used in method definitions
349                 // </summary>
350                 public virtual TypeSpec Resolve (IMemberContext rc, int index)
351                 {
352                         if (parameter_type != null)
353                                 return parameter_type;
354
355                         if (attributes != null)
356                                 attributes.AttachTo (this, rc);
357
358                         parameter_type = texpr.ResolveAsType (rc);
359                         if (parameter_type == null)
360                                 return null;
361
362                         this.idx = index;
363         
364                         if ((modFlags & Parameter.Modifier.ISBYREF) != 0 && parameter_type.IsSpecialRuntimeType) {
365                                 rc.Module.Compiler.Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
366                                         GetSignatureForError ());
367                                 return null;
368                         }
369
370                         TypeManager.CheckTypeVariance (parameter_type,
371                                 (modFlags & Parameter.Modifier.ISBYREF) != 0 ? Variance.None : Variance.Contravariant,
372                                 rc);
373
374                         if (parameter_type.IsStatic) {
375                                 rc.Module.Compiler.Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
376                                         texpr.GetSignatureForError ());
377                                 return parameter_type;
378                         }
379
380                         if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)) {
381                                 rc.Module.Compiler.Report.Error (1103, Location, "The extension method cannot be of type `{0}'",
382                                         TypeManager.CSharpName (parameter_type));
383                         }
384
385                         return parameter_type;
386                 }
387
388                 public void ResolveDefaultValue (ResolveContext rc)
389                 {
390                         //
391                         // Default value was specified using an expression
392                         //
393                         if (default_expr != null) {
394                                 ((DefaultParameterValueExpression)default_expr).Resolve (rc, this);
395                                 return;
396                         }
397
398                         if (attributes == null)
399                                 return;
400                         
401                         var opt_attr = attributes.Search (rc.Module.PredefinedAttributes.OptionalParameter);
402                         var def_attr = attributes.Search (rc.Module.PredefinedAttributes.DefaultParameterValue);
403                         if (def_attr != null) {
404                                 if (def_attr.Resolve () == null)
405                                         return;
406
407                                 var default_expr_attr = def_attr.GetParameterDefaultValue ();
408                                 if (default_expr_attr == null)
409                                         return;
410
411                                 var dpa_rc = def_attr.CreateResolveContext ();
412                                 default_expr = default_expr_attr.Resolve (dpa_rc);
413
414                                 if (default_expr is BoxedCast)
415                                         default_expr = ((BoxedCast) default_expr).Child;
416
417                                 Constant c = default_expr as Constant;
418                                 if (c == null) {
419                                         if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
420                                                 rc.Report.Error (1910, default_expr.Location,
421                                                         "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
422                                                         default_expr.Type.GetSignatureForError ());
423                                         } else {
424                                                 rc.Report.Error (1909, default_expr.Location,
425                                                         "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
426                                                         default_expr.Type.GetSignatureForError ()); ;
427                                         }
428
429                                         default_expr = null;
430                                         return;
431                                 }
432
433                                 if (TypeSpecComparer.IsEqual (default_expr.Type, parameter_type) ||
434                                         (default_expr is NullConstant && TypeSpec.IsReferenceType (parameter_type) && !parameter_type.IsGenericParameter) ||
435                                         parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
436                                         return;
437                                 }
438
439                                 //
440                                 // LAMESPEC: Some really weird csc behaviour which we have to mimic
441                                 // User operators returning same type as parameter type are considered
442                                 // valid for this attribute only
443                                 //
444                                 // struct S { public static implicit operator S (int i) {} }
445                                 //
446                                 // void M ([DefaultParameterValue (3)]S s)
447                                 //
448                                 var expr = Convert.ImplicitUserConversion (dpa_rc, default_expr, parameter_type, loc);
449                                 if (expr != null && TypeSpecComparer.IsEqual (expr.Type, parameter_type)) {
450                                         return;
451                                 }
452                                 
453                                 rc.Report.Error (1908, default_expr.Location, "The type of the default value should match the type of the parameter");
454                                 return;
455                         }
456
457                         if (opt_attr != null) {
458                                 default_expr = EmptyExpression.MissingValue;
459                         }
460                 }
461
462                 public bool HasDefaultValue {
463                         get { return default_expr != null; }
464                 }
465
466                 public bool HasExtensionMethodModifier {
467                         get { return (modFlags & Modifier.This) != 0; }
468                 }
469
470                 //
471                 // Hoisted parameter variant
472                 //
473                 public HoistedVariable HoistedVariant {
474                         get {
475                                 return hoisted_variant;
476                         }
477                         set {
478                                 hoisted_variant = value;
479                         }
480                 }
481
482                 public Modifier ModFlags {
483                         get { return modFlags & ~Modifier.This; }
484                 }
485
486                 public string Name {
487                         get { return name; }
488                         set { name = value; }
489                 }
490
491                 public override AttributeTargets AttributeTargets {
492                         get {
493                                 return AttributeTargets.Parameter;
494                         }
495                 }
496
497                 public void Error_DuplicateName (Report r)
498                 {
499                         r.Error (100, Location, "The parameter name `{0}' is a duplicate", Name);
500                 }
501
502                 public virtual string GetSignatureForError ()
503                 {
504                         string type_name;
505                         if (parameter_type != null)
506                                 type_name = TypeManager.CSharpName (parameter_type);
507                         else
508                                 type_name = texpr.GetSignatureForError ();
509
510                         string mod = GetModifierSignature (modFlags);
511                         if (mod.Length > 0)
512                                 return String.Concat (mod, " ", type_name);
513
514                         return type_name;
515                 }
516
517                 public static string GetModifierSignature (Modifier mod)
518                 {
519                         switch (mod) {
520                         case Modifier.OUT:
521                                 return "out";
522                         case Modifier.PARAMS:
523                                 return "params";
524                         case Modifier.REF:
525                                 return "ref";
526                         case Modifier.This:
527                                 return "this";
528                         default:
529                                 return "";
530                         }
531                 }
532
533                 public void IsClsCompliant (IMemberContext ctx)
534                 {
535                         if (parameter_type.IsCLSCompliant ())
536                                 return;
537
538                         ctx.Module.Compiler.Report.Warning (3001, 1, Location,
539                                 "Argument type `{0}' is not CLS-compliant", parameter_type.GetSignatureForError ());
540                 }
541
542                 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
543                 {
544                         if (builder != null)
545                                 throw new InternalErrorException ("builder already exists");
546
547                         var pattrs = ParametersCompiled.GetParameterAttribute (modFlags);
548                         if (HasOptionalExpression)
549                                 pattrs |= ParameterAttributes.Optional;
550
551                         if (mb == null)
552                                 builder = cb.DefineParameter (index, pattrs, Name);
553                         else
554                                 builder = mb.DefineParameter (index, pattrs, Name);
555
556                         if (OptAttributes != null)
557                                 OptAttributes.Emit ();
558
559                         if (HasDefaultValue) {
560                                 //
561                                 // Emit constant values for true constants only, the other
562                                 // constant-like expressions will rely on default value expression
563                                 //
564                                 var def_value = DefaultValue;
565                                 Constant c = def_value != null ? def_value.Child as Constant : default_expr as Constant;
566                                 if (c != null) {
567                                         if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
568                                                 pa.DecimalConstant.EmitAttribute (builder, (decimal) c.GetValue (), c.Location);
569                                         } else {
570                                                 builder.SetConstant (c.GetValue ());
571                                         }
572                                 } else if (default_expr.Type.IsStruct) {
573                                         //
574                                         // Handles special case where default expression is used with value-type
575                                         //
576                                         // void Foo (S s = default (S)) {}
577                                         //
578                                         builder.SetConstant (null);
579                                 }
580                         }
581
582                         if (parameter_type != null) {
583                                 if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
584                                         pa.Dynamic.EmitAttribute (builder);
585                                 } else if (parameter_type.HasDynamicElement) {
586                                         pa.Dynamic.EmitAttribute (builder, parameter_type, Location);
587                                 }
588                         }
589                 }
590
591                 public Parameter Clone ()
592                 {
593                         Parameter p = (Parameter) MemberwiseClone ();
594                         if (attributes != null)
595                                 p.attributes = attributes.Clone ();
596
597                         return p;
598                 }
599
600                 public ExpressionStatement CreateExpressionTreeVariable (BlockContext ec)
601                 {
602                         if ((modFlags & Modifier.ISBYREF) != 0)
603                                 ec.Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
604
605                         expr_tree_variable = TemporaryVariableReference.Create (ResolveParameterExpressionType (ec, Location).Type, ec.CurrentBlock.ParametersBlock, Location);
606                         expr_tree_variable = (TemporaryVariableReference) expr_tree_variable.Resolve (ec);
607
608                         Arguments arguments = new Arguments (2);
609                         arguments.Add (new Argument (new TypeOf (parameter_type, Location)));
610                         arguments.Add (new Argument (new StringConstant (ec.BuiltinTypes, Name, Location)));
611                         return new SimpleAssign (ExpressionTreeVariableReference (),
612                                 Expression.CreateExpressionFactoryCall (ec, "Parameter", null, arguments, Location));
613                 }
614
615                 public void Emit (EmitContext ec)
616                 {
617                         ec.EmitArgumentLoad (idx);
618                 }
619
620                 public void EmitAssign (EmitContext ec)
621                 {
622                         ec.EmitArgumentStore (idx);
623                 }
624
625                 public void EmitAddressOf (EmitContext ec)
626                 {
627                         if ((ModFlags & Modifier.ISBYREF) != 0) {
628                                 ec.EmitArgumentLoad (idx);
629                         } else {
630                                 ec.EmitArgumentAddress (idx);
631                         }
632                 }
633
634                 public TemporaryVariableReference ExpressionTreeVariableReference ()
635                 {
636                         return expr_tree_variable;
637                 }
638
639                 //
640                 // System.Linq.Expressions.ParameterExpression type
641                 //
642                 public static TypeExpr ResolveParameterExpressionType (IMemberContext ec, Location location)
643                 {
644                         TypeSpec p_type = ec.Module.PredefinedTypes.ParameterExpression.Resolve ();
645                         return new TypeExpression (p_type, location);
646                 }
647
648                 public void Warning_UselessOptionalParameter (Report Report)
649                 {
650                         Report.Warning (1066, 1, Location,
651                                 "The default value specified for optional parameter `{0}' will never be used",
652                                 Name);
653                 }
654         }
655
656         //
657         // Imported or resolved parameter information
658         //
659         public class ParameterData : IParameterData
660         {
661                 readonly string name;
662                 readonly Parameter.Modifier modifiers;
663                 readonly Expression default_value;
664
665                 public ParameterData (string name, Parameter.Modifier modifiers)
666                 {
667                         this.name = name;
668                         this.modifiers = modifiers;
669                 }
670
671                 public ParameterData (string name, Parameter.Modifier modifiers, Expression defaultValue)
672                         : this (name, modifiers)
673                 {
674                         this.default_value = defaultValue;
675                 }
676
677                 #region IParameterData Members
678
679                 public Expression DefaultValue {
680                         get { return default_value; }
681                 }
682
683                 public bool HasExtensionMethodModifier {
684                         get { return (modifiers & Parameter.Modifier.This) != 0; }
685                 }
686
687                 public bool HasDefaultValue {
688                         get { return default_value != null; }
689                 }
690
691                 public Parameter.Modifier ModFlags {
692                         get { return modifiers & ~Parameter.Modifier.This; }
693                 }
694
695                 public string Name {
696                         get { return name; }
697                 }
698
699                 #endregion
700         }
701
702         public abstract class AParametersCollection
703         {
704                 protected bool has_arglist;
705                 protected bool has_params;
706
707                 // Null object pattern
708                 protected IParameterData [] parameters;
709                 protected TypeSpec [] types;
710
711                 public CallingConventions CallingConvention {
712                         get {
713                                 return has_arglist ?
714                                         CallingConventions.VarArgs :
715                                         CallingConventions.Standard;
716                         }
717                 }
718
719                 public int Count {
720                         get { return parameters.Length; }
721                 }
722
723                 public TypeSpec ExtensionMethodType {
724                         get {
725                                 if (Count == 0)
726                                         return null;
727
728                                 return FixedParameters [0].HasExtensionMethodModifier ?
729                                         types [0] : null;
730                         }
731                 }
732
733                 public IParameterData [] FixedParameters {
734                         get {
735                                 return parameters;
736                         }
737                 }
738
739                 public static ParameterAttributes GetParameterAttribute (Parameter.Modifier modFlags)
740                 {
741                         return (modFlags & Parameter.Modifier.OUT) == Parameter.Modifier.OUT ?
742                                 ParameterAttributes.Out : ParameterAttributes.None;
743                 }
744
745                 // Very expensive operation
746                 public MetaType[] GetMetaInfo ()
747                 {
748                         MetaType[] types;
749                         if (has_arglist) {
750                                 if (Count == 1)
751                                         return MetaType.EmptyTypes;
752
753                                 types = new MetaType[Count - 1];
754                         } else {
755                                 if (Count == 0)
756                                         return MetaType.EmptyTypes;
757
758                                 types = new MetaType[Count];
759                         }
760
761                         for (int i = 0; i < types.Length; ++i) {
762                                 types[i] = Types[i].GetMetaInfo ();
763
764                                 if ((FixedParameters [i].ModFlags & Parameter.Modifier.ISBYREF) == 0)
765                                         continue;
766
767                                 // TODO MemberCache: Should go to MetaInfo getter
768                                 types [i] = types [i].MakeByRefType ();
769                         }
770
771                         return types;
772                 }
773
774                 //
775                 // Returns the parameter information based on the name
776                 //
777                 public int GetParameterIndexByName (string name)
778                 {
779                         for (int idx = 0; idx < Count; ++idx) {
780                                 if (parameters [idx].Name == name)
781                                         return idx;
782                         }
783
784                         return -1;
785                 }
786
787                 public string GetSignatureForDocumentation ()
788                 {
789                         if (IsEmpty)
790                                 return string.Empty;
791
792                         StringBuilder sb = new StringBuilder ("(");
793                         for (int i = 0; i < Count; ++i) {
794                                 if (i != 0)
795                                         sb.Append (",");
796
797                                 sb.Append (types [i].GetSignatureForDocumentation ());
798
799                                 if ((parameters[i].ModFlags & Parameter.Modifier.ISBYREF) != 0)
800                                         sb.Append ("@");
801                         }
802                         sb.Append (")");
803
804                         return sb.ToString ();
805                 }
806
807                 public string GetSignatureForError ()
808                 {
809                         return GetSignatureForError ("(", ")", Count);
810                 }
811
812                 public string GetSignatureForError (string start, string end, int count)
813                 {
814                         StringBuilder sb = new StringBuilder (start);
815                         for (int i = 0; i < count; ++i) {
816                                 if (i != 0)
817                                         sb.Append (", ");
818                                 sb.Append (ParameterDesc (i));
819                         }
820                         sb.Append (end);
821                         return sb.ToString ();
822                 }
823
824                 public bool HasArglist {
825                         get { return has_arglist; }
826                 }
827
828                 public bool HasExtensionMethodType {
829                         get {
830                                 if (Count == 0)
831                                         return false;
832
833                                 return FixedParameters [0].HasExtensionMethodModifier;
834                         }
835                 }
836
837                 public bool HasParams {
838                         get { return has_params; }
839                 }
840
841                 public bool IsEmpty {
842                         get { return parameters.Length == 0; }
843                 }
844
845                 public AParametersCollection Inflate (TypeParameterInflator inflator)
846                 {
847                         TypeSpec[] inflated_types = null;
848                         bool default_value = false;
849
850                         for (int i = 0; i < Count; ++i) {
851                                 var inflated_param = inflator.Inflate (types[i]);
852                                 if (inflated_types == null) {
853                                         if (inflated_param == types[i])
854                                                 continue;
855
856                                         default_value |= FixedParameters[i] is DefaultValueExpression;
857                                         inflated_types = new TypeSpec[types.Length];
858                                         Array.Copy (types, inflated_types, types.Length);       
859                                 }
860
861                                 inflated_types[i] = inflated_param;
862                         }
863
864                         if (inflated_types == null)
865                                 return this;
866
867                         var clone = (AParametersCollection) MemberwiseClone ();
868                         clone.types = inflated_types;
869                         if (default_value) {
870                                 for (int i = 0; i < Count; ++i) {
871                                         var dve = clone.FixedParameters[i] as DefaultValueExpression;
872                                         if (dve != null) {
873                                                 throw new NotImplementedException ("net");
874                                                 //      clone.FixedParameters [i].DefaultValue = new DefaultValueExpression ();
875                                         }
876                                 }
877                         }
878
879                         return clone;
880                 }
881
882                 public string ParameterDesc (int pos)
883                 {
884                         if (types == null || types [pos] == null)
885                                 return ((Parameter)FixedParameters [pos]).GetSignatureForError ();
886
887                         string type = TypeManager.CSharpName (types [pos]);
888                         if (FixedParameters [pos].HasExtensionMethodModifier)
889                                 return "this " + type;
890
891                         Parameter.Modifier mod = FixedParameters [pos].ModFlags;
892                         if (mod == 0)
893                                 return type;
894
895                         return Parameter.GetModifierSignature (mod) + " " + type;
896                 }
897
898                 public TypeSpec[] Types {
899                         get { return types; }
900                         set { types = value; }
901                 }
902         }
903
904         //
905         // A collection of imported or resolved parameters
906         //
907         public class ParametersImported : AParametersCollection
908         {
909                 public ParametersImported (IParameterData [] parameters, TypeSpec [] types, bool hasArglist, bool hasParams)
910                 {
911                         this.parameters = parameters;
912                         this.types = types;
913                         this.has_arglist = hasArglist;
914                         this.has_params = hasParams;
915                 }
916
917                 public ParametersImported (IParameterData[] param, TypeSpec[] types, bool hasParams)
918                 {
919                         this.parameters = param;
920                         this.types = types;
921                         this.has_params = hasParams;
922                 }
923         }
924
925         /// <summary>
926         ///   Represents the methods parameters
927         /// </summary>
928         public class ParametersCompiled : AParametersCollection
929         {
930                 public static readonly ParametersCompiled EmptyReadOnlyParameters = new ParametersCompiled ();
931                 
932                 // Used by C# 2.0 delegates
933                 public static readonly ParametersCompiled Undefined = new ParametersCompiled ();
934
935                 private ParametersCompiled ()
936                 {
937                         parameters = new Parameter [0];
938                         types = TypeSpec.EmptyTypes;
939                 }
940
941                 private ParametersCompiled (IParameterData[] parameters, TypeSpec[] types)
942                 {
943                         this.parameters = parameters;
944                     this.types = types;
945                 }
946                 
947                 public ParametersCompiled (params Parameter[] parameters)
948                 {
949                         if (parameters == null || parameters.Length == 0)
950                                 throw new ArgumentException ("Use EmptyReadOnlyParameters");
951
952                         this.parameters = parameters;
953                         int count = parameters.Length;
954
955                         for (int i = 0; i < count; i++){
956                                 has_params |= (parameters [i].ModFlags & Parameter.Modifier.PARAMS) != 0;
957                         }
958                 }
959
960                 public ParametersCompiled (Parameter [] parameters, bool has_arglist) :
961                         this (parameters)
962                 {
963                         this.has_arglist = has_arglist;
964                 }
965                 
966                 public static ParametersCompiled CreateFullyResolved (Parameter p, TypeSpec type)
967                 {
968                         return new ParametersCompiled (new Parameter [] { p }, new TypeSpec [] { type });
969                 }
970                 
971                 public static ParametersCompiled CreateFullyResolved (Parameter[] parameters, TypeSpec[] types)
972                 {
973                         return new ParametersCompiled (parameters, types);
974                 }
975
976                 //
977                 // TODO: This does not fit here, it should go to different version of AParametersCollection
978                 // as the underlying type is not Parameter and some methods will fail to cast
979                 //
980                 public static AParametersCollection CreateFullyResolved (params TypeSpec[] types)
981                 {
982                         var pd = new ParameterData [types.Length];
983                         for (int i = 0; i < pd.Length; ++i)
984                                 pd[i] = new ParameterData (null, Parameter.Modifier.NONE, null);
985
986                         return new ParametersCompiled (pd, types);
987                 }
988
989                 public static ParametersCompiled CreateImplicitParameter (FullNamedExpression texpr, Location loc)
990                 {
991                         return new ParametersCompiled (
992                                 new[] { new Parameter (texpr, "value", Parameter.Modifier.NONE, null, loc) },
993                                 null);
994                 }
995
996                 public void CheckConstraints (IMemberContext mc)
997                 {
998                         foreach (Parameter p in parameters) {
999                                 //
1000                                 // It's null for compiler generated types or special types like __arglist
1001                                 //
1002                                 if (p.TypeExpression != null)
1003                                         ConstraintChecker.Check (mc, p.Type, p.TypeExpression.Location);
1004                         }
1005                 }
1006
1007                 //
1008                 // Returns non-zero value for equal CLS parameter signatures
1009                 //
1010                 public static int IsSameClsSignature (AParametersCollection a, AParametersCollection b)
1011                 {
1012                         int res = 0;
1013
1014                         for (int i = 0; i < a.Count; ++i) {
1015                                 var a_type = a.Types[i];
1016                                 var b_type = b.Types[i];
1017                                 if (TypeSpecComparer.Override.IsEqual (a_type, b_type)) {
1018                                         const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT;
1019                                         if ((a.FixedParameters[i].ModFlags & ref_out) != (b.FixedParameters[i].ModFlags & ref_out))
1020                                                 res |= 1;
1021
1022                                         continue;
1023                                 }
1024
1025                                 var ac_a = a_type as ArrayContainer;
1026                                 if (ac_a == null)
1027                                         return 0;
1028
1029                                 var ac_b = b_type as ArrayContainer;
1030                                 if (ac_b == null)
1031                                         return 0;
1032
1033                                 if (ac_a.Element is ArrayContainer || ac_b.Element is ArrayContainer) {
1034                                         res |= 2;
1035                                         continue;
1036                                 }
1037
1038                                 if (ac_a.Rank != ac_b.Rank && TypeSpecComparer.Override.IsEqual (ac_a.Element, ac_b.Element)) {
1039                                         res |= 1;
1040                                         continue;
1041                                 }
1042
1043                                 return 0;
1044                         }
1045
1046                         return res;
1047                 }
1048
1049                 public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, TypeSpec compilerTypes)
1050                 {
1051                         return MergeGenerated (ctx, userParams, checkConflicts,
1052                                 new Parameter [] { compilerParams },
1053                                 new TypeSpec [] { compilerTypes });
1054                 }
1055
1056                 //
1057                 // Use this method when you merge compiler generated parameters with user parameters
1058                 //
1059                 public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter[] compilerParams, TypeSpec[] compilerTypes)
1060                 {
1061                         Parameter[] all_params = new Parameter [userParams.Count + compilerParams.Length];
1062                         userParams.FixedParameters.CopyTo(all_params, 0);
1063
1064                         TypeSpec [] all_types;
1065                         if (userParams.types != null) {
1066                                 all_types = new TypeSpec [all_params.Length];
1067                                 userParams.Types.CopyTo (all_types, 0);
1068                         } else {
1069                                 all_types = null;
1070                         }
1071
1072                         int last_filled = userParams.Count;
1073                         int index = 0;
1074                         foreach (Parameter p in compilerParams) {
1075                                 for (int i = 0; i < last_filled; ++i) {
1076                                         while (p.Name == all_params [i].Name) {
1077                                                 if (checkConflicts && i < userParams.Count) {
1078                                                         ctx.Report.Error (316, userParams[i].Location,
1079                                                                 "The parameter name `{0}' conflicts with a compiler generated name", p.Name);
1080                                                 }
1081                                                 p.Name = '_' + p.Name;
1082                                         }
1083                                 }
1084                                 all_params [last_filled] = p;
1085                                 if (all_types != null)
1086                                         all_types [last_filled] = compilerTypes [index++];
1087                                 ++last_filled;
1088                         }
1089                         
1090                         ParametersCompiled parameters = new ParametersCompiled (all_params, all_types);
1091                         parameters.has_params = userParams.has_params;
1092                         return parameters;
1093                 }
1094
1095                 //
1096                 // Parameters checks for members which don't have a block
1097                 //
1098                 public void CheckParameters (MemberCore member)
1099                 {
1100                         for (int i = 0; i < parameters.Length; ++i) {
1101                                 var name = parameters[i].Name;
1102                                 for (int ii = i + 1; ii < parameters.Length; ++ii) {
1103                                         if (parameters[ii].Name == name)
1104                                                 this[ii].Error_DuplicateName (member.Compiler.Report);
1105                                 }
1106                         }
1107                 }
1108
1109                 public bool Resolve (IMemberContext ec)
1110                 {
1111                         if (types != null)
1112                                 return true;
1113                         
1114                         types = new TypeSpec [Count];
1115                         
1116                         bool ok = true;
1117                         Parameter p;
1118                         for (int i = 0; i < FixedParameters.Length; ++i) {
1119                                 p = this [i];
1120                                 TypeSpec t = p.Resolve (ec, i);
1121                                 if (t == null) {
1122                                         ok = false;
1123                                         continue;
1124                                 }
1125
1126                                 types [i] = t;
1127                         }
1128
1129                         return ok;
1130                 }
1131
1132                 public void ResolveDefaultValues (MemberCore m)
1133                 {
1134                         ResolveContext rc = null;
1135                         for (int i = 0; i < parameters.Length; ++i) {
1136                                 Parameter p = (Parameter) parameters [i];
1137
1138                                 //
1139                                 // Try not to enter default values resolution if there are is not any default value possible
1140                                 //
1141                                 if (p.HasDefaultValue || p.OptAttributes != null) {
1142                                         if (rc == null)
1143                                                 rc = new ResolveContext (m);
1144
1145                                         p.ResolveDefaultValue (rc);
1146                                 }
1147                         }
1148                 }
1149
1150                 // Define each type attribute (in/out/ref) and
1151                 // the argument names.
1152                 public void ApplyAttributes (IMemberContext mc, MethodBase builder)
1153                 {
1154                         if (Count == 0)
1155                                 return;
1156
1157                         MethodBuilder mb = builder as MethodBuilder;
1158                         ConstructorBuilder cb = builder as ConstructorBuilder;
1159                         var pa = mc.Module.PredefinedAttributes;
1160
1161                         for (int i = 0; i < Count; i++) {
1162                                 this [i].ApplyAttributes (mb, cb, i + 1, pa);
1163                         }
1164                 }
1165
1166                 public void VerifyClsCompliance (IMemberContext ctx)
1167                 {
1168                         foreach (Parameter p in FixedParameters)
1169                                 p.IsClsCompliant (ctx);
1170                 }
1171
1172                 public Parameter this [int pos] {
1173                         get { return (Parameter) parameters [pos]; }
1174                 }
1175
1176                 public Expression CreateExpressionTree (BlockContext ec, Location loc)
1177                 {
1178                         var initializers = new ArrayInitializer (Count, loc);
1179                         foreach (Parameter p in FixedParameters) {
1180                                 //
1181                                 // Each parameter expression is stored to local variable
1182                                 // to save some memory when referenced later.
1183                                 //
1184                                 StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec));
1185                                 if (se.Resolve (ec)) {
1186                                         ec.CurrentBlock.AddScopeStatement (new TemporaryVariableReference.Declarator (p.ExpressionTreeVariableReference ()));
1187                                         ec.CurrentBlock.AddScopeStatement (se);
1188                                 }
1189                                 
1190                                 initializers.Add (p.ExpressionTreeVariableReference ());
1191                         }
1192
1193                         return new ArrayCreation (
1194                                 Parameter.ResolveParameterExpressionType (ec, loc),
1195                                 initializers, loc);
1196                 }
1197
1198                 public ParametersCompiled Clone ()
1199                 {
1200                         ParametersCompiled p = (ParametersCompiled) MemberwiseClone ();
1201
1202                         p.parameters = new IParameterData [parameters.Length];
1203                         for (int i = 0; i < Count; ++i)
1204                                 p.parameters [i] = this [i].Clone ();
1205
1206                         return p;
1207                 }
1208         }
1209
1210         //
1211         // Default parameter value expression. We need this wrapper to handle
1212         // default parameter values of folded constants when for indexer parameters
1213         // The expression is resolved only once but applied to two methods which
1214         // both share reference to this expression and we ensure that resolving
1215         // this expression always returns same instance
1216         //
1217         public class DefaultParameterValueExpression : CompositeExpression
1218         {
1219                 public DefaultParameterValueExpression (Expression expr)
1220                         : base (expr)
1221                 {
1222                 }
1223
1224                 protected override Expression DoResolve (ResolveContext rc)
1225                 {
1226                         return base.DoResolve (rc);
1227                 }
1228
1229                 public void Resolve (ResolveContext rc, Parameter p)
1230                 {
1231                         var expr = Resolve (rc);
1232                         if (expr == null)
1233                                 return;
1234
1235                         expr = Child;
1236
1237                         if (!(expr is Constant || expr is DefaultValueExpression || (expr is New && ((New) expr).IsDefaultStruct))) {
1238                                 rc.Report.Error (1736, Location,
1239                                         "The expression being assigned to optional parameter `{0}' must be a constant or default value",
1240                                         p.Name);
1241
1242                                 return;
1243                         }
1244
1245                         var parameter_type = p.Type;
1246                         if (type == parameter_type)
1247                                 return;
1248
1249                         var res = Convert.ImplicitConversionStandard (rc, expr, parameter_type, Location);
1250                         if (res != null) {
1251                                 if (parameter_type.IsNullableType && res is Nullable.Wrap) {
1252                                         Nullable.Wrap wrap = (Nullable.Wrap) res;
1253                                         res = wrap.Child;
1254                                         if (!(res is Constant)) {
1255                                                 rc.Report.Error (1770, Location,
1256                                                         "The expression being assigned to nullable optional parameter `{0}' must be default value",
1257                                                         p.Name);
1258                                                 return;
1259                                         }
1260                                 }
1261
1262                                 if (!expr.IsNull && TypeSpec.IsReferenceType (parameter_type) && parameter_type.BuiltinType != BuiltinTypeSpec.Type.String) {
1263                                         rc.Report.Error (1763, Location,
1264                                                 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
1265                                                 p.Name, parameter_type.GetSignatureForError ());
1266
1267                                         return;
1268                                 }
1269
1270                                 this.expr = res;
1271                                 return;
1272                         }
1273
1274                         rc.Report.Error (1750, Location,
1275                                 "Optional parameter expression of type `{0}' cannot be converted to parameter type `{1}'",
1276                                 type.GetSignatureForError (), parameter_type.GetSignatureForError ());
1277                 }
1278         }
1279 }