2 // parameter.cs: Parameter definition.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 namespace Mono.CSharp {
22 /// Abstract Base class for parameters of a method.
24 public abstract class ParameterBase : Attributable {
26 protected ParameterBuilder builder;
28 protected ParameterBase (Attributes attrs)
33 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
35 if (a.Type == TypeManager.marshal_as_attr_type) {
36 UnmanagedMarshal marshal = a.GetMarshal (this);
37 if (marshal != null) {
38 builder.SetMarshal (marshal);
43 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
44 a.Error_InvalidSecurityParent ();
48 builder.SetCustomAttribute (cb);
51 public override bool IsClsComplianceRequired()
58 /// Class for applying custom attributes on the return type
60 public class ReturnParameter : ParameterBase {
61 public ReturnParameter (MethodBuilder mb, Location location):
65 builder = mb.DefineParameter (0, ParameterAttributes.None, "");
67 catch (ArgumentOutOfRangeException) {
68 Report.RuntimeMissingSupport (location, "custom attributes on the return type");
72 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
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");
78 // This occurs after Warning -28
82 base.ApplyAttributeBuilder (a, cb);
85 public override AttributeTargets AttributeTargets {
87 return AttributeTargets.ReturnValue;
91 public override IResolveContext ResolveContext {
93 throw new NotSupportedException ();
100 public override string[] ValidAttributeTargets {
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.
112 // TODO: should use more code from Parameter.ApplyAttributeBuilder
113 public class ImplicitParameter : ParameterBase {
114 public ImplicitParameter (MethodBuilder mb):
117 builder = mb.DefineParameter (1, ParameterAttributes.None, "");
120 public override AttributeTargets AttributeTargets {
122 return AttributeTargets.Parameter;
126 public override IResolveContext ResolveContext {
128 throw new NotSupportedException ();
135 public override string[] ValidAttributeTargets {
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)
148 public override bool Resolve (IResolveContext ec)
150 if (!base.Resolve (ec))
153 if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
154 Report.Error (225, Location, "The params parameter must be a single dimensional array");
160 public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
162 base.ApplyAttributes (mb, cb, index);
164 CustomAttributeBuilder a = new CustomAttributeBuilder (
165 TypeManager.ConsParamArrayAttribute, new object [0]);
167 builder.SetCustomAttribute (a);
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)
178 public override bool Resolve (IResolveContext ec)
183 public override string GetSignatureForError ()
190 /// Represents a single method parameter
192 public class Parameter : ParameterBase {
194 public enum Modifier : byte {
196 REF = REFMASK | ISBYREF,
197 OUT = OUTMASK | ISBYREF,
199 // This is a flag which says that it's either REF or OUT.
206 static string[] attribute_targets = new string [] { "param" };
208 public Expression TypeName;
209 public readonly Modifier ModFlags;
211 public bool IsCaptured;
212 protected Type parameter_type;
213 public readonly Location Location;
215 IResolveContext resolve_context;
218 public Variable Variable {
223 GenericConstraints constraints;
226 public Parameter (Expression type, string name, Modifier mod, Attributes attrs, Location loc)
235 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
240 parameter_type = type;
244 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
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");
251 if (a.Type == TypeManager.param_array_type) {
252 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
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");
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");
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 ();
271 Type t = val.GetType ();
272 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
273 if (parameter_type == TypeManager.object_type) {
275 t = TypeManager.type_type;
277 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
278 TypeManager.CSharpName (t));
280 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
281 TypeManager.CSharpName (parameter_type)); ;
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);
292 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
296 base.ApplyAttributeBuilder (a, cb);
299 public override IResolveContext ResolveContext {
301 return resolve_context;
306 // Resolve is used in method definitions
308 public virtual bool Resolve (IResolveContext ec)
310 if (parameter_type != null)
313 this.resolve_context = ec;
315 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
319 parameter_type = texpr.Type;
322 TypeParameterExpr tparam = texpr as TypeParameterExpr;
323 if (tparam != null) {
324 constraints = tparam.TypeParameter.Constraints;
329 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
330 Report.Error (721, Location, "`{0}': static types cannot be used as parameters", GetSignatureForError ());
334 if (parameter_type == TypeManager.void_type){
335 Report.Error (1536, Location, "Invalid parameter type 'void'");
339 if ((ModFlags & Parameter.Modifier.ISBYREF) != 0){
340 if (parameter_type == TypeManager.typed_reference_type ||
341 parameter_type == TypeManager.arg_iterator_type){
342 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
343 GetSignatureForError ());
351 public void ResolveVariable (ToplevelBlock toplevel, int idx)
353 if (toplevel.RootScope != null)
354 var = toplevel.RootScope.GetCapturedParameter (this);
356 var = new ParameterVariable (this, idx);
359 public Type ExternalType ()
361 if ((ModFlags & Parameter.Modifier.ISBYREF) != 0)
362 return TypeManager.GetReferenceType (parameter_type);
364 return parameter_type;
367 public Type ParameterType {
369 return parameter_type;
374 public GenericConstraints GenericConstraints {
381 public ParameterAttributes Attributes {
385 return ParameterAttributes.None;
387 return ParameterAttributes.None;
389 return ParameterAttributes.Out;
390 case Modifier.PARAMS:
394 return ParameterAttributes.None;
398 public static ParameterAttributes GetParameterAttributes (Modifier mod)
400 int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
401 switch ((Modifier) flags) {
403 return ParameterAttributes.None;
405 return ParameterAttributes.None;
407 return ParameterAttributes.Out;
408 case Modifier.PARAMS:
412 return ParameterAttributes.None;
415 public override AttributeTargets AttributeTargets {
417 return AttributeTargets.Parameter;
421 public virtual string GetSignatureForError ()
424 if (parameter_type != null)
425 type_name = TypeManager.CSharpName (parameter_type);
427 type_name = TypeName.GetSignatureForError ();
429 string mod = GetModifierSignature (ModFlags);
431 return String.Concat (mod, ' ', type_name);
436 public static string GetModifierSignature (Modifier mod)
441 case Modifier.PARAMS:
445 case Modifier.ARGLIST:
452 public void IsClsCompliant ()
454 if (AttributeTester.IsClsCompliant (ExternalType ()))
457 Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
460 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
462 #if !GMCS_SOURCE || !MS_COMPATIBLE
463 // TODO: It should use mb.DefineGenericParameters
465 builder = cb.DefineParameter (index, Attributes, Name);
467 builder = mb.DefineParameter (index, Attributes, Name);
470 if (OptAttributes != null)
471 OptAttributes.Emit ();
474 public override string[] ValidAttributeTargets {
476 return attribute_targets;
480 protected class ParameterVariable : Variable
482 public readonly Parameter Parameter;
483 public readonly int Idx;
484 public readonly bool IsRef;
486 public ParameterVariable (Parameter par, int idx)
488 this.Parameter = par;
490 this.IsRef = (par.ModFlags & Parameter.Modifier.ISBYREF) != 0;
493 public override Type Type {
494 get { return Parameter.ParameterType; }
497 public override bool HasInstance {
498 get { return false; }
501 public override bool NeedsTemporary {
502 get { return false; }
505 public override void EmitInstance (EmitContext ec)
509 public override void Emit (EmitContext ec)
512 if (!ec.MethodIsStatic)
515 ParameterReference.EmitLdArg (ec.ig, arg_idx);
518 public override void EmitAssign (EmitContext ec)
521 if (!ec.MethodIsStatic)
525 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
527 ec.ig.Emit (OpCodes.Starg, arg_idx);
530 public override void EmitAddressOf (EmitContext ec)
534 if (!ec.MethodIsStatic)
539 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
541 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
544 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
546 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
551 public Parameter Clone ()
553 Parameter p = new Parameter (TypeName, Name, ModFlags, attributes, Location);
554 p.parameter_type = parameter_type;
561 /// Represents the methods parameters
563 public class Parameters : ParameterData {
564 // Null object pattern
565 public Parameter [] FixedParameters;
566 public readonly bool HasArglist;
570 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
571 static readonly Parameter ArgList = new ArglistParameter ();
574 public readonly TypeParameter[] TypeParameters;
577 private Parameters ()
579 FixedParameters = new Parameter[0];
580 types = new Type [0];
583 public Parameters (Parameter[] parameters, Type[] types)
585 FixedParameters = parameters;
587 count = types.Length;
590 public Parameters (Parameter[] parameters)
592 if (parameters == null)
593 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
595 FixedParameters = parameters;
596 count = parameters.Length;
599 public Parameters (Parameter[] parameters, bool has_arglist):
602 HasArglist = has_arglist;
606 /// Use this method when you merge compiler generated argument with user arguments
608 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
610 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
611 Type[] all_types = new Type[all_params.Length];
612 userParams.FixedParameters.CopyTo(all_params, 0);
613 userParams.Types.CopyTo (all_types, 0);
615 int last_filled = userParams.Count;
616 foreach (Parameter p in compilerParams) {
617 for (int i = 0; i < last_filled; ++i) {
618 while (p.Name == all_params [i].Name) {
619 p.Name = '_' + p.Name;
622 all_params [last_filled] = p;
623 all_types [last_filled] = p.ParameterType;
627 return new Parameters (all_params, all_types);
638 return HasArglist ? count + 1 : count;
647 for (int i = 0; i < count; i++){
648 string base_name = FixedParameters [i].Name;
649 for (int j = i + 1; j < count; j++){
650 if (base_name != FixedParameters [j].Name)
653 Report.Error (100, FixedParameters [i].Location,
654 "The parameter name `{0}' is a duplicate", base_name);
663 /// Returns the paramenter information based on the name
665 public Parameter GetParameterByName (string name, out int idx)
674 foreach (Parameter par in FixedParameters){
675 if (par.Name == name){
684 public Parameter GetParameterByName (string name)
688 return GetParameterByName (name, out idx);
691 public bool Resolve (IResolveContext ec)
696 types = new Type [count];
703 for (int i = 0; i < FixedParameters.Length; ++i) {
704 p = FixedParameters [i];
705 if (!p.Resolve (ec)) {
709 types [i] = p.ExternalType ();
715 public void ResolveVariable (ToplevelBlock toplevel)
717 for (int i = 0; i < FixedParameters.Length; ++i) {
718 Parameter p = FixedParameters [i];
719 p.ResolveVariable (toplevel, i);
723 public CallingConventions CallingConvention
727 return CallingConventions.VarArgs;
729 return CallingConventions.Standard;
733 // Define each type attribute (in/out/ref) and
734 // the argument names.
735 public void ApplyAttributes (MethodBase builder)
740 MethodBuilder mb = builder as MethodBuilder;
741 ConstructorBuilder cb = builder as ConstructorBuilder;
743 for (int i = 0; i < FixedParameters.Length; i++) {
744 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
748 public void VerifyClsCompliance ()
750 foreach (Parameter p in FixedParameters)
754 public string GetSignatureForError ()
756 StringBuilder sb = new StringBuilder ("(");
758 for (int i = 0; i < FixedParameters.Length; ++i) {
759 sb.Append (FixedParameters[i].GetSignatureForError ());
760 if (i < FixedParameters.Length - 1)
768 sb.Append ("__arglist");
772 return sb.ToString ();
775 public Type[] Types {
781 public Parameter this [int pos]
784 if (pos >= count && (HasArglist || HasParams)) {
785 if (HasArglist && (pos == 0 || pos >= count))
790 return FixedParameters [pos];
794 #region ParameterData Members
796 public Type ParameterType (int pos)
798 return this [pos].ExternalType ();
801 public bool HasParams {
806 for (int i = count; i != 0; --i) {
807 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
814 public string ParameterName (int pos)
816 return this [pos].Name;
819 public string ParameterDesc (int pos)
821 return this [pos].GetSignatureForError ();
824 public Parameter.Modifier ParameterModifier (int pos)
826 return this [pos].ModFlags;
829 public Parameters Clone ()
831 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
833 foreach (Parameter p in FixedParameters)
834 parameters_copy [i++] = p.Clone ();
835 return new Parameters (parameters_copy, HasArglist);