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;
239 LocalVariableReference expr_tree_variable;
240 static TypeExpr parameter_expr_tree_type;
243 public Variable Variable {
248 public bool IsTypeParameter;
249 GenericConstraints constraints;
251 public bool IsTypeParameter {
257 throw new Exception ("You can not se TypeParameter in MCS");
262 public Parameter (Expression type, string name, Modifier mod, Attributes attrs, Location loc)
263 : this (type.Type, name, mod, attrs, loc)
265 if (type == TypeManager.system_void_expr)
266 Report.Error (1536, loc, "Invalid parameter type `void'");
271 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
276 parameter_type = type;
280 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
282 if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
283 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
287 if (a.Type == TypeManager.param_array_type) {
288 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
292 if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
293 !OptAttributes.Contains (TypeManager.in_attribute_type)) {
294 Report.Error (662, a.Location,
295 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
299 if (a.Type == TypeManager.cls_compliant_attribute_type) {
300 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
303 // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
304 if (a.Type == TypeManager.default_parameter_value_attribute_type) {
305 object val = a.GetParameterDefaultValue ();
307 Type t = val.GetType ();
308 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
309 if (parameter_type == TypeManager.object_type) {
311 t = TypeManager.type_type;
313 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
314 TypeManager.CSharpName (t));
316 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
317 TypeManager.CSharpName (parameter_type)); ;
323 if (parameter_type == TypeManager.object_type ||
324 (val == null && !TypeManager.IsValueType (parameter_type)) ||
325 (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
326 builder.SetConstant (val);
328 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
332 base.ApplyAttributeBuilder (a, cb);
335 public virtual bool CheckAccessibility (InterfaceMemberBase member)
340 return member.IsAccessibleAs (parameter_type);
343 public override IResolveContext ResolveContext {
345 return resolve_context;
350 // Resolve is used in method definitions
352 public virtual bool Resolve (IResolveContext ec)
354 // HACK: to resolve attributes correctly
355 this.resolve_context = ec;
357 if (parameter_type != null)
360 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
364 parameter_type = texpr.Type;
367 TypeParameterExpr tparam = texpr as TypeParameterExpr;
368 if (tparam != null) {
369 IsTypeParameter = true;
370 constraints = tparam.TypeParameter.Constraints;
375 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
376 Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
377 texpr.GetSignatureForError ());
381 if ((modFlags & Parameter.Modifier.ISBYREF) != 0){
382 if (parameter_type == TypeManager.typed_reference_type ||
383 parameter_type == TypeManager.arg_iterator_type){
384 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
385 GetSignatureForError ());
390 if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer) {
391 Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
392 TypeManager.CSharpName (parameter_type));
399 public void ResolveVariable (ToplevelBlock toplevel, int idx)
401 if (toplevel.RootScope != null)
402 var = toplevel.RootScope.GetCapturedParameter (this);
404 var = new ParameterVariable (this, idx);
407 public Type ExternalType ()
409 if ((modFlags & Parameter.Modifier.ISBYREF) != 0)
410 return TypeManager.GetReferenceType (parameter_type);
412 return parameter_type;
415 public bool HasExtensionMethodModifier {
416 get { return (modFlags & Modifier.This) != 0; }
419 public Modifier ModFlags {
420 get { return modFlags & ~Modifier.This; }
423 public Type ParameterType {
425 return parameter_type;
428 parameter_type = value;
429 IsTypeParameter = false;
434 public GenericConstraints GenericConstraints {
441 ParameterAttributes Attributes {
443 return (modFlags & Modifier.OUT) == Modifier.OUT ?
444 ParameterAttributes.Out : ParameterAttributes.None;
448 // TODO: should be removed !!!!!!!
449 public static ParameterAttributes GetParameterAttributes (Modifier mod)
451 int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
452 switch ((Modifier) flags) {
454 return ParameterAttributes.None;
456 return ParameterAttributes.None;
458 return ParameterAttributes.Out;
459 case Modifier.PARAMS:
463 return ParameterAttributes.None;
466 public override AttributeTargets AttributeTargets {
468 return AttributeTargets.Parameter;
472 public virtual string GetSignatureForError ()
475 if (parameter_type != null)
476 type_name = TypeManager.CSharpName (parameter_type);
478 type_name = TypeName.GetSignatureForError ();
480 string mod = GetModifierSignature (modFlags);
482 return String.Concat (mod, ' ', type_name);
487 public static string GetModifierSignature (Modifier mod)
492 case Modifier.PARAMS:
496 case Modifier.ARGLIST:
505 public void IsClsCompliant ()
507 if (AttributeTester.IsClsCompliant (ExternalType ()))
510 Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
513 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
515 #if !GMCS_SOURCE || !MS_COMPATIBLE
516 // TODO: It should use mb.DefineGenericParameters
518 builder = cb.DefineParameter (index, Attributes, Name);
520 builder = mb.DefineParameter (index, Attributes, Name);
523 if (OptAttributes != null)
524 OptAttributes.Emit ();
527 public override string[] ValidAttributeTargets {
529 return attribute_targets;
533 protected class ParameterVariable : Variable
535 public readonly Parameter Parameter;
536 public readonly int Idx;
537 public readonly bool IsRef;
539 public ParameterVariable (Parameter par, int idx)
541 this.Parameter = par;
543 this.IsRef = (par.ModFlags & Parameter.Modifier.ISBYREF) != 0;
546 public override Type Type {
547 get { return Parameter.ParameterType; }
550 public override bool HasInstance {
551 get { return false; }
554 public override bool NeedsTemporary {
555 get { return false; }
558 public override void EmitInstance (EmitContext ec)
562 public override void Emit (EmitContext ec)
565 if (!ec.MethodIsStatic)
568 ParameterReference.EmitLdArg (ec.ig, arg_idx);
571 public override void EmitAssign (EmitContext ec)
574 if (!ec.MethodIsStatic)
578 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
580 ec.ig.Emit (OpCodes.Starg, arg_idx);
583 public override void EmitAddressOf (EmitContext ec)
587 if (!ec.MethodIsStatic)
592 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
594 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
597 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
599 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
604 public Parameter Clone ()
606 Parameter p = new Parameter (parameter_type, Name, ModFlags, attributes, Location);
607 p.IsTypeParameter = IsTypeParameter;
612 public ExpressionStatement CreateExpressionTreeVariable (EmitContext ec)
614 if ((modFlags & Modifier.ISBYREF) != 0)
615 Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
617 LocalInfo variable = ec.CurrentBlock.AddTemporaryVariable (
618 ResolveParameterExpressionType (ec, Location), Location);
619 variable.Resolve (ec);
621 expr_tree_variable = new LocalVariableReference (
622 ec.CurrentBlock, variable.Name, Location, variable, false);
624 ArrayList arguments = new ArrayList (2);
625 arguments.Add (new Argument (new TypeOf (
626 new TypeExpression (parameter_type, Location), Location)));
627 arguments.Add (new Argument (new StringConstant (Name, Location)));
628 return new Assign (ExpressionTreeVariableReference (),
629 Expression.CreateExpressionFactoryCall ("Parameter", null, arguments, Location));
632 public Expression ExpressionTreeVariableReference ()
634 return expr_tree_variable;
638 // System.Linq.Expressions.ParameterExpression type
640 public static TypeExpr ResolveParameterExpressionType (EmitContext ec, Location location)
642 if (parameter_expr_tree_type != null)
643 return parameter_expr_tree_type;
645 parameter_expr_tree_type = new TypeExpression (LinqExpression.parameter_expression_type, location).
646 ResolveAsTypeTerminal (ec, false);
648 return parameter_expr_tree_type;
653 /// Represents the methods parameters
655 public class Parameters : ParameterData {
656 // Null object pattern
657 public Parameter [] FixedParameters;
658 public readonly bool HasArglist;
662 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
663 static readonly Parameter ArgList = new ArglistParameter ();
666 // public readonly TypeParameter[] TypeParameters;
669 private Parameters ()
671 FixedParameters = new Parameter[0];
672 types = new Type [0];
675 private Parameters (Parameter[] parameters, Type[] types)
677 FixedParameters = parameters;
679 count = types.Length;
682 public Parameters (params Parameter[] parameters)
684 if (parameters == null)
685 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
687 FixedParameters = parameters;
688 count = parameters.Length;
691 public Parameters (Parameter[] parameters, bool has_arglist):
694 HasArglist = has_arglist;
697 public static Parameters CreateFullyResolved (Parameter p)
699 return new Parameters (new Parameter [] { p }, new Type [] { p.ParameterType });
702 public static Parameters CreateFullyResolved (Parameter[] parameters, Type[] types)
704 return new Parameters (parameters, types);
708 /// Use this method when you merge compiler generated argument with user arguments
710 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
712 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
713 Type[] all_types = new Type[all_params.Length];
714 userParams.FixedParameters.CopyTo(all_params, 0);
715 userParams.Types.CopyTo (all_types, 0);
717 int last_filled = userParams.Count;
718 foreach (Parameter p in compilerParams) {
719 for (int i = 0; i < last_filled; ++i) {
720 while (p.Name == all_params [i].Name) {
721 p.Name = '_' + p.Name;
724 all_params [last_filled] = p;
725 all_types [last_filled] = p.ParameterType;
729 return new Parameters (all_params, all_types);
740 return HasArglist ? count + 1 : count;
745 // The property can be used after parameter types were resolved.
747 public Type ExtensionMethodType {
752 return FixedParameters [0].HasExtensionMethodModifier ?
757 public bool HasExtensionMethodType {
762 return FixedParameters [0].HasExtensionMethodModifier;
772 for (int i = 0; i < count; i++){
773 string base_name = FixedParameters [i].Name;
774 for (int j = i + 1; j < count; j++){
775 if (base_name != FixedParameters [j].Name)
778 Report.Error (100, FixedParameters [i].Location,
779 "The parameter name `{0}' is a duplicate", base_name);
788 /// Returns the paramenter information based on the name
790 public Parameter GetParameterByName (string name, out int idx)
799 foreach (Parameter par in FixedParameters){
800 if (par.Name == name){
809 public Parameter GetParameterByName (string name)
813 return GetParameterByName (name, out idx);
816 public bool Resolve (IResolveContext ec)
821 types = new Type [count];
828 for (int i = 0; i < FixedParameters.Length; ++i) {
829 p = FixedParameters [i];
830 if (!p.Resolve (ec)) {
834 types [i] = p.ExternalType ();
840 public void ResolveVariable (ToplevelBlock toplevel)
842 for (int i = 0; i < FixedParameters.Length; ++i) {
843 Parameter p = FixedParameters [i];
844 p.ResolveVariable (toplevel, i);
848 public CallingConventions CallingConvention
852 return CallingConventions.VarArgs;
854 return CallingConventions.Standard;
858 // Define each type attribute (in/out/ref) and
859 // the argument names.
860 public void ApplyAttributes (MethodBase builder)
865 MethodBuilder mb = builder as MethodBuilder;
866 ConstructorBuilder cb = builder as ConstructorBuilder;
868 for (int i = 0; i < FixedParameters.Length; i++) {
869 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
874 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
876 Parameters p = Clone ();
877 for (int i = 0; i < count; ++i) {
878 if (types[i].IsGenericType) {
879 Type[] gen_arguments_open = new Type [types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
880 Type[] gen_arguments = types[i].GetGenericArguments ();
881 for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
882 if (gen_arguments[ii].IsGenericParameter) {
883 Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
884 gen_arguments_open[ii] = t;
886 gen_arguments_open[ii] = gen_arguments[ii];
889 p.FixedParameters [i].ParameterType = p.types[i] =
890 types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
894 if (types[i].IsGenericParameter) {
895 Type gen_argument = argTypes[types[i].GenericParameterPosition];
896 p.FixedParameters[i].ParameterType = p.types[i] = gen_argument;
905 public void VerifyClsCompliance ()
907 foreach (Parameter p in FixedParameters)
911 public string GetSignatureForError ()
913 StringBuilder sb = new StringBuilder ("(");
915 for (int i = 0; i < FixedParameters.Length; ++i) {
916 sb.Append (FixedParameters[i].GetSignatureForError ());
917 if (i < FixedParameters.Length - 1)
925 sb.Append ("__arglist");
929 return sb.ToString ();
932 public Type[] Types {
937 // Dangerous, used by implicit lambda parameters
938 // only to workaround bad design
945 public Parameter this [int pos]
948 if (pos >= count && (HasArglist || HasParams)) {
949 if (HasArglist && (pos == 0 || pos >= count))
954 return FixedParameters [pos];
958 #region ParameterData Members
960 public Type ParameterType (int pos)
962 return this [pos].ExternalType ();
965 public bool HasParams {
970 for (int i = count; i != 0; --i) {
971 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
978 public string ParameterName (int pos)
980 return this [pos].Name;
983 public string ParameterDesc (int pos)
985 return this [pos].GetSignatureForError ();
988 public Parameter.Modifier ParameterModifier (int pos)
990 return this [pos].ModFlags;
993 public Expression CreateExpressionTree (EmitContext ec, Location loc)
995 ArrayList initializers = new ArrayList (count);
996 foreach (Parameter p in FixedParameters) {
998 // Each parameter expression is stored to local variable
999 // to save some memory when referenced later.
1001 StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec));
1002 if (se.Resolve (ec))
1003 ec.CurrentBlock.AddScopeStatement (se);
1005 initializers.Add (p.ExpressionTreeVariableReference ());
1008 return new ArrayCreation (
1009 Parameter.ResolveParameterExpressionType (ec, loc),
1010 "[]", initializers, loc);
1013 public Parameters Clone ()
1015 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
1017 foreach (Parameter p in FixedParameters)
1018 parameters_copy [i++] = p.Clone ();
1019 Parameters ps = new Parameters (parameters_copy, HasArglist);
1021 ps.types = (Type[])types.Clone ();