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