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