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