Merge pull request #194 from QuickJack/master
[mono.git] / mcs / mcs / argument.cs
1 //
2 // argument.cs: Argument expressions
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximain.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
11 //
12
13 using System;
14 using System.Collections.Generic;
15
16 #if STATIC
17 using IKVM.Reflection.Emit;
18 #else
19 using System.Reflection.Emit;
20 #endif
21
22 namespace Mono.CSharp
23 {
24         //
25         // Argument expression used for invocation
26         //
27         public class Argument
28         {
29                 public enum AType : byte
30                 {
31                         None = 0,
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
37                 }
38
39                 public readonly AType ArgType;
40                 public Expression Expr;
41
42                 public Argument (Expression expr, AType type)
43                 {
44                         this.Expr = expr;
45                         this.ArgType = type;
46                 }
47
48                 public Argument (Expression expr)
49                 {
50                         if (expr == null)
51                                 throw new ArgumentNullException ();
52
53                         this.Expr = expr;
54                 }
55
56                 #region Properties
57
58                 public bool IsByRef {
59                         get { return ArgType == AType.Ref || ArgType == AType.Out; }
60                 }
61
62                 public bool IsDefaultArgument {
63                         get { return ArgType == AType.Default; }
64                 }
65
66                 public Parameter.Modifier Modifier {
67                         get {
68                                 switch (ArgType) {
69                                 case AType.Out:
70                                         return Parameter.Modifier.OUT;
71
72                                 case AType.Ref:
73                                         return Parameter.Modifier.REF;
74
75                                 default:
76                                         return Parameter.Modifier.NONE;
77                                 }
78                         }
79                 }
80
81                 public TypeSpec Type {
82                         get { return Expr.Type; }
83                 }
84
85                 #endregion
86
87                 public Argument Clone (Expression expr)
88                 {
89                         Argument a = (Argument) MemberwiseClone ();
90                         a.Expr = expr;
91                         return a;
92                 }
93
94                 public Argument Clone (CloneContext clonectx)
95                 {
96                         return Clone (Expr.Clone (clonectx));
97                 }
98
99                 public virtual Expression CreateExpressionTree (ResolveContext ec)
100                 {
101                         if (ArgType == AType.Default)
102                                 ec.Report.Error (854, Expr.Location, "An expression tree cannot contain an invocation which uses optional parameter");
103
104                         return Expr.CreateExpressionTree (ec);
105                 }
106
107
108                 public virtual void Emit (EmitContext ec)
109                 {
110                         if (!IsByRef) {
111                                 Expr.Emit (ec);
112                                 return;
113                         }
114
115                         AddressOp mode = AddressOp.Store;
116                         if (ArgType == AType.Ref)
117                                 mode |= AddressOp.Load;
118
119                         IMemoryLocation ml = (IMemoryLocation) Expr;
120                         ml.AddressOf (ec, mode);
121                 }
122
123                 public Argument EmitToField (EmitContext ec)
124                 {
125                         var res = Expr.EmitToField (ec);
126                         return res == Expr ? this : new Argument (res, ArgType);
127                 }
128
129                 public string GetSignatureForError ()
130                 {
131                         if (Expr.eclass == ExprClass.MethodGroup)
132                                 return Expr.ExprClassName;
133
134                         return TypeManager.CSharpName (Expr.Type);
135                 }
136
137                 public bool ResolveMethodGroup (ResolveContext ec)
138                 {
139                         SimpleName sn = Expr as SimpleName;
140                         if (sn != null)
141                                 Expr = sn.GetMethodGroup ();
142
143                         // FIXME: csc doesn't report any error if you try to use `ref' or
144                         //        `out' in a delegate creation expression.
145                         Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
146                         if (Expr == null)
147                                 return false;
148
149                         return true;
150                 }
151
152                 public void Resolve (ResolveContext ec)
153                 {
154 //                      using (ec.With (ResolveContext.Options.DoFlowAnalysis, true)) {
155                                 // Verify that the argument is readable
156                                 if (ArgType != AType.Out)
157                                         Expr = Expr.Resolve (ec);
158
159                                 // Verify that the argument is writeable
160                                 if (Expr != null && IsByRef)
161                                         Expr = Expr.ResolveLValue (ec, EmptyExpression.OutAccess);
162
163                                 if (Expr == null)
164                                         Expr = ErrorExpression.Instance;
165 //                      }
166                 }
167         }
168
169         public class MovableArgument : Argument
170         {
171                 LocalTemporary variable;
172
173                 public MovableArgument (Argument arg)
174                         : this (arg.Expr, arg.ArgType)
175                 {
176                 }
177
178                 protected MovableArgument (Expression expr, AType modifier)
179                         : base (expr, modifier)
180                 {
181                 }
182
183                 public override void Emit (EmitContext ec)
184                 {
185                         // TODO: Should guard against multiple emits
186                         base.Emit (ec);
187
188                         // Release temporary variable when used
189                         if (variable != null)
190                                 variable.Release (ec);
191                 }
192
193                 public void EmitToVariable (EmitContext ec)
194                 {
195                         var type = Expr.Type;
196                         if (IsByRef) {
197                                 var ml = (IMemoryLocation) Expr;
198                                 ml.AddressOf (ec, AddressOp.LoadStore);
199                                 type = ReferenceContainer.MakeType (ec.Module, type);
200                         } else {
201                                 Expr.Emit (ec);
202                         }
203
204                         variable = new LocalTemporary (type);
205                         variable.Store (ec);
206
207                         Expr = variable;
208                 }
209         }
210
211         public class NamedArgument : MovableArgument
212         {
213                 public readonly string Name;
214                 readonly Location loc;
215
216                 public NamedArgument (string name, Location loc, Expression expr)
217                         : this (name, loc, expr, AType.None)
218                 {
219                 }
220
221                 public NamedArgument (string name, Location loc, Expression expr, AType modifier)
222                         : base (expr, modifier)
223                 {
224                         this.Name = name;
225                         this.loc = loc;
226                 }
227
228                 public override Expression CreateExpressionTree (ResolveContext ec)
229                 {
230                         ec.Report.Error (853, loc, "An expression tree cannot contain named argument");
231                         return base.CreateExpressionTree (ec);
232                 }
233
234                 public Location Location {
235                         get { return loc; }
236                 }
237         }
238         
239         public class Arguments
240         {
241                 sealed class ArgumentsOrdered : Arguments
242                 {
243                         readonly List<MovableArgument> ordered;
244
245                         public ArgumentsOrdered (Arguments args)
246                                 : base (args.Count)
247                         {
248                                 AddRange (args);
249                                 ordered = new List<MovableArgument> ();
250                         }
251
252                         public void AddOrdered (MovableArgument arg)
253                         {
254                                 ordered.Add (arg);
255                         }
256
257                         public override Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
258                         {
259                                 foreach (var a in ordered) {
260                                         if (prepareAwait)
261                                                 a.EmitToField (ec);
262                                         else
263                                                 a.EmitToVariable (ec);
264                                 }
265
266                                 return base.Emit (ec, dup_args, prepareAwait);
267                         }
268                 }
269
270                 // Try not to add any more instances to this class, it's allocated a lot
271                 List<Argument> args;
272
273                 public Arguments (int capacity)
274                 {
275                         args = new List<Argument> (capacity);
276                 }
277
278                 private Arguments (List<Argument> args)
279                 {
280                         this.args = args;
281                 }
282
283                 public void Add (Argument arg)
284                 {
285                         args.Add (arg);
286                 }
287
288                 public void AddRange (Arguments args)
289                 {
290                         this.args.AddRange (args.args);
291                 }
292
293                 public bool ContainsEmitWithAwait ()
294                 {
295                         foreach (var arg in args) {
296                                 if (arg.Expr.ContainsEmitWithAwait ())
297                                         return true;
298                         }
299
300                         return false;
301                 }
302
303                 public ArrayInitializer CreateDynamicBinderArguments (ResolveContext rc)
304                 {
305                         Location loc = Location.Null;
306                         var all = new ArrayInitializer (args.Count, loc);
307
308                         MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace (loc);
309
310                         foreach (Argument a in args) {
311                                 Arguments dargs = new Arguments (2);
312
313                                 // CSharpArgumentInfoFlags.None = 0
314                                 const string info_flags_enum = "CSharpArgumentInfoFlags";
315                                 Expression info_flags = new IntLiteral (rc.BuiltinTypes, 0, loc);
316
317                                 if (a.Expr is Constant) {
318                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
319                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "Constant", loc), loc);
320                                 } else if (a.ArgType == Argument.AType.Ref) {
321                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
322                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsRef", loc), loc);
323                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
324                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
325                                 } else if (a.ArgType == Argument.AType.Out) {
326                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
327                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsOut", loc), loc);
328                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
329                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
330                                 } else if (a.ArgType == Argument.AType.DynamicTypeName) {
331                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
332                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsStaticType", loc), loc);
333                                 }
334
335                                 var arg_type = a.Expr.Type;
336
337                                 if (arg_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && arg_type != InternalType.NullLiteral) {
338                                         MethodGroupExpr mg = a.Expr as MethodGroupExpr;
339                                         if (mg != null) {
340                                                 rc.Report.Error (1976, a.Expr.Location,
341                                                         "The method group `{0}' cannot be used as an argument of dynamic operation. Consider using parentheses to invoke the method",
342                                                         mg.Name);
343                                         } else if (arg_type == InternalType.AnonymousMethod) {
344                                                 rc.Report.Error (1977, a.Expr.Location,
345                                                         "An anonymous method or lambda expression cannot be used as an argument of dynamic operation. Consider using a cast");
346                                         } else if (arg_type.Kind == MemberKind.Void || arg_type == InternalType.Arglist || arg_type.IsPointer) {
347                                                 rc.Report.Error (1978, a.Expr.Location,
348                                                         "An expression of type `{0}' cannot be used as an argument of dynamic operation",
349                                                         TypeManager.CSharpName (arg_type));
350                                         }
351
352                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
353                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
354                                 }
355
356                                 string named_value;
357                                 NamedArgument na = a as NamedArgument;
358                                 if (na != null) {
359                                         info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
360                                                 new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "NamedArgument", loc), loc);
361
362                                         named_value = na.Name;
363                                 } else {
364                                         named_value = null;
365                                 }
366
367                                 dargs.Add (new Argument (info_flags));
368                                 dargs.Add (new Argument (new StringLiteral (rc.BuiltinTypes, named_value, loc)));
369                                 all.Add (new Invocation (new MemberAccess (new MemberAccess (binder, "CSharpArgumentInfo", loc), "Create", loc), dargs));
370                         }
371
372                         return all;
373                 }
374
375                 public static Arguments CreateForExpressionTree (ResolveContext ec, Arguments args, params Expression[] e)
376                 {
377                         Arguments all = new Arguments ((args == null ? 0 : args.Count) + e.Length);
378                         for (int i = 0; i < e.Length; ++i) {
379                                 if (e [i] != null)
380                                         all.Add (new Argument (e[i]));
381                         }
382
383                         if (args != null) {
384                                 foreach (Argument a in args.args) {
385                                         Expression tree_arg = a.CreateExpressionTree (ec);
386                                         if (tree_arg != null)
387                                                 all.Add (new Argument (tree_arg));
388                                 }
389                         }
390
391                         return all;
392                 }
393
394                 public void CheckArrayAsAttribute (CompilerContext ctx)
395                 {
396                         foreach (Argument arg in args) {
397                                 // Type is undefined (was error 246)
398                                 if (arg.Type == null)
399                                         continue;
400
401                                 if (arg.Type.IsArray)
402                                         ctx.Report.Warning (3016, 1, arg.Expr.Location, "Arrays as attribute arguments are not CLS-compliant");
403                         }
404                 }
405
406                 public Arguments Clone (CloneContext ctx)
407                 {
408                         Arguments cloned = new Arguments (args.Count);
409                         foreach (Argument a in args)
410                                 cloned.Add (a.Clone (ctx));
411
412                         return cloned;
413                 }
414
415                 public int Count {
416                         get { return args.Count; }
417                 }
418
419                 //
420                 // Emits a list of resolved Arguments
421                 // 
422                 public void Emit (EmitContext ec)
423                 {
424                         Emit (ec, false, false);
425                 }
426
427                 //
428                 // if `dup_args' is true or any of arguments contains await.
429                 // A copy of all arguments will be returned to the caller
430                 //
431                 public virtual Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
432                 {
433                         List<Argument> dups;
434
435                         if ((dup_args && Count != 0) || prepareAwait)
436                                 dups = new List<Argument> (Count);
437                         else
438                                 dups = null;
439
440                         LocalTemporary lt;
441                         foreach (Argument a in args) {
442                                 if (prepareAwait) {
443                                         dups.Add (a.EmitToField (ec));
444                                         continue;
445                                 }
446                                 
447                                 a.Emit (ec);
448
449                                 if (!dup_args) {
450                                         continue;
451                                 }
452
453                                 if (a.Expr.IsSideEffectFree) {
454                                         //
455                                         // No need to create a temporary variable for side effect free expressions. I assume
456                                         // all side-effect free expressions are cheap, this has to be tweaked when we become
457                                         // more aggressive on detection
458                                         //
459                                         dups.Add (a);
460                                 } else {
461                                         ec.Emit (OpCodes.Dup);
462
463                                         // TODO: Release local temporary on next Emit
464                                         // Need to add a flag to argument to indicate this
465                                         lt = new LocalTemporary (a.Type);
466                                         lt.Store (ec);
467
468                                         dups.Add (new Argument (lt, a.ArgType));
469                                 }
470                         }
471
472                         if (dups != null)
473                                 return new Arguments (dups);
474
475                         return null;
476                 }
477
478                 public List<Argument>.Enumerator GetEnumerator ()
479                 {
480                         return args.GetEnumerator ();
481                 }
482
483                 //
484                 // At least one argument is of dynamic type
485                 //
486                 public bool HasDynamic {
487                         get {
488                                 foreach (Argument a in args) {
489                                         if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
490                                                 return true;
491                                 }
492                                 
493                                 return false;
494                         }
495                 }
496
497                 //
498                 // At least one argument is named argument
499                 //
500                 public bool HasNamed {
501                         get {
502                                 foreach (Argument a in args) {
503                                         if (a is NamedArgument)
504                                                 return true;
505                                 }
506                                 
507                                 return false;
508                         }
509                 }
510
511
512                 public void Insert (int index, Argument arg)
513                 {
514                         args.Insert (index, arg);
515                 }
516
517                 public static System.Linq.Expressions.Expression[] MakeExpression (Arguments args, BuilderContext ctx)
518                 {
519                         if (args == null || args.Count == 0)
520                                 return null;
521
522                         var exprs = new System.Linq.Expressions.Expression [args.Count];
523                         for (int i = 0; i < exprs.Length; ++i) {
524                                 Argument a = args.args [i];
525                                 exprs[i] = a.Expr.MakeExpression (ctx);
526                         }
527
528                         return exprs;
529                 }
530
531                 //
532                 // For named arguments when the order of execution is different
533                 // to order of invocation
534                 //
535                 public Arguments MarkOrderedArgument (NamedArgument a)
536                 {
537                         //
538                         // An expression has no effect on left-to-right execution
539                         //
540                         if (a.Expr.IsSideEffectFree)
541                                 return this;
542
543                         ArgumentsOrdered ra = this as ArgumentsOrdered;
544                         if (ra == null) {
545                                 ra = new ArgumentsOrdered (this);
546
547                                 for (int i = 0; i < args.Count; ++i) {
548                                         var la = args [i];
549                                         if (la == a)
550                                                 break;
551
552                                         //
553                                         // When the argument is filled later by default expression
554                                         //
555                                         if (la == null)
556                                                 continue;
557
558                                         var ma = la as MovableArgument;
559                                         if (ma == null) {
560                                                 ma = new MovableArgument (la);
561                                                 ra.args[i] = ma;
562                                         }
563
564                                         ra.AddOrdered (ma);
565                                 }
566                         }
567
568                         ra.AddOrdered (a);
569                         return ra;
570                 }
571
572                 //
573                 // Returns dynamic when at least one argument is of dynamic type
574                 //
575                 public void Resolve (ResolveContext ec, out bool dynamic)
576                 {
577                         dynamic = false;
578                         foreach (Argument a in args) {
579                                 a.Resolve (ec);
580                                 if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
581                                         dynamic = true;
582                         }
583                 }
584
585                 public void RemoveAt (int index)
586                 {
587                         args.RemoveAt (index);
588                 }
589
590                 public Argument this [int index] {
591                         get { return args [index]; }
592                         set { args [index] = value; }
593                 }
594         }
595 }