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 ImplicitLambdaParameter : Parameter
144 public ImplicitLambdaParameter (string name, Location loc)
145 : base ((Type)null, name, Modifier.NONE, null, loc)
149 public override bool Resolve (IResolveContext ec)
151 if (parameter_type == null)
152 throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set",
159 public class ParamsParameter : Parameter {
160 public ParamsParameter (Expression type, string name, Attributes attrs, Location loc):
161 base (type, name, Parameter.Modifier.PARAMS, attrs, loc)
165 public override bool Resolve (IResolveContext ec)
167 if (!base.Resolve (ec))
170 if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
171 Report.Error (225, Location, "The params parameter must be a single dimensional array");
177 public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
179 base.ApplyAttributes (mb, cb, index);
181 CustomAttributeBuilder a = new CustomAttributeBuilder (
182 TypeManager.cons_param_array_attribute, new object[0]);
184 builder.SetCustomAttribute (a);
188 public class ArglistParameter : Parameter {
189 // Doesn't have proper type because it's never chosen for better conversion
190 public ArglistParameter () :
191 base (typeof (ArglistParameter), String.Empty, Parameter.Modifier.ARGLIST, null, Location.Null)
195 public override bool CheckAccessibility (InterfaceMemberBase member)
200 public override bool Resolve (IResolveContext ec)
205 public override string GetSignatureForError ()
212 /// Represents a single method parameter
214 public class Parameter : ParameterBase {
216 public enum Modifier : byte {
218 REF = REFMASK | ISBYREF,
219 OUT = OUTMASK | ISBYREF,
221 // This is a flag which says that it's either REF or OUT.
229 static string[] attribute_targets = new string [] { "param" };
232 public Modifier modFlags;
234 public bool IsCaptured;
235 protected Type parameter_type;
236 public readonly Location Location;
238 IResolveContext resolve_context;
241 public Variable Variable {
246 public bool IsTypeParameter;
247 GenericConstraints constraints;
249 public bool IsTypeParameter {
255 throw new Exception ("You can not se TypeParameter in MCS");
260 public Parameter (Expression type, string name, Modifier mod, Attributes attrs, Location loc)
261 : this (type.Type, name, mod, attrs, loc)
263 if (type == TypeManager.system_void_expr)
264 Report.Error (1536, loc, "Invalid parameter type `void'");
269 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
274 parameter_type = type;
278 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
280 if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
281 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
285 if (a.Type == TypeManager.param_array_type) {
286 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
290 if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
291 !OptAttributes.Contains (TypeManager.in_attribute_type)) {
292 Report.Error (662, a.Location,
293 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
297 if (a.Type == TypeManager.cls_compliant_attribute_type) {
298 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
301 // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
302 if (a.Type == TypeManager.default_parameter_value_attribute_type) {
303 object val = a.GetParameterDefaultValue ();
305 Type t = val.GetType ();
306 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
307 if (parameter_type == TypeManager.object_type) {
309 t = TypeManager.type_type;
311 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
312 TypeManager.CSharpName (t));
314 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
315 TypeManager.CSharpName (parameter_type)); ;
321 if (parameter_type == TypeManager.object_type ||
322 (val == null && !TypeManager.IsValueType (parameter_type)) ||
323 (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
324 builder.SetConstant (val);
326 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
330 base.ApplyAttributeBuilder (a, cb);
333 public virtual bool CheckAccessibility (InterfaceMemberBase member)
338 return member.ds.AsAccessible (parameter_type, member.ModFlags);
341 public override IResolveContext ResolveContext {
343 return resolve_context;
348 // Resolve is used in method definitions
350 public virtual bool Resolve (IResolveContext ec)
352 // HACK: to resolve attributes correctly
353 this.resolve_context = ec;
355 if (parameter_type != null)
358 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
362 parameter_type = texpr.Type;
365 TypeParameterExpr tparam = texpr as TypeParameterExpr;
366 if (tparam != null) {
367 IsTypeParameter = true;
368 constraints = tparam.TypeParameter.Constraints;
373 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
374 Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
375 texpr.GetSignatureForError ());
379 if ((modFlags & Parameter.Modifier.ISBYREF) != 0){
380 if (parameter_type == TypeManager.typed_reference_type ||
381 parameter_type == TypeManager.arg_iterator_type){
382 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
383 GetSignatureForError ());
388 if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer) {
389 Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
390 TypeManager.CSharpName (parameter_type));
397 public void ResolveVariable (ToplevelBlock toplevel, int idx)
399 if (toplevel.RootScope != null)
400 var = toplevel.RootScope.GetCapturedParameter (this);
402 var = new ParameterVariable (this, idx);
405 public Type ExternalType ()
407 if ((modFlags & Parameter.Modifier.ISBYREF) != 0)
408 return TypeManager.GetReferenceType (parameter_type);
410 return parameter_type;
413 public bool HasExtensionMethodModifier {
414 get { return (modFlags & Modifier.This) != 0; }
417 public Modifier ModFlags {
418 get { return modFlags & ~Modifier.This; }
421 public Type ParameterType {
423 return parameter_type;
426 parameter_type = value;
427 IsTypeParameter = false;
432 public GenericConstraints GenericConstraints {
439 ParameterAttributes Attributes {
441 return (modFlags & Modifier.OUT) == Modifier.OUT ?
442 ParameterAttributes.Out : ParameterAttributes.None;
446 // TODO: should be removed !!!!!!!
447 public static ParameterAttributes GetParameterAttributes (Modifier mod)
449 int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
450 switch ((Modifier) flags) {
452 return ParameterAttributes.None;
454 return ParameterAttributes.None;
456 return ParameterAttributes.Out;
457 case Modifier.PARAMS:
461 return ParameterAttributes.None;
464 public override AttributeTargets AttributeTargets {
466 return AttributeTargets.Parameter;
470 public virtual string GetSignatureForError ()
473 if (parameter_type != null)
474 type_name = TypeManager.CSharpName (parameter_type);
476 type_name = TypeName.GetSignatureForError ();
478 string mod = GetModifierSignature (modFlags);
480 return String.Concat (mod, ' ', type_name);
485 public static string GetModifierSignature (Modifier mod)
490 case Modifier.PARAMS:
494 case Modifier.ARGLIST:
503 public void IsClsCompliant ()
505 if (AttributeTester.IsClsCompliant (ExternalType ()))
508 Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
511 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
513 #if !GMCS_SOURCE || !MS_COMPATIBLE
514 // TODO: It should use mb.DefineGenericParameters
516 builder = cb.DefineParameter (index, Attributes, Name);
518 builder = mb.DefineParameter (index, Attributes, Name);
521 if (OptAttributes != null)
522 OptAttributes.Emit ();
525 public override string[] ValidAttributeTargets {
527 return attribute_targets;
531 protected class ParameterVariable : Variable
533 public readonly Parameter Parameter;
534 public readonly int Idx;
535 public readonly bool IsRef;
537 public ParameterVariable (Parameter par, int idx)
539 this.Parameter = par;
541 this.IsRef = (par.ModFlags & Parameter.Modifier.ISBYREF) != 0;
544 public override Type Type {
545 get { return Parameter.ParameterType; }
548 public override bool HasInstance {
549 get { return false; }
552 public override bool NeedsTemporary {
553 get { return false; }
556 public override void EmitInstance (EmitContext ec)
560 public override void Emit (EmitContext ec)
563 if (!ec.MethodIsStatic)
566 ParameterReference.EmitLdArg (ec.ig, arg_idx);
569 public override void EmitAssign (EmitContext ec)
572 if (!ec.MethodIsStatic)
576 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
578 ec.ig.Emit (OpCodes.Starg, arg_idx);
581 public override void EmitAddressOf (EmitContext ec)
585 if (!ec.MethodIsStatic)
590 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
592 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
595 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
597 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
602 public Parameter Clone ()
604 Parameter p = new Parameter (parameter_type, Name, ModFlags, attributes, Location);
605 p.IsTypeParameter = IsTypeParameter;
612 /// Represents the methods parameters
614 public class Parameters : ParameterData {
615 // Null object pattern
616 public Parameter [] FixedParameters;
617 public readonly bool HasArglist;
621 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
622 static readonly Parameter ArgList = new ArglistParameter ();
625 // public readonly TypeParameter[] TypeParameters;
628 private Parameters ()
630 FixedParameters = new Parameter[0];
631 types = new Type [0];
634 private Parameters (Parameter[] parameters, Type[] types)
636 FixedParameters = parameters;
638 count = types.Length;
641 public Parameters (params Parameter[] parameters)
643 if (parameters == null)
644 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
646 FixedParameters = parameters;
647 count = parameters.Length;
650 public Parameters (Parameter[] parameters, bool has_arglist):
653 HasArglist = has_arglist;
656 public static Parameters CreateFullyResolved (Parameter p)
658 return new Parameters (new Parameter [] { p }, new Type [] { p.ParameterType });
661 public static Parameters CreateFullyResolved (Parameter[] parameters, Type[] types)
663 return new Parameters (parameters, types);
667 /// Use this method when you merge compiler generated argument with user arguments
669 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
671 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
672 Type[] all_types = new Type[all_params.Length];
673 userParams.FixedParameters.CopyTo(all_params, 0);
674 userParams.Types.CopyTo (all_types, 0);
676 int last_filled = userParams.Count;
677 foreach (Parameter p in compilerParams) {
678 for (int i = 0; i < last_filled; ++i) {
679 while (p.Name == all_params [i].Name) {
680 p.Name = '_' + p.Name;
683 all_params [last_filled] = p;
684 all_types [last_filled] = p.ParameterType;
688 return new Parameters (all_params, all_types);
699 return HasArglist ? count + 1 : count;
704 // The property can be used after parameter types were resolved.
706 public Type ExtensionMethodType {
711 return FixedParameters [0].HasExtensionMethodModifier ?
716 public bool HasExtensionMethodType {
721 return FixedParameters [0].HasExtensionMethodModifier;
731 for (int i = 0; i < count; i++){
732 string base_name = FixedParameters [i].Name;
733 for (int j = i + 1; j < count; j++){
734 if (base_name != FixedParameters [j].Name)
737 Report.Error (100, FixedParameters [i].Location,
738 "The parameter name `{0}' is a duplicate", base_name);
747 /// Returns the paramenter information based on the name
749 public Parameter GetParameterByName (string name, out int idx)
758 foreach (Parameter par in FixedParameters){
759 if (par.Name == name){
768 public Parameter GetParameterByName (string name)
772 return GetParameterByName (name, out idx);
775 public bool Resolve (IResolveContext ec)
780 types = new Type [count];
787 for (int i = 0; i < FixedParameters.Length; ++i) {
788 p = FixedParameters [i];
789 if (!p.Resolve (ec)) {
793 types [i] = p.ExternalType ();
799 public void ResolveVariable (ToplevelBlock toplevel)
801 for (int i = 0; i < FixedParameters.Length; ++i) {
802 Parameter p = FixedParameters [i];
803 p.ResolveVariable (toplevel, i);
807 public CallingConventions CallingConvention
811 return CallingConventions.VarArgs;
813 return CallingConventions.Standard;
817 // Define each type attribute (in/out/ref) and
818 // the argument names.
819 public void ApplyAttributes (MethodBase builder)
824 MethodBuilder mb = builder as MethodBuilder;
825 ConstructorBuilder cb = builder as ConstructorBuilder;
827 for (int i = 0; i < FixedParameters.Length; i++) {
828 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
833 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
835 Parameters p = Clone ();
836 for (int i = 0; i < count; ++i) {
837 if (types[i].IsGenericType) {
838 Type[] gen_arguments_open = new Type [types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
839 Type[] gen_arguments = types[i].GetGenericArguments ();
840 for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
841 if (gen_arguments[ii].IsGenericParameter) {
842 Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
843 gen_arguments_open[ii] = t;
845 gen_arguments_open[ii] = gen_arguments[ii];
848 p.FixedParameters [i].ParameterType = p.types[i] =
849 types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
853 if (types[i].IsGenericParameter) {
854 Type gen_argument = argTypes[types[i].GenericParameterPosition];
855 p.FixedParameters[i].ParameterType = p.types[i] = gen_argument;
864 public void VerifyClsCompliance ()
866 foreach (Parameter p in FixedParameters)
870 public string GetSignatureForError ()
872 StringBuilder sb = new StringBuilder ("(");
874 for (int i = 0; i < FixedParameters.Length; ++i) {
875 sb.Append (FixedParameters[i].GetSignatureForError ());
876 if (i < FixedParameters.Length - 1)
884 sb.Append ("__arglist");
888 return sb.ToString ();
891 public Type[] Types {
896 // Dangerous, used by implicit lambda parameters
897 // only to workaround bad design
904 public Parameter this [int pos]
907 if (pos >= count && (HasArglist || HasParams)) {
908 if (HasArglist && (pos == 0 || pos >= count))
913 return FixedParameters [pos];
917 #region ParameterData Members
919 public Type ParameterType (int pos)
921 return this [pos].ExternalType ();
924 public bool HasParams {
929 for (int i = count; i != 0; --i) {
930 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
937 public string ParameterName (int pos)
939 return this [pos].Name;
942 public string ParameterDesc (int pos)
944 return this [pos].GetSignatureForError ();
947 public Parameter.Modifier ParameterModifier (int pos)
949 return this [pos].ModFlags;
952 public Parameters Clone ()
954 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
956 foreach (Parameter p in FixedParameters)
957 parameters_copy [i++] = p.Clone ();
958 Parameters ps = new Parameters (parameters_copy, HasArglist);
960 ps.types = (Type[])types.Clone ();