2 // parameter.cs: Parameter definition.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
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.HasSecurityAttribute) {
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 (FullNamedExpression 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 ca = TypeManager.param_array_attr;
183 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (TypeManager.param_array_type, Location, Type.EmptyTypes);
187 ca = new CustomAttributeBuilder (ci, new object [0]);
191 TypeManager.param_array_attr = ca;
194 builder.SetCustomAttribute (ca);
198 public class ArglistParameter : Parameter {
199 // Doesn't have proper type because it's never chosen for better conversion
200 public ArglistParameter () :
201 base (typeof (ArglistParameter), String.Empty, Parameter.Modifier.ARGLIST, null, Location.Null)
205 public override bool CheckAccessibility (InterfaceMemberBase member)
210 public override bool Resolve (IResolveContext ec)
215 public override string GetSignatureForError ()
222 /// Represents a single method parameter
224 public class Parameter : ParameterBase {
226 public enum Modifier : byte {
228 REF = REFMASK | ISBYREF,
229 OUT = OUTMASK | ISBYREF,
231 // This is a flag which says that it's either REF or OUT.
239 class ParameterVariable : Variable
241 readonly Parameter Parameter;
244 public ParameterVariable (Parameter par, int idx)
246 this.Parameter = par;
250 public override Type Type
252 get { return Parameter.ParameterType; }
255 public override bool HasInstance
257 get { return false; }
260 public override bool NeedsTemporary
262 get { return false; }
265 public override void EmitInstance (EmitContext ec)
269 public override void Emit (EmitContext ec)
272 if (!ec.MethodIsStatic)
275 ParameterReference.EmitLdArg (ec.ig, arg_idx);
278 public override void EmitAssign (EmitContext ec)
281 if (!ec.MethodIsStatic)
285 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
287 ec.ig.Emit (OpCodes.Starg, arg_idx);
290 public override void EmitAddressOf (EmitContext ec)
294 if (!ec.MethodIsStatic)
297 bool is_ref = (Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0;
300 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
302 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
305 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
307 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
312 static string[] attribute_targets = new string [] { "param" };
314 FullNamedExpression TypeName;
315 readonly Modifier modFlags;
317 public bool IsCaptured;
318 protected Type parameter_type;
319 public readonly Location Location;
321 IResolveContext resolve_context;
322 LocalVariableReference expr_tree_variable;
323 static TypeExpr parameter_expr_tree_type;
326 public Variable Variable {
331 public bool IsTypeParameter;
333 public bool IsTypeParameter {
339 throw new Exception ("You can not se TypeParameter in MCS");
344 public Parameter (FullNamedExpression type, string name, Modifier mod, Attributes attrs, Location loc)
345 : this (type.Type, name, mod, attrs, loc)
347 if (type == TypeManager.system_void_expr)
348 Report.Error (1536, loc, "Invalid parameter type `void'");
353 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
358 parameter_type = type;
362 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
364 if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
365 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
369 if (a.Type == TypeManager.param_array_type) {
370 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
374 if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
375 TypeManager.in_attribute_type != null && !OptAttributes.Contains (TypeManager.in_attribute_type)) {
376 Report.Error (662, a.Location,
377 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
381 if (a.Type == TypeManager.cls_compliant_attribute_type) {
382 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
385 // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
386 if (a.Type == TypeManager.default_parameter_value_attribute_type) {
387 object val = a.GetParameterDefaultValue ();
389 Type t = val.GetType ();
390 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
391 if (parameter_type == TypeManager.object_type) {
393 t = TypeManager.type_type;
395 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
396 TypeManager.CSharpName (t));
398 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
399 TypeManager.CSharpName (parameter_type)); ;
405 if (parameter_type == TypeManager.object_type ||
406 (val == null && !TypeManager.IsValueType (parameter_type)) ||
407 (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
408 builder.SetConstant (val);
410 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
414 base.ApplyAttributeBuilder (a, cb);
417 public virtual bool CheckAccessibility (InterfaceMemberBase member)
422 return member.IsAccessibleAs (parameter_type);
425 public override IResolveContext ResolveContext {
427 return resolve_context;
432 // Resolve is used in method definitions
434 public virtual bool Resolve (IResolveContext ec)
436 // HACK: to resolve attributes correctly
437 this.resolve_context = ec;
439 if (parameter_type != null)
442 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
446 parameter_type = texpr.Type;
449 TypeParameterExpr tparam = texpr as TypeParameterExpr;
450 if (tparam != null) {
451 IsTypeParameter = true;
456 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
457 Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
458 texpr.GetSignatureForError ());
462 if ((modFlags & Parameter.Modifier.ISBYREF) != 0){
463 if (parameter_type == TypeManager.typed_reference_type ||
464 parameter_type == TypeManager.arg_iterator_type){
465 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
466 GetSignatureForError ());
471 if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer) {
472 Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
473 TypeManager.CSharpName (parameter_type));
480 public void ResolveVariable (ToplevelBlock toplevel, int idx)
482 if (toplevel.RootScope != null)
483 var = toplevel.RootScope.GetCapturedParameter (this);
485 var = new ParameterVariable (this, idx);
488 public Type ExternalType ()
490 if ((modFlags & Parameter.Modifier.ISBYREF) != 0)
491 return TypeManager.GetReferenceType (parameter_type);
493 return parameter_type;
496 public bool HasExtensionMethodModifier {
497 get { return (modFlags & Modifier.This) != 0; }
500 public Modifier ModFlags {
501 get { return modFlags & ~Modifier.This; }
504 public Type ParameterType {
506 return parameter_type;
509 parameter_type = value;
510 IsTypeParameter = false;
514 ParameterAttributes Attributes {
516 return (modFlags & Modifier.OUT) == Modifier.OUT ?
517 ParameterAttributes.Out : ParameterAttributes.None;
521 // TODO: should be removed !!!!!!!
522 public static ParameterAttributes GetParameterAttributes (Modifier mod)
524 int flags = ((int) mod) & ~((int) Parameter.Modifier.ISBYREF);
525 switch ((Modifier) flags) {
527 return ParameterAttributes.None;
529 return ParameterAttributes.None;
531 return ParameterAttributes.Out;
532 case Modifier.PARAMS:
536 return ParameterAttributes.None;
539 public override AttributeTargets AttributeTargets {
541 return AttributeTargets.Parameter;
545 public virtual string GetSignatureForError ()
548 if (parameter_type != null)
549 type_name = TypeManager.CSharpName (parameter_type);
551 type_name = TypeName.GetSignatureForError ();
553 string mod = GetModifierSignature (modFlags);
555 return String.Concat (mod, ' ', type_name);
560 public static string GetModifierSignature (Modifier mod)
565 case Modifier.PARAMS:
569 case Modifier.ARGLIST:
578 public void IsClsCompliant ()
580 if (AttributeTester.IsClsCompliant (ExternalType ()))
583 Report.Error (3001, Location, "Argument type `{0}' is not CLS-compliant", GetSignatureForError ());
586 public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
588 #if !GMCS_SOURCE || !MS_COMPATIBLE
589 // TODO: It should use mb.DefineGenericParameters
591 builder = cb.DefineParameter (index, Attributes, Name);
593 builder = mb.DefineParameter (index, Attributes, Name);
596 if (OptAttributes != null)
597 OptAttributes.Emit ();
600 public override string[] ValidAttributeTargets {
602 return attribute_targets;
606 public Parameter Clone ()
608 Parameter p = new Parameter (parameter_type, Name, modFlags, attributes, Location);
609 p.IsTypeParameter = IsTypeParameter;
614 public ExpressionStatement CreateExpressionTreeVariable (EmitContext ec)
616 if ((modFlags & Modifier.ISBYREF) != 0)
617 Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
619 LocalInfo variable = ec.CurrentBlock.AddTemporaryVariable (
620 ResolveParameterExpressionType (ec, Location), Location);
621 variable.Resolve (ec);
623 expr_tree_variable = new LocalVariableReference (
624 ec.CurrentBlock, variable.Name, Location, variable, false);
626 ArrayList arguments = new ArrayList (2);
627 arguments.Add (new Argument (new TypeOf (
628 new TypeExpression (parameter_type, Location), Location)));
629 arguments.Add (new Argument (new StringConstant (Name, Location)));
630 return new SimpleAssign (ExpressionTreeVariableReference (),
631 Expression.CreateExpressionFactoryCall ("Parameter", null, arguments, Location));
634 public Expression ExpressionTreeVariableReference ()
636 return expr_tree_variable;
640 // System.Linq.Expressions.ParameterExpression type
642 public static TypeExpr ResolveParameterExpressionType (EmitContext ec, Location location)
644 if (parameter_expr_tree_type != null)
645 return parameter_expr_tree_type;
647 Type p_type = TypeManager.parameter_expression_type;
648 if (p_type == null) {
649 p_type = TypeManager.CoreLookupType ("System.Linq.Expressions", "ParameterExpression", Kind.Class, true);
650 TypeManager.parameter_expression_type = p_type;
653 parameter_expr_tree_type = new TypeExpression (p_type, location).
654 ResolveAsTypeTerminal (ec, false);
656 return parameter_expr_tree_type;
661 /// Represents the methods parameters
663 public class Parameters : ParameterData {
664 // Null object pattern
665 public readonly Parameter [] FixedParameters;
666 public readonly bool HasArglist;
670 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
671 static readonly Parameter ArgList = new ArglistParameter ();
674 // public readonly TypeParameter[] TypeParameters;
677 private Parameters ()
679 FixedParameters = new Parameter[0];
680 types = new Type [0];
683 private Parameters (Parameter[] parameters, Type[] types)
685 FixedParameters = parameters;
687 count = types.Length;
690 public Parameters (params Parameter[] parameters)
692 if (parameters == null)
693 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
695 FixedParameters = parameters;
696 count = parameters.Length;
699 public Parameters (Parameter[] parameters, bool has_arglist):
702 HasArglist = has_arglist;
705 public static Parameters CreateFullyResolved (Parameter p)
707 return new Parameters (new Parameter [] { p }, new Type [] { p.ParameterType });
710 public static Parameters CreateFullyResolved (Parameter[] parameters, Type[] types)
712 return new Parameters (parameters, types);
716 /// Use this method when you merge compiler generated argument with user arguments
718 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
720 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
721 Type[] all_types = new Type[all_params.Length];
722 userParams.FixedParameters.CopyTo(all_params, 0);
723 userParams.Types.CopyTo (all_types, 0);
725 int last_filled = userParams.Count;
726 foreach (Parameter p in compilerParams) {
727 for (int i = 0; i < last_filled; ++i) {
728 while (p.Name == all_params [i].Name) {
729 p.Name = '_' + p.Name;
732 all_params [last_filled] = p;
733 all_types [last_filled] = p.ParameterType;
737 return new Parameters (all_params, all_types);
748 return HasArglist ? count + 1 : count;
753 // The property can be used after parameter types were resolved.
755 public Type ExtensionMethodType {
760 return FixedParameters [0].HasExtensionMethodModifier ?
765 public bool HasExtensionMethodType {
770 return FixedParameters [0].HasExtensionMethodModifier;
780 for (int i = 0; i < count; i++){
781 string base_name = FixedParameters [i].Name;
782 for (int j = i + 1; j < count; j++){
783 if (base_name != FixedParameters [j].Name)
786 Report.Error (100, FixedParameters [i].Location,
787 "The parameter name `{0}' is a duplicate", base_name);
796 /// Returns the paramenter information based on the name
798 public Parameter GetParameterByName (string name, out int idx)
807 foreach (Parameter par in FixedParameters){
808 if (par.Name == name){
817 public Parameter GetParameterByName (string name)
821 return GetParameterByName (name, out idx);
824 public bool Resolve (IResolveContext ec)
829 types = new Type [count];
836 for (int i = 0; i < FixedParameters.Length; ++i) {
837 p = FixedParameters [i];
838 if (!p.Resolve (ec)) {
842 types [i] = p.ExternalType ();
848 public void ResolveVariable (ToplevelBlock toplevel)
850 for (int i = 0; i < FixedParameters.Length; ++i) {
851 Parameter p = FixedParameters [i];
852 p.ResolveVariable (toplevel, i);
856 public CallingConventions CallingConvention
860 return CallingConventions.VarArgs;
862 return CallingConventions.Standard;
866 // Define each type attribute (in/out/ref) and
867 // the argument names.
868 public void ApplyAttributes (MethodBase builder)
873 MethodBuilder mb = builder as MethodBuilder;
874 ConstructorBuilder cb = builder as ConstructorBuilder;
876 for (int i = 0; i < FixedParameters.Length; i++) {
877 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
882 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
884 Parameters p = Clone ();
885 for (int i = 0; i < count; ++i) {
886 if (types[i].IsGenericType) {
887 Type[] gen_arguments_open = new Type [types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
888 Type[] gen_arguments = types[i].GetGenericArguments ();
889 for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
890 if (gen_arguments[ii].IsGenericParameter) {
891 Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
892 gen_arguments_open[ii] = t;
894 gen_arguments_open[ii] = gen_arguments[ii];
897 p.FixedParameters [i].ParameterType = p.types[i] =
898 types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
902 if (types[i].IsGenericParameter) {
903 Type gen_argument = argTypes[types[i].GenericParameterPosition];
904 p.FixedParameters[i].ParameterType = p.types[i] = gen_argument;
913 public void VerifyClsCompliance ()
915 foreach (Parameter p in FixedParameters)
919 public string GetSignatureForError ()
921 StringBuilder sb = new StringBuilder ("(");
923 for (int i = 0; i < FixedParameters.Length; ++i) {
924 sb.Append (FixedParameters[i].GetSignatureForError ());
925 if (i < FixedParameters.Length - 1)
933 sb.Append ("__arglist");
937 return sb.ToString ();
940 public Type[] Types {
945 // Dangerous, used by implicit lambda parameters
946 // only to workaround bad design
953 public Parameter this [int pos]
956 if (pos >= count && (HasArglist || HasParams)) {
957 if (HasArglist && (pos == 0 || pos >= count))
962 return FixedParameters [pos];
966 #region ParameterData Members
968 public Type ParameterType (int pos)
970 return this [pos].ExternalType ();
973 public bool HasParams {
978 for (int i = count; i != 0; --i) {
979 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
986 public string ParameterName (int pos)
988 return this [pos].Name;
991 public string ParameterDesc (int pos)
993 return this [pos].GetSignatureForError ();
996 public Parameter.Modifier ParameterModifier (int pos)
998 return this [pos].ModFlags;
1001 public Expression CreateExpressionTree (EmitContext ec, Location loc)
1003 ArrayList initializers = new ArrayList (count);
1004 foreach (Parameter p in FixedParameters) {
1006 // Each parameter expression is stored to local variable
1007 // to save some memory when referenced later.
1009 StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec));
1010 if (se.Resolve (ec))
1011 ec.CurrentBlock.AddScopeStatement (se);
1013 initializers.Add (p.ExpressionTreeVariableReference ());
1016 return new ArrayCreation (
1017 Parameter.ResolveParameterExpressionType (ec, loc),
1018 "[]", initializers, loc);
1021 public Parameters Clone ()
1023 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
1025 foreach (Parameter p in FixedParameters)
1026 parameters_copy [i++] = p.Clone ();
1027 Parameters ps = new Parameters (parameters_copy, HasArglist);
1029 ps.types = (Type[])types.Clone ();