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 ("Implicit lambda parameter type is not set");
158 public class ParamsParameter : Parameter {
159 public ParamsParameter (Expression type, string name, Attributes attrs, Location loc):
160 base (type, name, Parameter.Modifier.PARAMS, attrs, loc)
164 public override bool Resolve (IResolveContext ec)
166 if (!base.Resolve (ec))
169 if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
170 Report.Error (225, Location, "The params parameter must be a single dimensional array");
176 public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
178 base.ApplyAttributes (mb, cb, index);
180 CustomAttributeBuilder a = new CustomAttributeBuilder (
181 TypeManager.cons_param_array_attribute, new object[0]);
183 builder.SetCustomAttribute (a);
187 public class ArglistParameter : Parameter {
188 // Doesn't have proper type because it's never chosen for better conversion
189 public ArglistParameter () :
190 base (typeof (ArglistParameter), String.Empty, Parameter.Modifier.ARGLIST, null, Location.Null)
194 public override bool CheckAccessibility (InterfaceMemberBase member)
199 public override bool Resolve (IResolveContext ec)
204 public override string GetSignatureForError ()
211 /// Represents a single method parameter
213 public class Parameter : ParameterBase {
215 public enum Modifier : byte {
217 REF = REFMASK | ISBYREF,
218 OUT = OUTMASK | ISBYREF,
220 // This is a flag which says that it's either REF or OUT.
228 static string[] attribute_targets = new string [] { "param" };
231 public Modifier modFlags;
233 public bool IsCaptured;
234 protected Type parameter_type;
235 public readonly Location Location;
237 IResolveContext resolve_context;
240 public Variable Variable {
245 public bool IsTypeParameter;
246 GenericConstraints constraints;
248 public bool IsTypeParameter {
254 throw new Exception ("You can not se TypeParameter in MCS");
259 public Parameter (Expression type, string name, Modifier mod, Attributes attrs, Location loc)
260 : this (type.Type, name, mod, attrs, loc)
262 if (type == TypeManager.system_void_expr)
263 Report.Error (1536, loc, "Invalid parameter type `void'");
268 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
273 parameter_type = type;
277 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
279 if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
280 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
284 if (a.Type == TypeManager.param_array_type) {
285 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
289 if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
290 !OptAttributes.Contains (TypeManager.in_attribute_type)) {
291 Report.Error (662, a.Location,
292 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
296 if (a.Type == TypeManager.cls_compliant_attribute_type) {
297 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
300 // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
301 if (a.Type == TypeManager.default_parameter_value_attribute_type) {
302 object val = a.GetParameterDefaultValue ();
304 Type t = val.GetType ();
305 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
306 if (parameter_type == TypeManager.object_type) {
308 t = TypeManager.type_type;
310 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
311 TypeManager.CSharpName (t));
313 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
314 TypeManager.CSharpName (parameter_type)); ;
320 if (parameter_type == TypeManager.object_type ||
321 (val == null && !TypeManager.IsValueType (parameter_type)) ||
322 (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
323 builder.SetConstant (val);
325 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
329 base.ApplyAttributeBuilder (a, cb);
332 public virtual bool CheckAccessibility (InterfaceMemberBase member)
337 return member.ds.AsAccessible (parameter_type, member.ModFlags);
340 public override IResolveContext ResolveContext {
342 return resolve_context;
347 // Resolve is used in method definitions
349 public virtual bool Resolve (IResolveContext ec)
351 // HACK: to resolve attributes correctly
352 this.resolve_context = ec;
354 if (parameter_type != null)
357 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
361 parameter_type = texpr.Type;
364 TypeParameterExpr tparam = texpr as TypeParameterExpr;
365 if (tparam != null) {
366 IsTypeParameter = true;
367 constraints = tparam.TypeParameter.Constraints;
372 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
373 Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
374 texpr.GetSignatureForError ());
378 if ((modFlags & Parameter.Modifier.ISBYREF) != 0){
379 if (parameter_type == TypeManager.typed_reference_type ||
380 parameter_type == TypeManager.arg_iterator_type){
381 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
382 GetSignatureForError ());
387 if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer) {
388 Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
389 TypeManager.CSharpName (parameter_type));
396 public void ResolveVariable (ToplevelBlock toplevel, int idx)
398 if (toplevel.RootScope != null)
399 var = toplevel.RootScope.GetCapturedParameter (this);
401 var = new ParameterVariable (this, idx);
404 public Type ExternalType ()
406 if ((modFlags & Parameter.Modifier.ISBYREF) != 0)
407 return TypeManager.GetReferenceType (parameter_type);
409 return parameter_type;
412 public bool HasExtensionMethodModifier {
413 get { return (modFlags & Modifier.This) != 0; }
416 public Modifier ModFlags {
417 get { return modFlags & ~Modifier.This; }
420 public Type ParameterType {
422 return parameter_type;
425 parameter_type = value;
426 IsTypeParameter = false;
431 public GenericConstraints GenericConstraints {
438 ParameterAttributes Attributes {
440 return (modFlags & Modifier.OUT) == Modifier.OUT ?
441 ParameterAttributes.Out : ParameterAttributes.None;
445 // TODO: should be removed !!!!!!!
446 public static ParameterAttributes GetParameterAttributes (Modifier mod)
448 int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
449 switch ((Modifier) flags) {
451 return ParameterAttributes.None;
453 return ParameterAttributes.None;
455 return ParameterAttributes.Out;
456 case Modifier.PARAMS:
460 return ParameterAttributes.None;
463 public override AttributeTargets AttributeTargets {
465 return AttributeTargets.Parameter;
469 public virtual string GetSignatureForError ()
472 if (parameter_type != null)
473 type_name = TypeManager.CSharpName (parameter_type);
475 type_name = TypeName.GetSignatureForError ();
477 string mod = GetModifierSignature (modFlags);
479 return String.Concat (mod, ' ', type_name);
484 public static string GetModifierSignature (Modifier mod)
489 case Modifier.PARAMS:
493 case Modifier.ARGLIST:
502 public void IsClsCompliant ()
504 if (AttributeTester.IsClsCompliant (ExternalType ()))
507 Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
510 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
512 #if !GMCS_SOURCE || !MS_COMPATIBLE
513 // TODO: It should use mb.DefineGenericParameters
515 builder = cb.DefineParameter (index, Attributes, Name);
517 builder = mb.DefineParameter (index, Attributes, Name);
520 if (OptAttributes != null)
521 OptAttributes.Emit ();
524 public override string[] ValidAttributeTargets {
526 return attribute_targets;
530 protected class ParameterVariable : Variable
532 public readonly Parameter Parameter;
533 public readonly int Idx;
534 public readonly bool IsRef;
536 public ParameterVariable (Parameter par, int idx)
538 this.Parameter = par;
540 this.IsRef = (par.ModFlags & Parameter.Modifier.ISBYREF) != 0;
543 public override Type Type {
544 get { return Parameter.ParameterType; }
547 public override bool HasInstance {
548 get { return false; }
551 public override bool NeedsTemporary {
552 get { return false; }
555 public override void EmitInstance (EmitContext ec)
559 public override void Emit (EmitContext ec)
562 if (!ec.MethodIsStatic)
565 ParameterReference.EmitLdArg (ec.ig, arg_idx);
568 public override void EmitAssign (EmitContext ec)
571 if (!ec.MethodIsStatic)
575 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
577 ec.ig.Emit (OpCodes.Starg, arg_idx);
580 public override void EmitAddressOf (EmitContext ec)
584 if (!ec.MethodIsStatic)
589 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
591 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
594 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
596 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
601 public Parameter Clone ()
603 Parameter p = new Parameter (parameter_type, Name, ModFlags, attributes, Location);
604 p.IsTypeParameter = IsTypeParameter;
611 /// Represents the methods parameters
613 public class Parameters : ParameterData {
614 // Null object pattern
615 public Parameter [] FixedParameters;
616 public readonly bool HasArglist;
620 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
621 static readonly Parameter ArgList = new ArglistParameter ();
624 // public readonly TypeParameter[] TypeParameters;
627 private Parameters ()
629 FixedParameters = new Parameter[0];
630 types = new Type [0];
633 private Parameters (Parameter[] parameters, Type[] types)
635 FixedParameters = parameters;
637 count = types.Length;
640 public Parameters (params Parameter[] parameters)
642 if (parameters == null)
643 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
645 FixedParameters = parameters;
646 count = parameters.Length;
649 public Parameters (Parameter[] parameters, bool has_arglist):
652 HasArglist = has_arglist;
655 public static Parameters CreateFullyResolved (Parameter p)
657 return new Parameters (new Parameter [] { p }, new Type [] { p.ParameterType });
660 public static Parameters CreateFullyResolved (Parameter[] parameters, Type[] types)
662 return new Parameters (parameters, types);
666 /// Use this method when you merge compiler generated argument with user arguments
668 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
670 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
671 Type[] all_types = new Type[all_params.Length];
672 userParams.FixedParameters.CopyTo(all_params, 0);
673 userParams.Types.CopyTo (all_types, 0);
675 int last_filled = userParams.Count;
676 foreach (Parameter p in compilerParams) {
677 for (int i = 0; i < last_filled; ++i) {
678 while (p.Name == all_params [i].Name) {
679 p.Name = '_' + p.Name;
682 all_params [last_filled] = p;
683 all_types [last_filled] = p.ParameterType;
687 return new Parameters (all_params, all_types);
698 return HasArglist ? count + 1 : count;
703 // The property can be used after parameter types were resolved.
705 public Type ExtensionMethodType {
710 return FixedParameters [0].HasExtensionMethodModifier ?
715 public bool HasExtensionMethodType {
720 return FixedParameters [0].HasExtensionMethodModifier;
730 for (int i = 0; i < count; i++){
731 string base_name = FixedParameters [i].Name;
732 for (int j = i + 1; j < count; j++){
733 if (base_name != FixedParameters [j].Name)
736 Report.Error (100, FixedParameters [i].Location,
737 "The parameter name `{0}' is a duplicate", base_name);
746 /// Returns the paramenter information based on the name
748 public Parameter GetParameterByName (string name, out int idx)
757 foreach (Parameter par in FixedParameters){
758 if (par.Name == name){
767 public Parameter GetParameterByName (string name)
771 return GetParameterByName (name, out idx);
774 public bool Resolve (IResolveContext ec)
779 types = new Type [count];
786 for (int i = 0; i < FixedParameters.Length; ++i) {
787 p = FixedParameters [i];
788 if (!p.Resolve (ec)) {
792 types [i] = p.ExternalType ();
798 public void ResolveVariable (ToplevelBlock toplevel)
800 for (int i = 0; i < FixedParameters.Length; ++i) {
801 Parameter p = FixedParameters [i];
802 p.ResolveVariable (toplevel, i);
806 public CallingConventions CallingConvention
810 return CallingConventions.VarArgs;
812 return CallingConventions.Standard;
816 // Define each type attribute (in/out/ref) and
817 // the argument names.
818 public void ApplyAttributes (MethodBase builder)
823 MethodBuilder mb = builder as MethodBuilder;
824 ConstructorBuilder cb = builder as ConstructorBuilder;
826 for (int i = 0; i < FixedParameters.Length; i++) {
827 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
832 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
834 Parameters p = Clone ();
835 for (int i = 0; i < count; ++i) {
836 if (types[i].IsGenericType) {
837 Type[] gen_arguments_open = new Type [types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
838 Type[] gen_arguments = types[i].GetGenericArguments ();
839 for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
840 if (gen_arguments[ii].IsGenericParameter) {
841 Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
842 gen_arguments_open[ii] = t;
844 gen_arguments_open[ii] = gen_arguments[ii];
847 p.FixedParameters [i].ParameterType = p.types[i] =
848 types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
852 if (types[i].IsGenericParameter) {
853 Type gen_argument = argTypes[types[i].GenericParameterPosition];
854 p.FixedParameters[i].ParameterType = p.types[i] = gen_argument;
863 public void VerifyClsCompliance ()
865 foreach (Parameter p in FixedParameters)
869 public string GetSignatureForError ()
871 StringBuilder sb = new StringBuilder ("(");
873 for (int i = 0; i < FixedParameters.Length; ++i) {
874 sb.Append (FixedParameters[i].GetSignatureForError ());
875 if (i < FixedParameters.Length - 1)
883 sb.Append ("__arglist");
887 return sb.ToString ();
890 public Type[] Types {
895 // Dangerous, used by implicit lambda parameters
896 // only to workaround bad design
903 public Parameter this [int pos]
906 if (pos >= count && (HasArglist || HasParams)) {
907 if (HasArglist && (pos == 0 || pos >= count))
912 return FixedParameters [pos];
916 #region ParameterData Members
918 public Type ParameterType (int pos)
920 return this [pos].ExternalType ();
923 public bool HasParams {
928 for (int i = count; i != 0; --i) {
929 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
936 public string ParameterName (int pos)
938 return this [pos].Name;
941 public string ParameterDesc (int pos)
943 return this [pos].GetSignatureForError ();
946 public Parameter.Modifier ParameterModifier (int pos)
948 return this [pos].ModFlags;
951 public Parameters Clone ()
953 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
955 foreach (Parameter p in FixedParameters)
956 parameters_copy [i++] = p.Clone ();
957 Parameters ps = new Parameters (parameters_copy, HasArglist);
959 ps.types = (Type[])types.Clone ();