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