2 // argument.cs: Argument expressions
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
17 using IKVM.Reflection.Emit;
19 using System.Reflection.Emit;
25 // Argument expression used for invocation
29 public enum AType : byte
32 Ref = 1, // ref modifier used
33 Out = 2, // out modifier used
34 Default = 3, // argument created from default parameter value
35 DynamicTypeName = 4, // System.Type argument for dynamic binding
36 ExtensionType = 5, // Instance expression inserted as the first argument
38 // Conditional instance expression inserted as the first argument
39 ExtensionTypeConditionalAccess = 5 | ConditionalAccessFlag,
41 ConditionalAccessFlag = 1 << 7
44 public readonly AType ArgType;
45 public Expression Expr;
47 public Argument (Expression expr, AType type)
53 public Argument (Expression expr)
61 get { return ArgType == AType.Ref || ArgType == AType.Out; }
64 public bool IsDefaultArgument {
65 get { return ArgType == AType.Default; }
68 public bool IsExtensionType {
70 return (ArgType & AType.ExtensionType) == AType.ExtensionType;
74 public Parameter.Modifier Modifier {
78 return Parameter.Modifier.OUT;
81 return Parameter.Modifier.REF;
84 return Parameter.Modifier.NONE;
89 public TypeSpec Type {
90 get { return Expr.Type; }
95 public Argument Clone (Expression expr)
97 Argument a = (Argument) MemberwiseClone ();
102 public Argument Clone (CloneContext clonectx)
104 return Clone (Expr.Clone (clonectx));
107 public virtual Expression CreateExpressionTree (ResolveContext ec)
109 if (ArgType == AType.Default)
110 ec.Report.Error (854, Expr.Location, "An expression tree cannot contain an invocation which uses optional parameter");
112 return Expr.CreateExpressionTree (ec);
116 public virtual void Emit (EmitContext ec)
119 if (ArgType == AType.ExtensionTypeConditionalAccess) {
120 var ie = new InstanceEmitter (Expr, false);
129 AddressOp mode = AddressOp.Store;
130 if (ArgType == AType.Ref)
131 mode |= AddressOp.Load;
133 IMemoryLocation ml = (IMemoryLocation) Expr;
134 ml.AddressOf (ec, mode);
137 public Argument EmitToField (EmitContext ec, bool cloneResult)
139 var res = Expr.EmitToField (ec);
140 if (cloneResult && res != Expr)
141 return new Argument (res, ArgType);
147 public void FlowAnalysis (FlowAnalysisContext fc)
149 if (ArgType == AType.Out) {
150 var vr = Expr as VariableReference;
152 if (vr.VariableInfo != null)
153 fc.SetVariableAssigned (vr.VariableInfo);
158 var fe = Expr as FieldExpr;
160 fe.SetFieldAssigned (fc);
167 Expr.FlowAnalysis (fc);
170 public string GetSignatureForError ()
172 if (Expr.eclass == ExprClass.MethodGroup)
173 return Expr.ExprClassName;
175 return Expr.Type.GetSignatureForError ();
178 public bool ResolveMethodGroup (ResolveContext ec)
180 SimpleName sn = Expr as SimpleName;
182 Expr = sn.GetMethodGroup ();
184 // FIXME: csc doesn't report any error if you try to use `ref' or
185 // `out' in a delegate creation expression.
186 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
193 public void Resolve (ResolveContext ec)
195 // Verify that the argument is readable
196 if (ArgType != AType.Out)
197 Expr = Expr.Resolve (ec);
199 // Verify that the argument is writeable
200 if (Expr != null && IsByRef)
201 Expr = Expr.ResolveLValue (ec, EmptyExpression.OutAccess);
204 Expr = ErrorExpression.Instance;
208 public class MovableArgument : Argument
210 LocalTemporary variable;
212 public MovableArgument (Argument arg)
213 : this (arg.Expr, arg.ArgType)
217 protected MovableArgument (Expression expr, AType modifier)
218 : base (expr, modifier)
222 public override void Emit (EmitContext ec)
224 // TODO: Should guard against multiple emits
227 // Release temporary variable when used
228 if (variable != null)
229 variable.Release (ec);
232 public void EmitToVariable (EmitContext ec)
234 var type = Expr.Type;
236 var ml = (IMemoryLocation) Expr;
237 ml.AddressOf (ec, AddressOp.LoadStore);
238 type = ReferenceContainer.MakeType (ec.Module, type);
243 variable = new LocalTemporary (type);
250 public class NamedArgument : MovableArgument
252 public readonly string Name;
253 readonly Location loc;
255 public NamedArgument (string name, Location loc, Expression expr)
256 : this (name, loc, expr, AType.None)
260 public NamedArgument (string name, Location loc, Expression expr, AType modifier)
261 : base (expr, modifier)
267 public override Expression CreateExpressionTree (ResolveContext ec)
269 ec.Report.Error (853, loc, "An expression tree cannot contain named argument");
270 return base.CreateExpressionTree (ec);
273 public Location Location {
278 public class Arguments
280 sealed class ArgumentsOrdered : Arguments
282 readonly List<MovableArgument> ordered;
284 public ArgumentsOrdered (Arguments args)
288 ordered = new List<MovableArgument> ();
291 public void AddOrdered (MovableArgument arg)
296 public override void FlowAnalysis (FlowAnalysisContext fc, List<MovableArgument> movable = null)
298 foreach (var arg in ordered) {
299 if (arg.ArgType != Argument.AType.Out)
300 arg.FlowAnalysis (fc);
303 base.FlowAnalysis (fc, ordered);
306 public override Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
308 foreach (var a in ordered) {
310 a.EmitToField (ec, false);
312 a.EmitToVariable (ec);
315 return base.Emit (ec, dup_args, prepareAwait);
319 // Try not to add any more instances to this class, it's allocated a lot
322 public Arguments (int capacity)
324 args = new List<Argument> (capacity);
327 private Arguments (List<Argument> args)
332 public void Add (Argument arg)
337 public void AddRange (Arguments args)
339 this.args.AddRange (args.args);
342 public bool ContainsEmitWithAwait ()
344 foreach (var arg in args) {
345 if (arg.Expr.ContainsEmitWithAwait ())
352 public ArrayInitializer CreateDynamicBinderArguments (ResolveContext rc)
354 Location loc = Location.Null;
355 var all = new ArrayInitializer (args.Count, loc);
357 MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace (loc);
359 foreach (Argument a in args) {
360 Arguments dargs = new Arguments (2);
362 // CSharpArgumentInfoFlags.None = 0
363 const string info_flags_enum = "CSharpArgumentInfoFlags";
364 Expression info_flags = new IntLiteral (rc.BuiltinTypes, 0, loc);
366 if (a.Expr is Constant) {
367 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
368 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "Constant", loc));
369 } else if (a.ArgType == Argument.AType.Ref) {
370 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
371 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsRef", loc));
372 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
373 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
374 } else if (a.ArgType == Argument.AType.Out) {
375 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
376 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsOut", loc));
377 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
378 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
379 } else if (a.ArgType == Argument.AType.DynamicTypeName) {
380 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
381 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsStaticType", loc));
384 var arg_type = a.Expr.Type;
386 if (arg_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && arg_type != InternalType.NullLiteral) {
387 MethodGroupExpr mg = a.Expr as MethodGroupExpr;
389 rc.Report.Error (1976, a.Expr.Location,
390 "The method group `{0}' cannot be used as an argument of dynamic operation. Consider using parentheses to invoke the method",
392 } else if (arg_type == InternalType.AnonymousMethod) {
393 rc.Report.Error (1977, a.Expr.Location,
394 "An anonymous method or lambda expression cannot be used as an argument of dynamic operation. Consider using a cast");
395 } else if (arg_type.Kind == MemberKind.Void || arg_type == InternalType.Arglist || arg_type.IsPointer) {
396 rc.Report.Error (1978, a.Expr.Location,
397 "An expression of type `{0}' cannot be used as an argument of dynamic operation",
398 arg_type.GetSignatureForError ());
401 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
402 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
406 NamedArgument na = a as NamedArgument;
408 info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
409 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "NamedArgument", loc));
411 named_value = na.Name;
416 dargs.Add (new Argument (info_flags));
417 dargs.Add (new Argument (new StringLiteral (rc.BuiltinTypes, named_value, loc)));
418 all.Add (new Invocation (new MemberAccess (new MemberAccess (binder, "CSharpArgumentInfo", loc), "Create", loc), dargs));
424 public static Arguments CreateForExpressionTree (ResolveContext ec, Arguments args, params Expression[] e)
426 Arguments all = new Arguments ((args == null ? 0 : args.Count) + e.Length);
427 for (int i = 0; i < e.Length; ++i) {
429 all.Add (new Argument (e[i]));
433 foreach (Argument a in args.args) {
434 Expression tree_arg = a.CreateExpressionTree (ec);
435 if (tree_arg != null)
436 all.Add (new Argument (tree_arg));
443 public void CheckArrayAsAttribute (CompilerContext ctx)
445 foreach (Argument arg in args) {
446 // Type is undefined (was error 246)
447 if (arg.Type == null)
450 if (arg.Type.IsArray)
451 ctx.Report.Warning (3016, 1, arg.Expr.Location, "Arrays as attribute arguments are not CLS-compliant");
455 public Arguments Clone (CloneContext ctx)
457 Arguments cloned = new Arguments (args.Count);
458 foreach (Argument a in args)
459 cloned.Add (a.Clone (ctx));
465 get { return args.Count; }
469 // Emits a list of resolved Arguments
471 public void Emit (EmitContext ec)
473 Emit (ec, false, false);
477 // if `dup_args' is true or any of arguments contains await.
478 // A copy of all arguments will be returned to the caller
480 public virtual Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
484 if ((dup_args && Count != 0) || prepareAwait)
485 dups = new List<Argument> (Count);
490 foreach (Argument a in args) {
492 dups.Add (a.EmitToField (ec, true));
502 if (a.Expr.IsSideEffectFree) {
504 // No need to create a temporary variable for side effect free expressions. I assume
505 // all side-effect free expressions are cheap, this has to be tweaked when we become
506 // more aggressive on detection
510 ec.Emit (OpCodes.Dup);
512 // TODO: Release local temporary on next Emit
513 // Need to add a flag to argument to indicate this
514 lt = new LocalTemporary (a.Type);
517 dups.Add (new Argument (lt, a.ArgType));
522 return new Arguments (dups);
527 public virtual void FlowAnalysis (FlowAnalysisContext fc, List<MovableArgument> movable = null)
529 bool has_out = false;
530 foreach (var arg in args) {
531 if (arg.ArgType == Argument.AType.Out) {
536 if (movable == null) {
537 arg.FlowAnalysis (fc);
541 var ma = arg as MovableArgument;
542 if (ma != null && !movable.Contains (ma))
543 arg.FlowAnalysis (fc);
549 foreach (var arg in args) {
550 if (arg.ArgType != Argument.AType.Out)
553 arg.FlowAnalysis (fc);
557 public List<Argument>.Enumerator GetEnumerator ()
559 return args.GetEnumerator ();
563 // At least one argument is of dynamic type
565 public bool HasDynamic {
567 foreach (Argument a in args) {
568 if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
577 // At least one argument is named argument
579 public bool HasNamed {
581 foreach (Argument a in args) {
582 if (a is NamedArgument)
591 public void Insert (int index, Argument arg)
593 args.Insert (index, arg);
596 public static System.Linq.Expressions.Expression[] MakeExpression (Arguments args, BuilderContext ctx)
598 if (args == null || args.Count == 0)
601 var exprs = new System.Linq.Expressions.Expression [args.Count];
602 for (int i = 0; i < exprs.Length; ++i) {
603 Argument a = args.args [i];
604 exprs[i] = a.Expr.MakeExpression (ctx);
611 // For named arguments when the order of execution is different
612 // to order of invocation
614 public Arguments MarkOrderedArgument (NamedArgument a)
617 // An expression has no effect on left-to-right execution
619 if (a.Expr.IsSideEffectFree)
622 ArgumentsOrdered ra = this as ArgumentsOrdered;
624 ra = new ArgumentsOrdered (this);
626 for (int i = 0; i < args.Count; ++i) {
632 // When the argument is filled later by default expression
637 var ma = la as MovableArgument;
639 ma = new MovableArgument (la);
652 // Returns dynamic when at least one argument is of dynamic type
654 public void Resolve (ResolveContext rc, out bool dynamic)
658 List<LocalVariable> var_locals = null;
659 foreach (Argument a in args) {
662 if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef) {
667 if (a.Type == InternalType.VarOutType) {
668 var de = a.Expr as DeclarationExpression;
670 if (var_locals == null)
671 var_locals = new List<LocalVariable> ();
673 var_locals.Add (de.Variable);
677 var lvr = a.Expr as LocalVariableReference;
678 if (lvr != null && var_locals != null && var_locals.Contains (lvr.local_info)) {
679 rc.Report.Error (8196, lvr.Location, "Reference to an implicitly typed out variable `{0}' is not permitted in the same argument list", lvr.Name);
680 lvr.Type = InternalType.ErrorType;
686 public void RemoveAt (int index)
688 args.RemoveAt (index);
691 public Argument this [int index] {
692 get { return args [index]; }
693 set { args [index] = value; }