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 static string[] attribute_targets = new string [] { "param" };
241 FullNamedExpression TypeName;
242 readonly Modifier modFlags;
244 public bool IsCaptured;
245 protected Type parameter_type;
246 public readonly Location Location;
248 IResolveContext resolve_context;
249 LocalVariableReference expr_tree_variable;
250 static TypeExpr parameter_expr_tree_type;
253 public Variable Variable {
258 public bool IsTypeParameter;
260 public bool IsTypeParameter {
266 throw new Exception ("You can not se TypeParameter in MCS");
271 public Parameter (FullNamedExpression type, string name, Modifier mod, Attributes attrs, Location loc)
272 : this (type.Type, name, mod, attrs, loc)
274 if (type == TypeManager.system_void_expr)
275 Report.Error (1536, loc, "Invalid parameter type `void'");
280 public Parameter (Type type, string name, Modifier mod, Attributes attrs, Location loc)
285 parameter_type = type;
289 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
291 if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT) {
292 Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
296 if (a.Type == TypeManager.param_array_type) {
297 Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
301 if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
302 TypeManager.in_attribute_type != null && !OptAttributes.Contains (TypeManager.in_attribute_type)) {
303 Report.Error (662, a.Location,
304 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
308 if (a.Type == TypeManager.cls_compliant_attribute_type) {
309 Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
312 // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
313 if (a.Type == TypeManager.default_parameter_value_attribute_type) {
314 object val = a.GetParameterDefaultValue ();
316 Type t = val.GetType ();
317 if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
318 if (parameter_type == TypeManager.object_type) {
320 t = TypeManager.type_type;
322 Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultValue attribute",
323 TypeManager.CSharpName (t));
325 Report.Error (1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
326 TypeManager.CSharpName (parameter_type)); ;
332 if (parameter_type == TypeManager.object_type ||
333 (val == null && !TypeManager.IsValueType (parameter_type)) ||
334 (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
335 builder.SetConstant (val);
337 Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
341 base.ApplyAttributeBuilder (a, cb);
344 public virtual bool CheckAccessibility (InterfaceMemberBase member)
349 return member.IsAccessibleAs (parameter_type);
352 public override IResolveContext ResolveContext {
354 return resolve_context;
359 // Resolve is used in method definitions
361 public virtual bool Resolve (IResolveContext ec)
363 // HACK: to resolve attributes correctly
364 this.resolve_context = ec;
366 if (parameter_type != null)
369 TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
373 parameter_type = texpr.Type;
376 TypeParameterExpr tparam = texpr as TypeParameterExpr;
377 if (tparam != null) {
378 IsTypeParameter = true;
383 if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
384 Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
385 texpr.GetSignatureForError ());
389 if ((modFlags & Parameter.Modifier.ISBYREF) != 0){
390 if (parameter_type == TypeManager.typed_reference_type ||
391 parameter_type == TypeManager.arg_iterator_type){
392 Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
393 GetSignatureForError ());
398 if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer) {
399 Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
400 TypeManager.CSharpName (parameter_type));
407 public void ResolveVariable (ToplevelBlock toplevel, int idx)
409 if (toplevel.RootScope != null)
410 var = toplevel.RootScope.GetCapturedParameter (this);
412 var = new ParameterVariable (this, idx);
415 public Type ExternalType ()
417 if ((modFlags & Parameter.Modifier.ISBYREF) != 0)
418 return TypeManager.GetReferenceType (parameter_type);
420 return parameter_type;
423 public bool HasExtensionMethodModifier {
424 get { return (modFlags & Modifier.This) != 0; }
427 public Modifier ModFlags {
428 get { return modFlags & ~Modifier.This; }
431 public Type ParameterType {
433 return parameter_type;
436 parameter_type = value;
437 IsTypeParameter = false;
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 SimpleAssign (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 Type p_type = TypeManager.parameter_expression_type;
646 if (p_type == null) {
647 p_type = TypeManager.CoreLookupType ("System.Linq.Expressions", "ParameterExpression", Kind.Class, true);
648 TypeManager.parameter_expression_type = p_type;
651 parameter_expr_tree_type = new TypeExpression (p_type, location).
652 ResolveAsTypeTerminal (ec, false);
654 return parameter_expr_tree_type;
659 /// Represents the methods parameters
661 public class Parameters : ParameterData {
662 // Null object pattern
663 public Parameter [] FixedParameters;
664 public readonly bool HasArglist;
668 public static readonly Parameters EmptyReadOnlyParameters = new Parameters ();
669 static readonly Parameter ArgList = new ArglistParameter ();
672 // public readonly TypeParameter[] TypeParameters;
675 private Parameters ()
677 FixedParameters = new Parameter[0];
678 types = new Type [0];
681 private Parameters (Parameter[] parameters, Type[] types)
683 FixedParameters = parameters;
685 count = types.Length;
688 public Parameters (params Parameter[] parameters)
690 if (parameters == null)
691 throw new ArgumentException ("Use EmptyReadOnlyPatameters");
693 FixedParameters = parameters;
694 count = parameters.Length;
697 public Parameters (Parameter[] parameters, bool has_arglist):
700 HasArglist = has_arglist;
703 public static Parameters CreateFullyResolved (Parameter p)
705 return new Parameters (new Parameter [] { p }, new Type [] { p.ParameterType });
708 public static Parameters CreateFullyResolved (Parameter[] parameters, Type[] types)
710 return new Parameters (parameters, types);
714 /// Use this method when you merge compiler generated argument with user arguments
716 public static Parameters MergeGenerated (Parameters userParams, params Parameter[] compilerParams)
718 Parameter[] all_params = new Parameter [userParams.count + compilerParams.Length];
719 Type[] all_types = new Type[all_params.Length];
720 userParams.FixedParameters.CopyTo(all_params, 0);
721 userParams.Types.CopyTo (all_types, 0);
723 int last_filled = userParams.Count;
724 foreach (Parameter p in compilerParams) {
725 for (int i = 0; i < last_filled; ++i) {
726 while (p.Name == all_params [i].Name) {
727 p.Name = '_' + p.Name;
730 all_params [last_filled] = p;
731 all_types [last_filled] = p.ParameterType;
735 return new Parameters (all_params, all_types);
746 return HasArglist ? count + 1 : count;
751 // The property can be used after parameter types were resolved.
753 public Type ExtensionMethodType {
758 return FixedParameters [0].HasExtensionMethodModifier ?
763 public bool HasExtensionMethodType {
768 return FixedParameters [0].HasExtensionMethodModifier;
778 for (int i = 0; i < count; i++){
779 string base_name = FixedParameters [i].Name;
780 for (int j = i + 1; j < count; j++){
781 if (base_name != FixedParameters [j].Name)
784 Report.Error (100, FixedParameters [i].Location,
785 "The parameter name `{0}' is a duplicate", base_name);
794 /// Returns the paramenter information based on the name
796 public Parameter GetParameterByName (string name, out int idx)
805 foreach (Parameter par in FixedParameters){
806 if (par.Name == name){
815 public Parameter GetParameterByName (string name)
819 return GetParameterByName (name, out idx);
822 public bool Resolve (IResolveContext ec)
827 types = new Type [count];
834 for (int i = 0; i < FixedParameters.Length; ++i) {
835 p = FixedParameters [i];
836 if (!p.Resolve (ec)) {
840 types [i] = p.ExternalType ();
846 public void ResolveVariable (ToplevelBlock toplevel)
848 for (int i = 0; i < FixedParameters.Length; ++i) {
849 Parameter p = FixedParameters [i];
850 p.ResolveVariable (toplevel, i);
854 public CallingConventions CallingConvention
858 return CallingConventions.VarArgs;
860 return CallingConventions.Standard;
864 // Define each type attribute (in/out/ref) and
865 // the argument names.
866 public void ApplyAttributes (MethodBase builder)
871 MethodBuilder mb = builder as MethodBuilder;
872 ConstructorBuilder cb = builder as ConstructorBuilder;
874 for (int i = 0; i < FixedParameters.Length; i++) {
875 FixedParameters [i].ApplyAttributes (mb, cb, i + 1);
880 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
882 Parameters p = Clone ();
883 for (int i = 0; i < count; ++i) {
884 if (types[i].IsGenericType) {
885 Type[] gen_arguments_open = new Type [types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
886 Type[] gen_arguments = types[i].GetGenericArguments ();
887 for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
888 if (gen_arguments[ii].IsGenericParameter) {
889 Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
890 gen_arguments_open[ii] = t;
892 gen_arguments_open[ii] = gen_arguments[ii];
895 p.FixedParameters [i].ParameterType = p.types[i] =
896 types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
900 if (types[i].IsGenericParameter) {
901 Type gen_argument = argTypes[types[i].GenericParameterPosition];
902 p.FixedParameters[i].ParameterType = p.types[i] = gen_argument;
911 public void VerifyClsCompliance ()
913 foreach (Parameter p in FixedParameters)
917 public string GetSignatureForError ()
919 StringBuilder sb = new StringBuilder ("(");
921 for (int i = 0; i < FixedParameters.Length; ++i) {
922 sb.Append (FixedParameters[i].GetSignatureForError ());
923 if (i < FixedParameters.Length - 1)
931 sb.Append ("__arglist");
935 return sb.ToString ();
938 public Type[] Types {
943 // Dangerous, used by implicit lambda parameters
944 // only to workaround bad design
951 public Parameter this [int pos]
954 if (pos >= count && (HasArglist || HasParams)) {
955 if (HasArglist && (pos == 0 || pos >= count))
960 return FixedParameters [pos];
964 #region ParameterData Members
966 public Type ParameterType (int pos)
968 return this [pos].ExternalType ();
971 public bool HasParams {
976 for (int i = count; i != 0; --i) {
977 if ((FixedParameters [i - 1].ModFlags & Parameter.Modifier.PARAMS) != 0)
984 public string ParameterName (int pos)
986 return this [pos].Name;
989 public string ParameterDesc (int pos)
991 return this [pos].GetSignatureForError ();
994 public Parameter.Modifier ParameterModifier (int pos)
996 return this [pos].ModFlags;
999 public Expression CreateExpressionTree (EmitContext ec, Location loc)
1001 ArrayList initializers = new ArrayList (count);
1002 foreach (Parameter p in FixedParameters) {
1004 // Each parameter expression is stored to local variable
1005 // to save some memory when referenced later.
1007 StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec));
1008 if (se.Resolve (ec))
1009 ec.CurrentBlock.AddScopeStatement (se);
1011 initializers.Add (p.ExpressionTreeVariableReference ());
1014 return new ArrayCreation (
1015 Parameter.ResolveParameterExpressionType (ec, loc),
1016 "[]", initializers, loc);
1019 public Parameters Clone ()
1021 Parameter [] parameters_copy = new Parameter [FixedParameters.Length];
1023 foreach (Parameter p in FixedParameters)
1024 parameters_copy [i++] = p.Clone ();
1025 Parameters ps = new Parameters (parameters_copy, HasArglist);
1027 ps.types = (Type[])types.Clone ();