2009-07-17 Zoltan Varga <vargaz@gmail.com>
[mcs.git] / mcs / expression.cs
blob3d8026562dac8dc97a2acb9453731dcc89f847c5
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
11 #define USE_OLD
13 namespace Mono.CSharp {
14 using System;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Text;
21 // This is an user operator expression, automatically created during
22 // resolve phase
24 public class UserOperatorCall : Expression {
25 public delegate Expression ExpressionTreeExpression (EmitContext ec, MethodGroupExpr mg);
27 protected readonly Arguments arguments;
28 protected readonly MethodGroupExpr mg;
29 readonly ExpressionTreeExpression expr_tree;
31 public UserOperatorCall (MethodGroupExpr mg, Arguments args, ExpressionTreeExpression expr_tree, Location loc)
33 this.mg = mg;
34 this.arguments = args;
35 this.expr_tree = expr_tree;
37 type = TypeManager.TypeToCoreType (((MethodInfo) mg).ReturnType);
38 eclass = ExprClass.Value;
39 this.loc = loc;
42 public override Expression CreateExpressionTree (EmitContext ec)
44 if (expr_tree != null)
45 return expr_tree (ec, mg);
47 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
48 new NullLiteral (loc),
49 mg.CreateExpressionTree (ec));
51 return CreateExpressionFactoryCall ("Call", args);
54 protected override void CloneTo (CloneContext context, Expression target)
56 // Nothing to clone
59 public override Expression DoResolve (EmitContext ec)
62 // We are born fully resolved
64 return this;
67 public override void Emit (EmitContext ec)
69 mg.EmitCall (ec, arguments);
72 public MethodGroupExpr Method {
73 get { return mg; }
76 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
78 arguments.MutateHoistedGenericType (storey);
79 mg.MutateHoistedGenericType (storey);
83 public class ParenthesizedExpression : Expression
85 public Expression Expr;
87 public ParenthesizedExpression (Expression expr)
89 Expr = expr;
90 loc = expr.Location;
93 public override Expression CreateExpressionTree (EmitContext ec)
95 throw new NotSupportedException ("ET");
98 public override Expression DoResolve (EmitContext ec)
100 Expr = Expr.Resolve (ec);
101 return Expr;
104 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
106 return Expr.DoResolveLValue (ec, right_side);
109 public override void Emit (EmitContext ec)
111 throw new Exception ("Should not happen");
114 protected override void CloneTo (CloneContext clonectx, Expression t)
116 ParenthesizedExpression target = (ParenthesizedExpression) t;
118 target.Expr = Expr.Clone (clonectx);
123 // Unary implements unary expressions.
125 public class Unary : Expression
127 public enum Operator : byte {
128 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
129 AddressOf, TOP
132 static Type [] [] predefined_operators;
134 public readonly Operator Oper;
135 public Expression Expr;
136 Expression enum_conversion;
138 public Unary (Operator op, Expression expr)
140 Oper = op;
141 Expr = expr;
142 loc = expr.Location;
145 // <summary>
146 // This routine will attempt to simplify the unary expression when the
147 // argument is a constant.
148 // </summary>
149 Constant TryReduceConstant (EmitContext ec, Constant e)
151 if (e is EmptyConstantCast)
152 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
154 if (e is SideEffectConstant) {
155 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
156 return r == null ? null : new SideEffectConstant (r, e, r.Location);
159 Type expr_type = e.Type;
161 switch (Oper){
162 case Operator.UnaryPlus:
163 // Unary numeric promotions
164 if (expr_type == TypeManager.byte_type)
165 return new IntConstant (((ByteConstant)e).Value, e.Location);
166 if (expr_type == TypeManager.sbyte_type)
167 return new IntConstant (((SByteConstant)e).Value, e.Location);
168 if (expr_type == TypeManager.short_type)
169 return new IntConstant (((ShortConstant)e).Value, e.Location);
170 if (expr_type == TypeManager.ushort_type)
171 return new IntConstant (((UShortConstant)e).Value, e.Location);
172 if (expr_type == TypeManager.char_type)
173 return new IntConstant (((CharConstant)e).Value, e.Location);
175 // Predefined operators
176 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
177 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
178 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
179 expr_type == TypeManager.decimal_type) {
180 return e;
183 return null;
185 case Operator.UnaryNegation:
186 // Unary numeric promotions
187 if (expr_type == TypeManager.byte_type)
188 return new IntConstant (-((ByteConstant)e).Value, e.Location);
189 if (expr_type == TypeManager.sbyte_type)
190 return new IntConstant (-((SByteConstant)e).Value, e.Location);
191 if (expr_type == TypeManager.short_type)
192 return new IntConstant (-((ShortConstant)e).Value, e.Location);
193 if (expr_type == TypeManager.ushort_type)
194 return new IntConstant (-((UShortConstant)e).Value, e.Location);
195 if (expr_type == TypeManager.char_type)
196 return new IntConstant (-((CharConstant)e).Value, e.Location);
198 // Predefined operators
199 if (expr_type == TypeManager.int32_type) {
200 int value = ((IntConstant)e).Value;
201 if (value == int.MinValue) {
202 if (ec.ConstantCheckState) {
203 ConstantFold.Error_CompileTimeOverflow (loc);
204 return null;
206 return e;
208 return new IntConstant (-value, e.Location);
210 if (expr_type == TypeManager.int64_type) {
211 long value = ((LongConstant)e).Value;
212 if (value == long.MinValue) {
213 if (ec.ConstantCheckState) {
214 ConstantFold.Error_CompileTimeOverflow (loc);
215 return null;
217 return e;
219 return new LongConstant (-value, e.Location);
222 if (expr_type == TypeManager.uint32_type) {
223 UIntLiteral uil = e as UIntLiteral;
224 if (uil != null) {
225 if (uil.Value == 2147483648)
226 return new IntLiteral (int.MinValue, e.Location);
227 return new LongLiteral (-uil.Value, e.Location);
229 return new LongConstant (-((UIntConstant)e).Value, e.Location);
232 if (expr_type == TypeManager.uint64_type) {
233 ULongLiteral ull = e as ULongLiteral;
234 if (ull != null && ull.Value == 9223372036854775808)
235 return new LongLiteral (long.MinValue, e.Location);
236 return null;
239 if (expr_type == TypeManager.float_type) {
240 FloatLiteral fl = e as FloatLiteral;
241 // For better error reporting
242 if (fl != null)
243 return new FloatLiteral (-fl.Value, e.Location);
245 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
247 if (expr_type == TypeManager.double_type) {
248 DoubleLiteral dl = e as DoubleLiteral;
249 // For better error reporting
250 if (dl != null)
251 return new DoubleLiteral (-dl.Value, e.Location);
253 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
255 if (expr_type == TypeManager.decimal_type)
256 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
258 return null;
260 case Operator.LogicalNot:
261 if (expr_type != TypeManager.bool_type)
262 return null;
264 bool b = (bool)e.GetValue ();
265 return new BoolConstant (!b, e.Location);
267 case Operator.OnesComplement:
268 // Unary numeric promotions
269 if (expr_type == TypeManager.byte_type)
270 return new IntConstant (~((ByteConstant)e).Value, e.Location);
271 if (expr_type == TypeManager.sbyte_type)
272 return new IntConstant (~((SByteConstant)e).Value, e.Location);
273 if (expr_type == TypeManager.short_type)
274 return new IntConstant (~((ShortConstant)e).Value, e.Location);
275 if (expr_type == TypeManager.ushort_type)
276 return new IntConstant (~((UShortConstant)e).Value, e.Location);
277 if (expr_type == TypeManager.char_type)
278 return new IntConstant (~((CharConstant)e).Value, e.Location);
280 // Predefined operators
281 if (expr_type == TypeManager.int32_type)
282 return new IntConstant (~((IntConstant)e).Value, e.Location);
283 if (expr_type == TypeManager.uint32_type)
284 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
285 if (expr_type == TypeManager.int64_type)
286 return new LongConstant (~((LongConstant)e).Value, e.Location);
287 if (expr_type == TypeManager.uint64_type){
288 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
290 if (e is EnumConstant) {
291 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
292 if (e != null)
293 e = new EnumConstant (e, expr_type);
294 return e;
296 return null;
298 throw new Exception ("Can not constant fold: " + Oper.ToString());
301 protected Expression ResolveOperator (EmitContext ec, Expression expr)
303 eclass = ExprClass.Value;
305 if (predefined_operators == null)
306 CreatePredefinedOperatorsTable ();
308 Type expr_type = expr.Type;
309 Expression best_expr;
312 // Primitive types first
314 if (TypeManager.IsPrimitiveType (expr_type)) {
315 best_expr = ResolvePrimitivePredefinedType (expr);
316 if (best_expr == null)
317 return null;
319 type = best_expr.Type;
320 Expr = best_expr;
321 return this;
325 // E operator ~(E x);
327 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
328 return ResolveEnumOperator (ec, expr);
330 return ResolveUserType (ec, expr);
333 protected virtual Expression ResolveEnumOperator (EmitContext ec, Expression expr)
335 Type underlying_type = TypeManager.GetEnumUnderlyingType (expr.Type);
336 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
337 if (best_expr == null)
338 return null;
340 Expr = best_expr;
341 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
342 type = expr.Type;
343 return EmptyCast.Create (this, type);
346 public override Expression CreateExpressionTree (EmitContext ec)
348 return CreateExpressionTree (ec, null);
351 Expression CreateExpressionTree (EmitContext ec, MethodGroupExpr user_op)
353 string method_name;
354 switch (Oper) {
355 case Operator.AddressOf:
356 Error_PointerInsideExpressionTree ();
357 return null;
358 case Operator.UnaryNegation:
359 if (ec.CheckState && user_op == null && !IsFloat (type))
360 method_name = "NegateChecked";
361 else
362 method_name = "Negate";
363 break;
364 case Operator.OnesComplement:
365 case Operator.LogicalNot:
366 method_name = "Not";
367 break;
368 case Operator.UnaryPlus:
369 method_name = "UnaryPlus";
370 break;
371 default:
372 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
375 Arguments args = new Arguments (2);
376 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
377 if (user_op != null)
378 args.Add (new Argument (user_op.CreateExpressionTree (ec)));
379 return CreateExpressionFactoryCall (method_name, args);
382 static void CreatePredefinedOperatorsTable ()
384 predefined_operators = new Type [(int) Operator.TOP] [];
387 // 7.6.1 Unary plus operator
389 predefined_operators [(int) Operator.UnaryPlus] = new Type [] {
390 TypeManager.int32_type, TypeManager.uint32_type,
391 TypeManager.int64_type, TypeManager.uint64_type,
392 TypeManager.float_type, TypeManager.double_type,
393 TypeManager.decimal_type
397 // 7.6.2 Unary minus operator
399 predefined_operators [(int) Operator.UnaryNegation] = new Type [] {
400 TypeManager.int32_type,
401 TypeManager.int64_type,
402 TypeManager.float_type, TypeManager.double_type,
403 TypeManager.decimal_type
407 // 7.6.3 Logical negation operator
409 predefined_operators [(int) Operator.LogicalNot] = new Type [] {
410 TypeManager.bool_type
414 // 7.6.4 Bitwise complement operator
416 predefined_operators [(int) Operator.OnesComplement] = new Type [] {
417 TypeManager.int32_type, TypeManager.uint32_type,
418 TypeManager.int64_type, TypeManager.uint64_type
423 // Unary numeric promotions
425 static Expression DoNumericPromotion (Operator op, Expression expr)
427 Type expr_type = expr.Type;
428 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
429 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
430 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
431 expr_type == TypeManager.char_type)
432 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
434 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
435 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
437 return expr;
440 public override Expression DoResolve (EmitContext ec)
442 if (Oper == Operator.AddressOf) {
443 return ResolveAddressOf (ec);
446 Expr = Expr.Resolve (ec);
447 if (Expr == null)
448 return null;
450 if (Expr.Type == InternalType.Dynamic) {
451 Arguments args = new Arguments (1);
452 args.Add (new Argument (Expr));
453 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).DoResolve (ec);
456 if (TypeManager.IsNullableType (Expr.Type))
457 return new Nullable.LiftedUnaryOperator (Oper, Expr).Resolve (ec);
460 // Attempt to use a constant folding operation.
462 Constant cexpr = Expr as Constant;
463 if (cexpr != null) {
464 cexpr = TryReduceConstant (ec, cexpr);
465 if (cexpr != null)
466 return cexpr;
469 Expression expr = ResolveOperator (ec, Expr);
470 if (expr == null)
471 Error_OperatorCannotBeApplied (loc, OperName (Oper), Expr.Type);
474 // Reduce unary operator on predefined types
476 if (expr == this && Oper == Operator.UnaryPlus)
477 return Expr;
479 return expr;
482 public override Expression DoResolveLValue (EmitContext ec, Expression right)
484 return null;
487 public override void Emit (EmitContext ec)
489 EmitOperator (ec, type);
492 protected void EmitOperator (EmitContext ec, Type type)
494 ILGenerator ig = ec.ig;
496 switch (Oper) {
497 case Operator.UnaryPlus:
498 Expr.Emit (ec);
499 break;
501 case Operator.UnaryNegation:
502 if (ec.CheckState && !IsFloat (type)) {
503 ig.Emit (OpCodes.Ldc_I4_0);
504 if (type == TypeManager.int64_type)
505 ig.Emit (OpCodes.Conv_U8);
506 Expr.Emit (ec);
507 ig.Emit (OpCodes.Sub_Ovf);
508 } else {
509 Expr.Emit (ec);
510 ig.Emit (OpCodes.Neg);
513 break;
515 case Operator.LogicalNot:
516 Expr.Emit (ec);
517 ig.Emit (OpCodes.Ldc_I4_0);
518 ig.Emit (OpCodes.Ceq);
519 break;
521 case Operator.OnesComplement:
522 Expr.Emit (ec);
523 ig.Emit (OpCodes.Not);
524 break;
526 case Operator.AddressOf:
527 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
528 break;
530 default:
531 throw new Exception ("This should not happen: Operator = "
532 + Oper.ToString ());
536 // Same trick as in Binary expression
538 if (enum_conversion != null)
539 enum_conversion.Emit (ec);
542 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
544 if (Oper == Operator.LogicalNot)
545 Expr.EmitBranchable (ec, target, !on_true);
546 else
547 base.EmitBranchable (ec, target, on_true);
550 public override void EmitSideEffect (EmitContext ec)
552 Expr.EmitSideEffect (ec);
555 public static void Error_OperatorCannotBeApplied (Location loc, string oper, Type t)
557 Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
558 oper, TypeManager.CSharpName (t));
562 // Converts operator to System.Linq.Expressions.ExpressionType enum name
564 string GetOperatorExpressionTypeName ()
566 switch (Oper) {
567 case Operator.UnaryPlus:
568 return "UnaryPlus";
569 default:
570 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
574 static bool IsFloat (Type t)
576 return t == TypeManager.float_type || t == TypeManager.double_type;
580 // Returns a stringified representation of the Operator
582 public static string OperName (Operator oper)
584 switch (oper) {
585 case Operator.UnaryPlus:
586 return "+";
587 case Operator.UnaryNegation:
588 return "-";
589 case Operator.LogicalNot:
590 return "!";
591 case Operator.OnesComplement:
592 return "~";
593 case Operator.AddressOf:
594 return "&";
597 throw new NotImplementedException (oper.ToString ());
600 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
602 type = storey.MutateType (type);
603 Expr.MutateHoistedGenericType (storey);
606 Expression ResolveAddressOf (EmitContext ec)
608 if (!ec.InUnsafe)
609 UnsafeError (loc);
611 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
612 if (Expr == null || Expr.eclass != ExprClass.Variable) {
613 Error (211, "Cannot take the address of the given expression");
614 return null;
617 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)) {
618 return null;
621 IVariableReference vr = Expr as IVariableReference;
622 bool is_fixed;
623 if (vr != null) {
624 VariableInfo vi = vr.VariableInfo;
625 if (vi != null) {
626 if (vi.LocalInfo != null)
627 vi.LocalInfo.Used = true;
630 // A variable is considered definitely assigned if you take its address.
632 vi.SetAssigned (ec);
635 is_fixed = vr.IsFixed;
636 vr.SetHasAddressTaken ();
638 if (vr.IsHoisted) {
639 AnonymousMethodExpression.Error_AddressOfCapturedVar (vr, loc);
641 } else {
642 IFixedExpression fe = Expr as IFixedExpression;
643 is_fixed = fe != null && fe.IsFixed;
646 if (!is_fixed && !ec.InFixedInitializer) {
647 Error (212, "You can only take the address of unfixed expression inside of a fixed statement initializer");
650 type = TypeManager.GetPointerType (Expr.Type);
651 eclass = ExprClass.Value;
652 return this;
655 Expression ResolvePrimitivePredefinedType (Expression expr)
657 expr = DoNumericPromotion (Oper, expr);
658 Type expr_type = expr.Type;
659 Type[] predefined = predefined_operators [(int) Oper];
660 foreach (Type t in predefined) {
661 if (t == expr_type)
662 return expr;
664 return null;
668 // Perform user-operator overload resolution
670 protected virtual Expression ResolveUserOperator (EmitContext ec, Expression expr)
672 CSharp.Operator.OpType op_type;
673 switch (Oper) {
674 case Operator.LogicalNot:
675 op_type = CSharp.Operator.OpType.LogicalNot; break;
676 case Operator.OnesComplement:
677 op_type = CSharp.Operator.OpType.OnesComplement; break;
678 case Operator.UnaryNegation:
679 op_type = CSharp.Operator.OpType.UnaryNegation; break;
680 case Operator.UnaryPlus:
681 op_type = CSharp.Operator.OpType.UnaryPlus; break;
682 default:
683 throw new InternalErrorException (Oper.ToString ());
686 string op_name = CSharp.Operator.GetMetadataName (op_type);
687 MethodGroupExpr user_op = MemberLookup (ec.ContainerType, expr.Type, op_name, MemberTypes.Method, AllBindingFlags, expr.Location) as MethodGroupExpr;
688 if (user_op == null)
689 return null;
691 Arguments args = new Arguments (1);
692 args.Add (new Argument (expr));
693 user_op = user_op.OverloadResolve (ec, ref args, false, expr.Location);
695 if (user_op == null)
696 return null;
698 Expr = args [0].Expr;
699 return new UserOperatorCall (user_op, args, CreateExpressionTree, expr.Location);
703 // Unary user type overload resolution
705 Expression ResolveUserType (EmitContext ec, Expression expr)
707 Expression best_expr = ResolveUserOperator (ec, expr);
708 if (best_expr != null)
709 return best_expr;
711 Type[] predefined = predefined_operators [(int) Oper];
712 foreach (Type t in predefined) {
713 Expression oper_expr = Convert.UserDefinedConversion (ec, expr, t, expr.Location, false);
714 if (oper_expr == null)
715 continue;
718 // decimal type is predefined but has user-operators
720 if (oper_expr.Type == TypeManager.decimal_type)
721 oper_expr = ResolveUserType (ec, oper_expr);
722 else
723 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
725 if (oper_expr == null)
726 continue;
728 if (best_expr == null) {
729 best_expr = oper_expr;
730 continue;
733 int result = MethodGroupExpr.BetterTypeConversion (ec, best_expr.Type, t);
734 if (result == 0) {
735 Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
736 OperName (Oper), TypeManager.CSharpName (expr.Type));
737 break;
740 if (result == 2)
741 best_expr = oper_expr;
744 if (best_expr == null)
745 return null;
748 // HACK: Decimal user-operator is included in standard operators
750 if (best_expr.Type == TypeManager.decimal_type)
751 return best_expr;
753 Expr = best_expr;
754 type = best_expr.Type;
755 return this;
758 protected override void CloneTo (CloneContext clonectx, Expression t)
760 Unary target = (Unary) t;
762 target.Expr = Expr.Clone (clonectx);
767 // Unary operators are turned into Indirection expressions
768 // after semantic analysis (this is so we can take the address
769 // of an indirection).
771 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
772 Expression expr;
773 LocalTemporary temporary;
774 bool prepared;
776 public Indirection (Expression expr, Location l)
778 this.expr = expr;
779 loc = l;
782 public override Expression CreateExpressionTree (EmitContext ec)
784 Error_PointerInsideExpressionTree ();
785 return null;
788 protected override void CloneTo (CloneContext clonectx, Expression t)
790 Indirection target = (Indirection) t;
791 target.expr = expr.Clone (clonectx);
794 public override void Emit (EmitContext ec)
796 if (!prepared)
797 expr.Emit (ec);
799 LoadFromPtr (ec.ig, Type);
802 public void Emit (EmitContext ec, bool leave_copy)
804 Emit (ec);
805 if (leave_copy) {
806 ec.ig.Emit (OpCodes.Dup);
807 temporary = new LocalTemporary (expr.Type);
808 temporary.Store (ec);
812 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
814 prepared = prepare_for_load;
816 expr.Emit (ec);
818 if (prepare_for_load)
819 ec.ig.Emit (OpCodes.Dup);
821 source.Emit (ec);
822 if (leave_copy) {
823 ec.ig.Emit (OpCodes.Dup);
824 temporary = new LocalTemporary (expr.Type);
825 temporary.Store (ec);
828 StoreFromPtr (ec.ig, type);
830 if (temporary != null) {
831 temporary.Emit (ec);
832 temporary.Release (ec);
836 public void AddressOf (EmitContext ec, AddressOp Mode)
838 expr.Emit (ec);
841 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
843 return DoResolve (ec);
846 public override Expression DoResolve (EmitContext ec)
848 expr = expr.Resolve (ec);
849 if (expr == null)
850 return null;
852 if (!ec.InUnsafe)
853 UnsafeError (loc);
855 if (!expr.Type.IsPointer) {
856 Error (193, "The * or -> operator must be applied to a pointer");
857 return null;
860 if (expr.Type == TypeManager.void_ptr_type) {
861 Error (242, "The operation in question is undefined on void pointers");
862 return null;
865 type = TypeManager.GetElementType (expr.Type);
866 eclass = ExprClass.Variable;
867 return this;
870 public bool IsFixed {
871 get { return true; }
874 public override string ToString ()
876 return "*(" + expr + ")";
880 /// <summary>
881 /// Unary Mutator expressions (pre and post ++ and --)
882 /// </summary>
884 /// <remarks>
885 /// UnaryMutator implements ++ and -- expressions. It derives from
886 /// ExpressionStatement becuase the pre/post increment/decrement
887 /// operators can be used in a statement context.
889 /// FIXME: Idea, we could split this up in two classes, one simpler
890 /// for the common case, and one with the extra fields for more complex
891 /// classes (indexers require temporary access; overloaded require method)
893 /// </remarks>
894 public class UnaryMutator : ExpressionStatement {
895 [Flags]
896 public enum Mode : byte {
897 IsIncrement = 0,
898 IsDecrement = 1,
899 IsPre = 0,
900 IsPost = 2,
902 PreIncrement = 0,
903 PreDecrement = IsDecrement,
904 PostIncrement = IsPost,
905 PostDecrement = IsPost | IsDecrement
908 Mode mode;
909 bool is_expr = false;
910 bool recurse = false;
912 Expression expr;
915 // This is expensive for the simplest case.
917 UserOperatorCall method;
919 public UnaryMutator (Mode m, Expression e)
921 mode = m;
922 loc = e.Location;
923 expr = e;
926 static string OperName (Mode mode)
928 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
929 "++" : "--";
932 /// <summary>
933 /// Returns whether an object of type `t' can be incremented
934 /// or decremented with add/sub (ie, basically whether we can
935 /// use pre-post incr-decr operations on it, but it is not a
936 /// System.Decimal, which we require operator overloading to catch)
937 /// </summary>
938 static bool IsIncrementableNumber (Type t)
940 return (t == TypeManager.sbyte_type) ||
941 (t == TypeManager.byte_type) ||
942 (t == TypeManager.short_type) ||
943 (t == TypeManager.ushort_type) ||
944 (t == TypeManager.int32_type) ||
945 (t == TypeManager.uint32_type) ||
946 (t == TypeManager.int64_type) ||
947 (t == TypeManager.uint64_type) ||
948 (t == TypeManager.char_type) ||
949 (TypeManager.IsSubclassOf (t, TypeManager.enum_type)) ||
950 (t == TypeManager.float_type) ||
951 (t == TypeManager.double_type) ||
952 (t.IsPointer && t != TypeManager.void_ptr_type);
955 Expression ResolveOperator (EmitContext ec)
957 type = expr.Type;
960 // The operand of the prefix/postfix increment decrement operators
961 // should be an expression that is classified as a variable,
962 // a property access or an indexer access
964 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
965 expr = expr.ResolveLValue (ec, expr);
966 } else {
967 Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
971 // Step 1: Perform Operator Overload location
973 MethodGroupExpr mg;
974 string op_name;
976 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
977 op_name = Operator.GetMetadataName (Operator.OpType.Increment);
978 else
979 op_name = Operator.GetMetadataName (Operator.OpType.Decrement);
981 mg = MemberLookup (ec.ContainerType, type, op_name, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
983 if (mg != null) {
984 Arguments args = new Arguments (1);
985 args.Add (new Argument (expr));
986 mg = mg.OverloadResolve (ec, ref args, false, loc);
987 if (mg == null)
988 return null;
990 method = new UserOperatorCall (mg, args, null, loc);
991 Convert.ImplicitConversionRequired (ec, method, type, loc);
992 return this;
995 if (!IsIncrementableNumber (type)) {
996 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
997 TypeManager.CSharpName (type) + "'");
998 return null;
1001 return this;
1004 public override Expression CreateExpressionTree (EmitContext ec)
1006 return new SimpleAssign (this, this).CreateExpressionTree (ec);
1009 public override Expression DoResolve (EmitContext ec)
1011 expr = expr.Resolve (ec);
1013 if (expr == null)
1014 return null;
1016 eclass = ExprClass.Value;
1018 if (TypeManager.IsNullableType (expr.Type))
1019 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1021 return ResolveOperator (ec);
1025 // Loads the proper "1" into the stack based on the type, then it emits the
1026 // opcode for the operation requested
1028 void LoadOneAndEmitOp (EmitContext ec, Type t)
1031 // Measure if getting the typecode and using that is more/less efficient
1032 // that comparing types. t.GetTypeCode() is an internal call.
1034 ILGenerator ig = ec.ig;
1036 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
1037 LongConstant.EmitLong (ig, 1);
1038 else if (t == TypeManager.double_type)
1039 ig.Emit (OpCodes.Ldc_R8, 1.0);
1040 else if (t == TypeManager.float_type)
1041 ig.Emit (OpCodes.Ldc_R4, 1.0F);
1042 else if (t.IsPointer){
1043 Type et = TypeManager.GetElementType (t);
1044 int n = GetTypeSize (et);
1046 if (n == 0)
1047 ig.Emit (OpCodes.Sizeof, et);
1048 else {
1049 IntConstant.EmitInt (ig, n);
1050 ig.Emit (OpCodes.Conv_I);
1052 } else
1053 ig.Emit (OpCodes.Ldc_I4_1);
1056 // Now emit the operation
1059 Binary.Operator op = (mode & Mode.IsDecrement) != 0 ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1060 Binary.EmitOperatorOpcode (ec, op, t);
1062 if (t == TypeManager.sbyte_type){
1063 if (ec.CheckState)
1064 ig.Emit (OpCodes.Conv_Ovf_I1);
1065 else
1066 ig.Emit (OpCodes.Conv_I1);
1067 } else if (t == TypeManager.byte_type){
1068 if (ec.CheckState)
1069 ig.Emit (OpCodes.Conv_Ovf_U1);
1070 else
1071 ig.Emit (OpCodes.Conv_U1);
1072 } else if (t == TypeManager.short_type){
1073 if (ec.CheckState)
1074 ig.Emit (OpCodes.Conv_Ovf_I2);
1075 else
1076 ig.Emit (OpCodes.Conv_I2);
1077 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
1078 if (ec.CheckState)
1079 ig.Emit (OpCodes.Conv_Ovf_U2);
1080 else
1081 ig.Emit (OpCodes.Conv_U2);
1086 void EmitCode (EmitContext ec, bool is_expr)
1088 recurse = true;
1089 this.is_expr = is_expr;
1090 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1093 public override void Emit (EmitContext ec)
1096 // We use recurse to allow ourselfs to be the source
1097 // of an assignment. This little hack prevents us from
1098 // having to allocate another expression
1100 if (recurse) {
1101 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1102 if (method == null)
1103 LoadOneAndEmitOp (ec, expr.Type);
1104 else
1105 ec.ig.Emit (OpCodes.Call, (MethodInfo)method.Method);
1106 recurse = false;
1107 return;
1110 EmitCode (ec, true);
1113 public override void EmitStatement (EmitContext ec)
1115 EmitCode (ec, false);
1118 protected override void CloneTo (CloneContext clonectx, Expression t)
1120 UnaryMutator target = (UnaryMutator) t;
1122 target.expr = expr.Clone (clonectx);
1126 /// <summary>
1127 /// Base class for the `Is' and `As' classes.
1128 /// </summary>
1130 /// <remarks>
1131 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1132 /// size.
1133 /// </remarks>
1134 public abstract class Probe : Expression {
1135 public Expression ProbeType;
1136 protected Expression expr;
1137 protected TypeExpr probe_type_expr;
1139 public Probe (Expression expr, Expression probe_type, Location l)
1141 ProbeType = probe_type;
1142 loc = l;
1143 this.expr = expr;
1146 public Expression Expr {
1147 get {
1148 return expr;
1152 public override Expression DoResolve (EmitContext ec)
1154 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1155 if (probe_type_expr == null)
1156 return null;
1158 expr = expr.Resolve (ec);
1159 if (expr == null)
1160 return null;
1162 if ((probe_type_expr.Type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
1163 Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1164 OperatorName);
1167 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1168 Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1169 OperatorName);
1170 return null;
1173 if (expr.Type == InternalType.AnonymousMethod) {
1174 Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1175 OperatorName);
1176 return null;
1179 return this;
1182 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1184 expr.MutateHoistedGenericType (storey);
1185 probe_type_expr.MutateHoistedGenericType (storey);
1188 protected abstract string OperatorName { get; }
1190 protected override void CloneTo (CloneContext clonectx, Expression t)
1192 Probe target = (Probe) t;
1194 target.expr = expr.Clone (clonectx);
1195 target.ProbeType = ProbeType.Clone (clonectx);
1200 /// <summary>
1201 /// Implementation of the `is' operator.
1202 /// </summary>
1203 public class Is : Probe {
1204 Nullable.Unwrap expr_unwrap;
1206 public Is (Expression expr, Expression probe_type, Location l)
1207 : base (expr, probe_type, l)
1211 public override Expression CreateExpressionTree (EmitContext ec)
1213 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1214 expr.CreateExpressionTree (ec),
1215 new TypeOf (probe_type_expr, loc));
1217 return CreateExpressionFactoryCall ("TypeIs", args);
1220 public override void Emit (EmitContext ec)
1222 ILGenerator ig = ec.ig;
1223 if (expr_unwrap != null) {
1224 expr_unwrap.EmitCheck (ec);
1225 return;
1228 expr.Emit (ec);
1229 ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
1230 ig.Emit (OpCodes.Ldnull);
1231 ig.Emit (OpCodes.Cgt_Un);
1234 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1236 ILGenerator ig = ec.ig;
1237 if (expr_unwrap != null) {
1238 expr_unwrap.EmitCheck (ec);
1239 } else {
1240 expr.Emit (ec);
1241 ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
1243 ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1246 Expression CreateConstantResult (bool result)
1248 if (result)
1249 Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1250 TypeManager.CSharpName (probe_type_expr.Type));
1251 else
1252 Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1253 TypeManager.CSharpName (probe_type_expr.Type));
1255 return ReducedExpression.Create (new BoolConstant (result, loc), this);
1258 public override Expression DoResolve (EmitContext ec)
1260 if (base.DoResolve (ec) == null)
1261 return null;
1263 Type d = expr.Type;
1264 bool d_is_nullable = false;
1267 // If E is a method group or the null literal, or if the type of E is a reference
1268 // type or a nullable type and the value of E is null, the result is false
1270 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1271 return CreateConstantResult (false);
1273 if (TypeManager.IsNullableType (d) && !TypeManager.ContainsGenericParameters (d)) {
1274 d = TypeManager.GetTypeArguments (d) [0];
1275 d_is_nullable = true;
1278 type = TypeManager.bool_type;
1279 eclass = ExprClass.Value;
1280 Type t = probe_type_expr.Type;
1281 bool t_is_nullable = false;
1282 if (TypeManager.IsNullableType (t) && !TypeManager.ContainsGenericParameters (t)) {
1283 t = TypeManager.GetTypeArguments (t) [0];
1284 t_is_nullable = true;
1287 if (TypeManager.IsStruct (t)) {
1288 if (d == t) {
1290 // D and T are the same value types but D can be null
1292 if (d_is_nullable && !t_is_nullable) {
1293 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1294 return this;
1298 // The result is true if D and T are the same value types
1300 return CreateConstantResult (true);
1303 if (TypeManager.IsGenericParameter (d))
1304 return ResolveGenericParameter (t, d);
1307 // An unboxing conversion exists
1309 if (Convert.ExplicitReferenceConversionExists (d, t))
1310 return this;
1311 } else {
1312 if (TypeManager.IsGenericParameter (t))
1313 return ResolveGenericParameter (d, t);
1315 if (TypeManager.IsStruct (d)) {
1316 bool temp;
1317 if (Convert.ImplicitBoxingConversionExists (expr, t, out temp))
1318 return CreateConstantResult (true);
1319 } else {
1320 if (TypeManager.IsGenericParameter (d))
1321 return ResolveGenericParameter (t, d);
1323 if (TypeManager.ContainsGenericParameters (d))
1324 return this;
1326 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1327 Convert.ExplicitReferenceConversionExists (d, t)) {
1328 return this;
1333 return CreateConstantResult (false);
1336 Expression ResolveGenericParameter (Type d, Type t)
1338 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1339 if (constraints != null) {
1340 if (constraints.IsReferenceType && TypeManager.IsStruct (d))
1341 return CreateConstantResult (false);
1343 if (constraints.IsValueType && !TypeManager.IsStruct (d))
1344 return CreateConstantResult (TypeManager.IsEqual (d, t));
1347 if (!TypeManager.IsReferenceType (expr.Type))
1348 expr = new BoxedCast (expr, d);
1350 return this;
1353 protected override string OperatorName {
1354 get { return "is"; }
1358 /// <summary>
1359 /// Implementation of the `as' operator.
1360 /// </summary>
1361 public class As : Probe {
1362 bool do_isinst;
1363 Expression resolved_type;
1365 public As (Expression expr, Expression probe_type, Location l)
1366 : base (expr, probe_type, l)
1370 public override Expression CreateExpressionTree (EmitContext ec)
1372 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1373 expr.CreateExpressionTree (ec),
1374 new TypeOf (probe_type_expr, loc));
1376 return CreateExpressionFactoryCall ("TypeAs", args);
1379 public override void Emit (EmitContext ec)
1381 ILGenerator ig = ec.ig;
1383 expr.Emit (ec);
1385 if (do_isinst)
1386 ig.Emit (OpCodes.Isinst, type);
1388 #if GMCS_SOURCE
1389 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1390 ig.Emit (OpCodes.Unbox_Any, type);
1391 #endif
1394 public override Expression DoResolve (EmitContext ec)
1396 // Because expr is modified
1397 if (eclass != ExprClass.Invalid)
1398 return this;
1400 if (resolved_type == null) {
1401 resolved_type = base.DoResolve (ec);
1403 if (resolved_type == null)
1404 return null;
1407 type = probe_type_expr.Type;
1408 eclass = ExprClass.Value;
1409 Type etype = expr.Type;
1411 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1412 if (probe_type_expr is TypeParameterExpr) {
1413 Report.Error (413, loc,
1414 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1415 probe_type_expr.GetSignatureForError ());
1416 } else {
1417 Report.Error (77, loc,
1418 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1419 TypeManager.CSharpName (type));
1421 return null;
1424 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1425 return Nullable.LiftedNull.CreateFromExpression (this);
1428 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1429 if (e != null){
1430 expr = e;
1431 do_isinst = false;
1432 return this;
1435 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1436 if (TypeManager.IsGenericParameter (etype))
1437 expr = new BoxedCast (expr, etype);
1439 do_isinst = true;
1440 return this;
1443 if (TypeManager.ContainsGenericParameters (etype) ||
1444 TypeManager.ContainsGenericParameters (type)) {
1445 expr = new BoxedCast (expr, etype);
1446 do_isinst = true;
1447 return this;
1450 Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1451 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1453 return null;
1456 protected override string OperatorName {
1457 get { return "as"; }
1460 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1462 type = storey.MutateType (type);
1463 base.MutateHoistedGenericType (storey);
1466 public override bool GetAttributableValue (EmitContext ec, Type value_type, out object value)
1468 return expr.GetAttributableValue (ec, value_type, out value);
1472 /// <summary>
1473 /// This represents a typecast in the source language.
1475 /// FIXME: Cast expressions have an unusual set of parsing
1476 /// rules, we need to figure those out.
1477 /// </summary>
1478 public class Cast : Expression {
1479 Expression target_type;
1480 Expression expr;
1482 public Cast (Expression cast_type, Expression expr)
1483 : this (cast_type, expr, cast_type.Location)
1487 public Cast (Expression cast_type, Expression expr, Location loc)
1489 this.target_type = cast_type;
1490 this.expr = expr;
1491 this.loc = loc;
1494 public Expression TargetType {
1495 get { return target_type; }
1498 public Expression Expr {
1499 get { return expr; }
1502 public override Expression CreateExpressionTree (EmitContext ec)
1504 throw new NotSupportedException ("ET");
1507 public override Expression DoResolve (EmitContext ec)
1509 expr = expr.Resolve (ec);
1510 if (expr == null)
1511 return null;
1513 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1514 if (target == null)
1515 return null;
1517 type = target.Type;
1519 if (type.IsAbstract && type.IsSealed) {
1520 Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1521 return null;
1524 eclass = ExprClass.Value;
1526 Constant c = expr as Constant;
1527 if (c != null) {
1528 c = c.TryReduce (ec, type, loc);
1529 if (c != null)
1530 return c;
1533 if (type.IsPointer && !ec.InUnsafe) {
1534 UnsafeError (loc);
1535 return null;
1537 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1538 return expr;
1541 public override void Emit (EmitContext ec)
1543 throw new Exception ("Should not happen");
1546 protected override void CloneTo (CloneContext clonectx, Expression t)
1548 Cast target = (Cast) t;
1550 target.target_type = target_type.Clone (clonectx);
1551 target.expr = expr.Clone (clonectx);
1556 // C# 2.0 Default value expression
1558 public class DefaultValueExpression : Expression
1560 sealed class DefaultValueNullLiteral : NullLiteral
1562 public DefaultValueNullLiteral (DefaultValueExpression expr)
1563 : base (expr.type, expr.loc)
1567 public override void Error_ValueCannotBeConverted (EmitContext ec, Location loc, Type t, bool expl)
1569 Error_ValueCannotBeConvertedCore (ec, loc, t, expl);
1574 Expression expr;
1576 public DefaultValueExpression (Expression expr, Location loc)
1578 this.expr = expr;
1579 this.loc = loc;
1582 public override Expression CreateExpressionTree (EmitContext ec)
1584 Arguments args = new Arguments (2);
1585 args.Add (new Argument (this));
1586 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1587 return CreateExpressionFactoryCall ("Constant", args);
1590 public override Expression DoResolve (EmitContext ec)
1592 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1593 if (texpr == null)
1594 return null;
1596 type = texpr.Type;
1598 if ((type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
1599 Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1602 if (type.IsPointer)
1603 return new NullLiteral (Location).ConvertImplicitly (type);
1605 if (TypeManager.IsReferenceType (type))
1606 return new DefaultValueNullLiteral (this);
1608 Constant c = New.Constantify (type);
1609 if (c != null)
1610 return c;
1612 eclass = ExprClass.Variable;
1613 return this;
1616 public override void Emit (EmitContext ec)
1618 LocalTemporary temp_storage = new LocalTemporary(type);
1620 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1621 ec.ig.Emit(OpCodes.Initobj, type);
1622 temp_storage.Emit(ec);
1625 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1627 type = storey.MutateType (type);
1630 protected override void CloneTo (CloneContext clonectx, Expression t)
1632 DefaultValueExpression target = (DefaultValueExpression) t;
1634 target.expr = expr.Clone (clonectx);
1638 /// <summary>
1639 /// Binary operators
1640 /// </summary>
1641 public class Binary : Expression, IDynamicBinder
1644 protected class PredefinedOperator {
1645 protected readonly Type left;
1646 protected readonly Type right;
1647 public readonly Operator OperatorsMask;
1648 public Type ReturnType;
1650 public PredefinedOperator (Type ltype, Type rtype, Operator op_mask)
1651 : this (ltype, rtype, op_mask, ltype)
1655 public PredefinedOperator (Type type, Operator op_mask, Type return_type)
1656 : this (type, type, op_mask, return_type)
1660 public PredefinedOperator (Type type, Operator op_mask)
1661 : this (type, type, op_mask, type)
1665 public PredefinedOperator (Type ltype, Type rtype, Operator op_mask, Type return_type)
1667 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1668 throw new InternalErrorException ("Only masked values can be used");
1670 this.left = ltype;
1671 this.right = rtype;
1672 this.OperatorsMask = op_mask;
1673 this.ReturnType = return_type;
1676 public virtual Expression ConvertResult (EmitContext ec, Binary b)
1678 b.type = ReturnType;
1680 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1681 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1684 // A user operators does not support multiple user conversions, but decimal type
1685 // is considered to be predefined type therefore we apply predefined operators rules
1686 // and then look for decimal user-operator implementation
1688 if (left == TypeManager.decimal_type)
1689 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1691 return b;
1694 public bool IsPrimitiveApplicable (Type ltype, Type rtype)
1697 // We are dealing with primitive types only
1699 return left == ltype && ltype == rtype;
1702 public virtual bool IsApplicable (EmitContext ec, Expression lexpr, Expression rexpr)
1704 if (TypeManager.IsEqual (left, lexpr.Type) &&
1705 TypeManager.IsEqual (right, rexpr.Type))
1706 return true;
1708 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1709 Convert.ImplicitConversionExists (ec, rexpr, right);
1712 public PredefinedOperator ResolveBetterOperator (EmitContext ec, PredefinedOperator best_operator)
1714 int result = 0;
1715 if (left != null && best_operator.left != null) {
1716 result = MethodGroupExpr.BetterTypeConversion (ec, best_operator.left, left);
1720 // When second arguments are same as the first one, the result is same
1722 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1723 result |= MethodGroupExpr.BetterTypeConversion (ec, best_operator.right, right);
1726 if (result == 0 || result > 2)
1727 return null;
1729 return result == 1 ? best_operator : this;
1733 class PredefinedStringOperator : PredefinedOperator {
1734 public PredefinedStringOperator (Type type, Operator op_mask)
1735 : base (type, op_mask, type)
1737 ReturnType = TypeManager.string_type;
1740 public PredefinedStringOperator (Type ltype, Type rtype, Operator op_mask)
1741 : base (ltype, rtype, op_mask)
1743 ReturnType = TypeManager.string_type;
1746 public override Expression ConvertResult (EmitContext ec, Binary b)
1749 // Use original expression for nullable arguments
1751 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1752 if (unwrap != null)
1753 b.left = unwrap.Original;
1755 unwrap = b.right as Nullable.Unwrap;
1756 if (unwrap != null)
1757 b.right = unwrap.Original;
1759 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1760 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1763 // Start a new concat expression using converted expression
1765 return new StringConcat (ec, b.loc, b.left, b.right).Resolve (ec);
1769 class PredefinedShiftOperator : PredefinedOperator {
1770 public PredefinedShiftOperator (Type ltype, Operator op_mask) :
1771 base (ltype, TypeManager.int32_type, op_mask)
1775 public override Expression ConvertResult (EmitContext ec, Binary b)
1777 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1779 Expression expr_tree_expr = EmptyCast.Create (b.right, TypeManager.int32_type);
1781 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1784 // b = b.left >> b.right & (0x1f|0x3f)
1786 b.right = new Binary (Operator.BitwiseAnd,
1787 b.right, new IntConstant (right_mask, b.right.Location)).Resolve (ec);
1790 // Expression tree representation does not use & mask
1792 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1793 b.type = ReturnType;
1794 return b;
1798 class PredefinedPointerOperator : PredefinedOperator {
1799 public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask)
1800 : base (ltype, rtype, op_mask)
1804 public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask, Type retType)
1805 : base (ltype, rtype, op_mask, retType)
1809 public PredefinedPointerOperator (Type type, Operator op_mask, Type return_type)
1810 : base (type, op_mask, return_type)
1814 public override bool IsApplicable (EmitContext ec, Expression lexpr, Expression rexpr)
1816 if (left == null) {
1817 if (!lexpr.Type.IsPointer)
1818 return false;
1819 } else {
1820 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1821 return false;
1824 if (right == null) {
1825 if (!rexpr.Type.IsPointer)
1826 return false;
1827 } else {
1828 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1829 return false;
1832 return true;
1835 public override Expression ConvertResult (EmitContext ec, Binary b)
1837 if (left != null) {
1838 b.left = EmptyCast.Create (b.left, left);
1839 } else if (right != null) {
1840 b.right = EmptyCast.Create (b.right, right);
1843 Type r_type = ReturnType;
1844 Expression left_arg, right_arg;
1845 if (r_type == null) {
1846 if (left == null) {
1847 left_arg = b.left;
1848 right_arg = b.right;
1849 r_type = b.left.Type;
1850 } else {
1851 left_arg = b.right;
1852 right_arg = b.left;
1853 r_type = b.right.Type;
1855 } else {
1856 left_arg = b.left;
1857 right_arg = b.right;
1860 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1864 [Flags]
1865 public enum Operator {
1866 Multiply = 0 | ArithmeticMask,
1867 Division = 1 | ArithmeticMask,
1868 Modulus = 2 | ArithmeticMask,
1869 Addition = 3 | ArithmeticMask | AdditionMask,
1870 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1872 LeftShift = 5 | ShiftMask,
1873 RightShift = 6 | ShiftMask,
1875 LessThan = 7 | ComparisonMask | RelationalMask,
1876 GreaterThan = 8 | ComparisonMask | RelationalMask,
1877 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1878 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1879 Equality = 11 | ComparisonMask | EqualityMask,
1880 Inequality = 12 | ComparisonMask | EqualityMask,
1882 BitwiseAnd = 13 | BitwiseMask,
1883 ExclusiveOr = 14 | BitwiseMask,
1884 BitwiseOr = 15 | BitwiseMask,
1886 LogicalAnd = 16 | LogicalMask,
1887 LogicalOr = 17 | LogicalMask,
1890 // Operator masks
1892 ValuesOnlyMask = ArithmeticMask - 1,
1893 ArithmeticMask = 1 << 5,
1894 ShiftMask = 1 << 6,
1895 ComparisonMask = 1 << 7,
1896 EqualityMask = 1 << 8,
1897 BitwiseMask = 1 << 9,
1898 LogicalMask = 1 << 10,
1899 AdditionMask = 1 << 11,
1900 SubtractionMask = 1 << 12,
1901 RelationalMask = 1 << 13
1904 readonly Operator oper;
1905 protected Expression left, right;
1906 readonly bool is_compound;
1907 Expression enum_conversion;
1909 static PredefinedOperator [] standard_operators;
1910 static PredefinedOperator [] pointer_operators;
1912 public Binary (Operator oper, Expression left, Expression right, bool isCompound)
1913 : this (oper, left, right)
1915 this.is_compound = isCompound;
1918 public Binary (Operator oper, Expression left, Expression right)
1920 this.oper = oper;
1921 this.left = left;
1922 this.right = right;
1923 this.loc = left.Location;
1926 public Operator Oper {
1927 get {
1928 return oper;
1932 /// <summary>
1933 /// Returns a stringified representation of the Operator
1934 /// </summary>
1935 string OperName (Operator oper)
1937 string s;
1938 switch (oper){
1939 case Operator.Multiply:
1940 s = "*";
1941 break;
1942 case Operator.Division:
1943 s = "/";
1944 break;
1945 case Operator.Modulus:
1946 s = "%";
1947 break;
1948 case Operator.Addition:
1949 s = "+";
1950 break;
1951 case Operator.Subtraction:
1952 s = "-";
1953 break;
1954 case Operator.LeftShift:
1955 s = "<<";
1956 break;
1957 case Operator.RightShift:
1958 s = ">>";
1959 break;
1960 case Operator.LessThan:
1961 s = "<";
1962 break;
1963 case Operator.GreaterThan:
1964 s = ">";
1965 break;
1966 case Operator.LessThanOrEqual:
1967 s = "<=";
1968 break;
1969 case Operator.GreaterThanOrEqual:
1970 s = ">=";
1971 break;
1972 case Operator.Equality:
1973 s = "==";
1974 break;
1975 case Operator.Inequality:
1976 s = "!=";
1977 break;
1978 case Operator.BitwiseAnd:
1979 s = "&";
1980 break;
1981 case Operator.BitwiseOr:
1982 s = "|";
1983 break;
1984 case Operator.ExclusiveOr:
1985 s = "^";
1986 break;
1987 case Operator.LogicalOr:
1988 s = "||";
1989 break;
1990 case Operator.LogicalAnd:
1991 s = "&&";
1992 break;
1993 default:
1994 s = oper.ToString ();
1995 break;
1998 if (is_compound)
1999 return s + "=";
2001 return s;
2004 public static void Error_OperatorCannotBeApplied (Expression left, Expression right, Operator oper, Location loc)
2006 new Binary (oper, left, right).Error_OperatorCannotBeApplied (left, right);
2009 public static void Error_OperatorCannotBeApplied (Expression left, Expression right, string oper, Location loc)
2011 string l, r;
2012 l = TypeManager.CSharpName (left.Type);
2013 r = TypeManager.CSharpName (right.Type);
2015 Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2016 oper, l, r);
2019 protected void Error_OperatorCannotBeApplied (Expression left, Expression right)
2021 Error_OperatorCannotBeApplied (left, right, OperName (oper), loc);
2025 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2027 string GetOperatorExpressionTypeName ()
2029 switch (oper) {
2030 case Operator.Addition:
2031 return is_compound ? "AddAssign" : "Add";
2032 case Operator.Equality:
2033 return "Equal";
2034 case Operator.Multiply:
2035 return is_compound ? "MultiplyAssign" : "Multiply";
2036 default:
2037 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2041 static string GetOperatorMetadataName (Operator op)
2043 CSharp.Operator.OpType op_type;
2044 switch (op) {
2045 case Operator.Addition:
2046 op_type = CSharp.Operator.OpType.Addition; break;
2047 case Operator.BitwiseAnd:
2048 op_type = CSharp.Operator.OpType.BitwiseAnd; break;
2049 case Operator.BitwiseOr:
2050 op_type = CSharp.Operator.OpType.BitwiseOr; break;
2051 case Operator.Division:
2052 op_type = CSharp.Operator.OpType.Division; break;
2053 case Operator.Equality:
2054 op_type = CSharp.Operator.OpType.Equality; break;
2055 case Operator.ExclusiveOr:
2056 op_type = CSharp.Operator.OpType.ExclusiveOr; break;
2057 case Operator.GreaterThan:
2058 op_type = CSharp.Operator.OpType.GreaterThan; break;
2059 case Operator.GreaterThanOrEqual:
2060 op_type = CSharp.Operator.OpType.GreaterThanOrEqual; break;
2061 case Operator.Inequality:
2062 op_type = CSharp.Operator.OpType.Inequality; break;
2063 case Operator.LeftShift:
2064 op_type = CSharp.Operator.OpType.LeftShift; break;
2065 case Operator.LessThan:
2066 op_type = CSharp.Operator.OpType.LessThan; break;
2067 case Operator.LessThanOrEqual:
2068 op_type = CSharp.Operator.OpType.LessThanOrEqual; break;
2069 case Operator.Modulus:
2070 op_type = CSharp.Operator.OpType.Modulus; break;
2071 case Operator.Multiply:
2072 op_type = CSharp.Operator.OpType.Multiply; break;
2073 case Operator.RightShift:
2074 op_type = CSharp.Operator.OpType.RightShift; break;
2075 case Operator.Subtraction:
2076 op_type = CSharp.Operator.OpType.Subtraction; break;
2077 default:
2078 throw new InternalErrorException (op.ToString ());
2081 return CSharp.Operator.GetMetadataName (op_type);
2084 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, Type l)
2086 OpCode opcode;
2087 ILGenerator ig = ec.ig;
2089 switch (oper){
2090 case Operator.Multiply:
2091 if (ec.CheckState){
2092 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2093 opcode = OpCodes.Mul_Ovf;
2094 else if (!IsFloat (l))
2095 opcode = OpCodes.Mul_Ovf_Un;
2096 else
2097 opcode = OpCodes.Mul;
2098 } else
2099 opcode = OpCodes.Mul;
2101 break;
2103 case Operator.Division:
2104 if (IsUnsigned (l))
2105 opcode = OpCodes.Div_Un;
2106 else
2107 opcode = OpCodes.Div;
2108 break;
2110 case Operator.Modulus:
2111 if (IsUnsigned (l))
2112 opcode = OpCodes.Rem_Un;
2113 else
2114 opcode = OpCodes.Rem;
2115 break;
2117 case Operator.Addition:
2118 if (ec.CheckState){
2119 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2120 opcode = OpCodes.Add_Ovf;
2121 else if (!IsFloat (l))
2122 opcode = OpCodes.Add_Ovf_Un;
2123 else
2124 opcode = OpCodes.Add;
2125 } else
2126 opcode = OpCodes.Add;
2127 break;
2129 case Operator.Subtraction:
2130 if (ec.CheckState){
2131 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2132 opcode = OpCodes.Sub_Ovf;
2133 else if (!IsFloat (l))
2134 opcode = OpCodes.Sub_Ovf_Un;
2135 else
2136 opcode = OpCodes.Sub;
2137 } else
2138 opcode = OpCodes.Sub;
2139 break;
2141 case Operator.RightShift:
2142 if (IsUnsigned (l))
2143 opcode = OpCodes.Shr_Un;
2144 else
2145 opcode = OpCodes.Shr;
2146 break;
2148 case Operator.LeftShift:
2149 opcode = OpCodes.Shl;
2150 break;
2152 case Operator.Equality:
2153 opcode = OpCodes.Ceq;
2154 break;
2156 case Operator.Inequality:
2157 ig.Emit (OpCodes.Ceq);
2158 ig.Emit (OpCodes.Ldc_I4_0);
2160 opcode = OpCodes.Ceq;
2161 break;
2163 case Operator.LessThan:
2164 if (IsUnsigned (l))
2165 opcode = OpCodes.Clt_Un;
2166 else
2167 opcode = OpCodes.Clt;
2168 break;
2170 case Operator.GreaterThan:
2171 if (IsUnsigned (l))
2172 opcode = OpCodes.Cgt_Un;
2173 else
2174 opcode = OpCodes.Cgt;
2175 break;
2177 case Operator.LessThanOrEqual:
2178 if (IsUnsigned (l) || IsFloat (l))
2179 ig.Emit (OpCodes.Cgt_Un);
2180 else
2181 ig.Emit (OpCodes.Cgt);
2182 ig.Emit (OpCodes.Ldc_I4_0);
2184 opcode = OpCodes.Ceq;
2185 break;
2187 case Operator.GreaterThanOrEqual:
2188 if (IsUnsigned (l) || IsFloat (l))
2189 ig.Emit (OpCodes.Clt_Un);
2190 else
2191 ig.Emit (OpCodes.Clt);
2193 ig.Emit (OpCodes.Ldc_I4_0);
2195 opcode = OpCodes.Ceq;
2196 break;
2198 case Operator.BitwiseOr:
2199 opcode = OpCodes.Or;
2200 break;
2202 case Operator.BitwiseAnd:
2203 opcode = OpCodes.And;
2204 break;
2206 case Operator.ExclusiveOr:
2207 opcode = OpCodes.Xor;
2208 break;
2210 default:
2211 throw new InternalErrorException (oper.ToString ());
2214 ig.Emit (opcode);
2217 static bool IsUnsigned (Type t)
2219 if (t.IsPointer)
2220 return true;
2222 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2223 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2226 static bool IsFloat (Type t)
2228 return t == TypeManager.float_type || t == TypeManager.double_type;
2231 Expression ResolveOperator (EmitContext ec)
2233 Type l = left.Type;
2234 Type r = right.Type;
2235 Expression expr;
2236 bool primitives_only = false;
2238 if (standard_operators == null)
2239 CreateStandardOperatorsTable ();
2242 // Handles predefined primitive types
2244 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2245 if ((oper & Operator.ShiftMask) == 0) {
2246 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2247 return null;
2249 primitives_only = true;
2251 } else {
2252 // Pointers
2253 if (l.IsPointer || r.IsPointer)
2254 return ResolveOperatorPointer (ec, l, r);
2256 // Enums
2257 bool lenum = TypeManager.IsEnumType (l);
2258 bool renum = TypeManager.IsEnumType (r);
2259 if (lenum || renum) {
2260 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2262 // TODO: Can this be ambiguous
2263 if (expr != null)
2264 return expr;
2267 // Delegates
2268 if ((oper == Operator.Addition || oper == Operator.Subtraction || (oper & Operator.EqualityMask) != 0) &&
2269 (TypeManager.IsDelegateType (l) || TypeManager.IsDelegateType (r))) {
2271 expr = ResolveOperatorDelegate (ec, l, r);
2273 // TODO: Can this be ambiguous
2274 if (expr != null)
2275 return expr;
2278 // User operators
2279 expr = ResolveUserOperator (ec, l, r);
2280 if (expr != null)
2281 return expr;
2283 // Predefined reference types equality
2284 if ((oper & Operator.EqualityMask) != 0) {
2285 expr = ResolveOperatorEqualityRerefence (ec, l, r);
2286 if (expr != null)
2287 return expr;
2291 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2294 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2295 // if 'left' is not an enumeration constant, create one from the type of 'right'
2296 Constant EnumLiftUp (EmitContext ec, Constant left, Constant right, Location loc)
2298 switch (oper) {
2299 case Operator.BitwiseOr:
2300 case Operator.BitwiseAnd:
2301 case Operator.ExclusiveOr:
2302 case Operator.Equality:
2303 case Operator.Inequality:
2304 case Operator.LessThan:
2305 case Operator.LessThanOrEqual:
2306 case Operator.GreaterThan:
2307 case Operator.GreaterThanOrEqual:
2308 if (TypeManager.IsEnumType (left.Type))
2309 return left;
2311 if (left.IsZeroInteger)
2312 return left.TryReduce (ec, right.Type, loc);
2314 break;
2316 case Operator.Addition:
2317 case Operator.Subtraction:
2318 return left;
2320 case Operator.Multiply:
2321 case Operator.Division:
2322 case Operator.Modulus:
2323 case Operator.LeftShift:
2324 case Operator.RightShift:
2325 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2326 break;
2327 return left;
2329 Error_OperatorCannotBeApplied (this.left, this.right);
2330 return null;
2334 // The `|' operator used on types which were extended is dangerous
2336 void CheckBitwiseOrOnSignExtended ()
2338 OpcodeCast lcast = left as OpcodeCast;
2339 if (lcast != null) {
2340 if (IsUnsigned (lcast.UnderlyingType))
2341 lcast = null;
2344 OpcodeCast rcast = right as OpcodeCast;
2345 if (rcast != null) {
2346 if (IsUnsigned (rcast.UnderlyingType))
2347 rcast = null;
2350 if (lcast == null && rcast == null)
2351 return;
2353 // FIXME: consider constants
2355 Report.Warning (675, 3, loc,
2356 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2357 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2360 static void CreatePointerOperatorsTable ()
2362 ArrayList temp = new ArrayList ();
2365 // Pointer arithmetic:
2367 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2368 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2369 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2370 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2372 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2373 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2374 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2375 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2378 // T* operator + (int y, T* x);
2379 // T* operator + (uint y, T *x);
2380 // T* operator + (long y, T *x);
2381 // T* operator + (ulong y, T *x);
2383 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2384 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2385 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2386 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2389 // long operator - (T* x, T *y)
2391 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2393 pointer_operators = (PredefinedOperator []) temp.ToArray (typeof (PredefinedOperator));
2396 static void CreateStandardOperatorsTable ()
2398 ArrayList temp = new ArrayList ();
2399 Type bool_type = TypeManager.bool_type;
2401 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2402 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2403 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2404 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2405 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2406 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2407 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2409 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2410 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2411 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2412 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2413 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2414 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2415 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2417 temp.Add (new PredefinedOperator (TypeManager.string_type, Operator.EqualityMask, bool_type));
2419 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2420 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2421 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2423 temp.Add (new PredefinedOperator (bool_type,
2424 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2426 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2427 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2428 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2429 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2431 standard_operators = (PredefinedOperator []) temp.ToArray (typeof (PredefinedOperator));
2435 // Rules used during binary numeric promotion
2437 static bool DoNumericPromotion (ref Expression prim_expr, ref Expression second_expr, Type type)
2439 Expression temp;
2440 Type etype;
2442 Constant c = prim_expr as Constant;
2443 if (c != null) {
2444 temp = c.ConvertImplicitly (type);
2445 if (temp != null) {
2446 prim_expr = temp;
2447 return true;
2451 if (type == TypeManager.uint32_type) {
2452 etype = prim_expr.Type;
2453 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2454 type = TypeManager.int64_type;
2456 if (type != second_expr.Type) {
2457 c = second_expr as Constant;
2458 if (c != null)
2459 temp = c.ConvertImplicitly (type);
2460 else
2461 temp = Convert.ImplicitNumericConversion (second_expr, type);
2462 if (temp == null)
2463 return false;
2464 second_expr = temp;
2467 } else if (type == TypeManager.uint64_type) {
2469 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2471 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2472 type == TypeManager.sbyte_type || type == TypeManager.sbyte_type)
2473 return false;
2476 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2477 if (temp == null)
2478 return false;
2480 prim_expr = temp;
2481 return true;
2485 // 7.2.6.2 Binary numeric promotions
2487 public bool DoBinaryOperatorPromotion (EmitContext ec)
2489 Type ltype = left.Type;
2490 Type rtype = right.Type;
2491 Expression temp;
2493 foreach (Type t in ConstantFold.binary_promotions) {
2494 if (t == ltype)
2495 return t == rtype || DoNumericPromotion (ref right, ref left, t);
2497 if (t == rtype)
2498 return t == ltype || DoNumericPromotion (ref left, ref right, t);
2501 Type int32 = TypeManager.int32_type;
2502 if (ltype != int32) {
2503 Constant c = left as Constant;
2504 if (c != null)
2505 temp = c.ConvertImplicitly (int32);
2506 else
2507 temp = Convert.ImplicitNumericConversion (left, int32);
2509 if (temp == null)
2510 return false;
2511 left = temp;
2514 if (rtype != int32) {
2515 Constant c = right as Constant;
2516 if (c != null)
2517 temp = c.ConvertImplicitly (int32);
2518 else
2519 temp = Convert.ImplicitNumericConversion (right, int32);
2521 if (temp == null)
2522 return false;
2523 right = temp;
2526 return true;
2529 public override Expression DoResolve (EmitContext ec)
2531 if (left == null)
2532 return null;
2534 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2535 left = ((ParenthesizedExpression) left).Expr;
2536 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2537 if (left == null)
2538 return null;
2540 if (left.eclass == ExprClass.Type) {
2541 Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2542 return null;
2544 } else
2545 left = left.Resolve (ec);
2547 if (left == null)
2548 return null;
2550 Constant lc = left as Constant;
2552 if (lc != null && lc.Type == TypeManager.bool_type &&
2553 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2554 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2556 // FIXME: resolve right expression as unreachable
2557 // right.Resolve (ec);
2559 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2560 return left;
2563 right = right.Resolve (ec);
2564 if (right == null)
2565 return null;
2567 eclass = ExprClass.Value;
2568 Constant rc = right as Constant;
2570 // The conversion rules are ignored in enum context but why
2571 if (!ec.InEnumContext && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2572 lc = EnumLiftUp (ec, lc, rc, loc);
2573 if (lc != null)
2574 rc = EnumLiftUp (ec, rc, lc, loc);
2577 if (rc != null && lc != null) {
2578 int prev_e = Report.Errors;
2579 Expression e = ConstantFold.BinaryFold (
2580 ec, oper, lc, rc, loc);
2581 if (e != null || Report.Errors != prev_e)
2582 return e;
2583 } else {
2584 if ((oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) &&
2585 ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue))) {
2587 if ((ResolveOperator (ec)) == null) {
2588 Error_OperatorCannotBeApplied (left, right);
2589 return null;
2593 // The result is a constant with side-effect
2595 Constant side_effect = rc == null ?
2596 new SideEffectConstant (lc, right, loc) :
2597 new SideEffectConstant (rc, left, loc);
2599 return ReducedExpression.Create (side_effect, this);
2603 // Comparison warnings
2604 if ((oper & Operator.ComparisonMask) != 0) {
2605 if (left.Equals (right)) {
2606 Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2608 CheckUselessComparison (lc, right.Type);
2609 CheckUselessComparison (rc, left.Type);
2612 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2613 Arguments args = new Arguments (2);
2614 args.Add (new Argument (left));
2615 args.Add (new Argument (right));
2616 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2619 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2620 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2621 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2622 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2623 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2624 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2626 return DoResolveCore (ec, left, right);
2629 protected Expression DoResolveCore (EmitContext ec, Expression left_orig, Expression right_orig)
2631 Expression expr = ResolveOperator (ec);
2632 if (expr == null)
2633 Error_OperatorCannotBeApplied (left_orig, right_orig);
2635 if (left == null || right == null)
2636 throw new InternalErrorException ("Invalid conversion");
2638 if (oper == Operator.BitwiseOr)
2639 CheckBitwiseOrOnSignExtended ();
2641 return expr;
2644 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2646 left.MutateHoistedGenericType (storey);
2647 right.MutateHoistedGenericType (storey);
2651 // D operator + (D x, D y)
2652 // D operator - (D x, D y)
2653 // bool operator == (D x, D y)
2654 // bool operator != (D x, D y)
2656 Expression ResolveOperatorDelegate (EmitContext ec, Type l, Type r)
2658 bool is_equality = (oper & Operator.EqualityMask) != 0;
2659 if (!TypeManager.IsEqual (l, r) && !TypeManager.IsVariantOf (r, l)) {
2660 Expression tmp;
2661 if (right.eclass == ExprClass.MethodGroup || (r == InternalType.AnonymousMethod && !is_equality)) {
2662 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2663 if (tmp == null)
2664 return null;
2665 right = tmp;
2666 r = right.Type;
2667 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod && !is_equality)) {
2668 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2669 if (tmp == null)
2670 return null;
2671 left = tmp;
2672 l = left.Type;
2673 } else {
2674 return null;
2679 // Resolve delegate equality as a user operator
2681 if (is_equality)
2682 return ResolveUserOperator (ec, l, r);
2684 MethodInfo method;
2685 Arguments args = new Arguments (2);
2686 args.Add (new Argument (left));
2687 args.Add (new Argument (right));
2689 if (oper == Operator.Addition) {
2690 if (TypeManager.delegate_combine_delegate_delegate == null) {
2691 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2692 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2695 method = TypeManager.delegate_combine_delegate_delegate;
2696 } else {
2697 if (TypeManager.delegate_remove_delegate_delegate == null) {
2698 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2699 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2702 method = TypeManager.delegate_remove_delegate_delegate;
2705 MethodGroupExpr mg = new MethodGroupExpr (new MemberInfo [] { method }, TypeManager.delegate_type, loc);
2706 mg = mg.OverloadResolve (ec, ref args, false, loc);
2708 return new ClassCast (new UserOperatorCall (mg, args, CreateExpressionTree, loc), l);
2712 // Enumeration operators
2714 Expression ResolveOperatorEnum (EmitContext ec, bool lenum, bool renum, Type ltype, Type rtype)
2717 // bool operator == (E x, E y);
2718 // bool operator != (E x, E y);
2719 // bool operator < (E x, E y);
2720 // bool operator > (E x, E y);
2721 // bool operator <= (E x, E y);
2722 // bool operator >= (E x, E y);
2724 // E operator & (E x, E y);
2725 // E operator | (E x, E y);
2726 // E operator ^ (E x, E y);
2728 // U operator - (E e, E f)
2729 // E operator - (E e, U x)
2731 // E operator + (U x, E e)
2732 // E operator + (E e, U x)
2734 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2735 (oper == Operator.Subtraction && lenum) || (oper == Operator.Addition && lenum != renum)))
2736 return null;
2738 Expression ltemp = left;
2739 Expression rtemp = right;
2740 Type underlying_type;
2741 Expression expr;
2743 if ((oper & Operator.ComparisonMask | Operator.BitwiseMask) != 0) {
2744 if (renum) {
2745 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2746 if (expr != null) {
2747 left = expr;
2748 ltype = expr.Type;
2750 } else if (lenum) {
2751 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2752 if (expr != null) {
2753 right = expr;
2754 rtype = expr.Type;
2759 if (TypeManager.IsEqual (ltype, rtype)) {
2760 underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
2762 if (left is Constant)
2763 left = ((Constant) left).ConvertExplicitly (false, underlying_type);
2764 else
2765 left = EmptyCast.Create (left, underlying_type);
2767 if (right is Constant)
2768 right = ((Constant) right).ConvertExplicitly (false, underlying_type);
2769 else
2770 right = EmptyCast.Create (right, underlying_type);
2771 } else if (lenum) {
2772 underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
2774 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2775 Constant c = right as Constant;
2776 if (c == null || !c.IsDefaultValue)
2777 return null;
2778 } else {
2779 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2780 return null;
2782 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2785 if (left is Constant)
2786 left = ((Constant) left).ConvertExplicitly (false, underlying_type);
2787 else
2788 left = EmptyCast.Create (left, underlying_type);
2790 } else if (renum) {
2791 underlying_type = TypeManager.GetEnumUnderlyingType (rtype);
2793 if (oper != Operator.Addition) {
2794 Constant c = left as Constant;
2795 if (c == null || !c.IsDefaultValue)
2796 return null;
2797 } else {
2798 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2799 return null;
2801 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2804 if (right is Constant)
2805 right = ((Constant) right).ConvertExplicitly (false, underlying_type);
2806 else
2807 right = EmptyCast.Create (right, underlying_type);
2809 } else {
2810 return null;
2814 // C# specification uses explicit cast syntax which means binary promotion
2815 // should happen, however it seems that csc does not do that
2817 if (!DoBinaryOperatorPromotion (ec)) {
2818 left = ltemp;
2819 right = rtemp;
2820 return null;
2823 Type res_type = null;
2824 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2825 Type promoted_type = lenum ? left.Type : right.Type;
2826 enum_conversion = Convert.ExplicitNumericConversion (
2827 new EmptyExpression (promoted_type), underlying_type);
2829 if (oper == Operator.Subtraction && renum && lenum)
2830 res_type = underlying_type;
2831 else if (oper == Operator.Addition && renum)
2832 res_type = rtype;
2833 else
2834 res_type = ltype;
2837 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2838 if (!is_compound || expr == null)
2839 return expr;
2842 // TODO: Need to corectly implemented Coumpound Assigment for all operators
2843 // Section: 7.16.2
2845 if (Convert.ImplicitConversionExists (ec, left, rtype))
2846 return expr;
2848 if (!Convert.ImplicitConversionExists (ec, ltemp, rtype))
2849 return null;
2851 expr = Convert.ExplicitConversion (ec, expr, rtype, loc);
2852 return expr;
2856 // 7.9.6 Reference type equality operators
2858 Binary ResolveOperatorEqualityRerefence (EmitContext ec, Type l, Type r)
2861 // operator != (object a, object b)
2862 // operator == (object a, object b)
2865 // TODO: this method is almost equivalent to Convert.ImplicitReferenceConversion
2867 if (left.eclass == ExprClass.MethodGroup || right.eclass == ExprClass.MethodGroup)
2868 return null;
2870 type = TypeManager.bool_type;
2871 GenericConstraints constraints;
2873 bool lgen = TypeManager.IsGenericParameter (l);
2875 if (TypeManager.IsEqual (l, r)) {
2876 if (lgen) {
2878 // Only allow to compare same reference type parameter
2880 constraints = TypeManager.GetTypeParameterConstraints (l);
2881 if (constraints != null && constraints.IsReferenceType)
2882 return this;
2884 return null;
2887 if (l == InternalType.AnonymousMethod)
2888 return null;
2890 if (TypeManager.IsValueType (l))
2891 return null;
2893 return this;
2896 bool rgen = TypeManager.IsGenericParameter (r);
2899 // a, Both operands are reference-type values or the value null
2900 // b, One operand is a value of type T where T is a type-parameter and
2901 // the other operand is the value null. Furthermore T does not have the
2902 // value type constrain
2904 if (left is NullLiteral || right is NullLiteral) {
2905 if (lgen) {
2906 constraints = TypeManager.GetTypeParameterConstraints (l);
2907 if (constraints != null && constraints.HasValueTypeConstraint)
2908 return null;
2910 left = new BoxedCast (left, TypeManager.object_type);
2911 return this;
2914 if (rgen) {
2915 constraints = TypeManager.GetTypeParameterConstraints (r);
2916 if (constraints != null && constraints.HasValueTypeConstraint)
2917 return null;
2919 right = new BoxedCast (right, TypeManager.object_type);
2920 return this;
2925 // An interface is converted to the object before the
2926 // standard conversion is applied. It's not clear from the
2927 // standard but it looks like it works like that.
2929 if (lgen) {
2930 constraints = TypeManager.GetTypeParameterConstraints (l);
2931 if (constraints == null || constraints.IsReferenceType)
2932 return null;
2933 } else if (l.IsInterface) {
2934 l = TypeManager.object_type;
2935 } else if (TypeManager.IsStruct (l)) {
2936 return null;
2939 if (rgen) {
2940 constraints = TypeManager.GetTypeParameterConstraints (r);
2941 if (constraints == null || constraints.IsReferenceType)
2942 return null;
2943 } else if (r.IsInterface) {
2944 r = TypeManager.object_type;
2945 } else if (TypeManager.IsStruct (r)) {
2946 return null;
2950 const string ref_comparison = "Possible unintended reference comparison. " +
2951 "Consider casting the {0} side of the expression to `string' to compare the values";
2954 // A standard implicit conversion exists from the type of either
2955 // operand to the type of the other operand
2957 if (Convert.ImplicitReferenceConversionExists (left, r)) {
2958 if (l == TypeManager.string_type)
2959 Report.Warning (253, 2, loc, ref_comparison, "right");
2961 return this;
2964 if (Convert.ImplicitReferenceConversionExists (right, l)) {
2965 if (r == TypeManager.string_type)
2966 Report.Warning (252, 2, loc, ref_comparison, "left");
2968 return this;
2971 return null;
2975 Expression ResolveOperatorPointer (EmitContext ec, Type l, Type r)
2978 // bool operator == (void* x, void* y);
2979 // bool operator != (void* x, void* y);
2980 // bool operator < (void* x, void* y);
2981 // bool operator > (void* x, void* y);
2982 // bool operator <= (void* x, void* y);
2983 // bool operator >= (void* x, void* y);
2985 if ((oper & Operator.ComparisonMask) != 0) {
2986 Expression temp;
2987 if (!l.IsPointer) {
2988 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
2989 if (temp == null)
2990 return null;
2991 left = temp;
2994 if (!r.IsPointer) {
2995 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
2996 if (temp == null)
2997 return null;
2998 right = temp;
3001 type = TypeManager.bool_type;
3002 return this;
3005 if (pointer_operators == null)
3006 CreatePointerOperatorsTable ();
3008 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3012 // Build-in operators method overloading
3014 protected virtual Expression ResolveOperatorPredefined (EmitContext ec, PredefinedOperator [] operators, bool primitives_only, Type enum_type)
3016 PredefinedOperator best_operator = null;
3017 Type l = left.Type;
3018 Type r = right.Type;
3019 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3021 foreach (PredefinedOperator po in operators) {
3022 if ((po.OperatorsMask & oper_mask) == 0)
3023 continue;
3025 if (primitives_only) {
3026 if (!po.IsPrimitiveApplicable (l, r))
3027 continue;
3028 } else {
3029 if (!po.IsApplicable (ec, left, right))
3030 continue;
3033 if (best_operator == null) {
3034 best_operator = po;
3035 if (primitives_only)
3036 break;
3038 continue;
3041 best_operator = po.ResolveBetterOperator (ec, best_operator);
3043 if (best_operator == null) {
3044 Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3045 OperName (oper), left.GetSignatureForError (), right.GetSignatureForError ());
3047 best_operator = po;
3048 break;
3052 if (best_operator == null)
3053 return null;
3055 Expression expr = best_operator.ConvertResult (ec, this);
3056 if (enum_type == null)
3057 return expr;
3060 // HACK: required by enum_conversion
3062 expr.Type = enum_type;
3063 return EmptyCast.Create (expr, enum_type);
3067 // Performs user-operator overloading
3069 protected virtual Expression ResolveUserOperator (EmitContext ec, Type l, Type r)
3071 Operator user_oper;
3072 if (oper == Operator.LogicalAnd)
3073 user_oper = Operator.BitwiseAnd;
3074 else if (oper == Operator.LogicalOr)
3075 user_oper = Operator.BitwiseOr;
3076 else
3077 user_oper = oper;
3079 string op = GetOperatorMetadataName (user_oper);
3081 MethodGroupExpr left_operators = MemberLookup (ec.ContainerType, l, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
3082 MethodGroupExpr right_operators = null;
3084 if (!TypeManager.IsEqual (r, l)) {
3085 right_operators = MemberLookup (ec.ContainerType, r, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
3086 if (right_operators == null && left_operators == null)
3087 return null;
3088 } else if (left_operators == null) {
3089 return null;
3092 Arguments args = new Arguments (2);
3093 Argument larg = new Argument (left);
3094 args.Add (larg);
3095 Argument rarg = new Argument (right);
3096 args.Add (rarg);
3098 MethodGroupExpr union;
3101 // User-defined operator implementations always take precedence
3102 // over predefined operator implementations
3104 if (left_operators != null && right_operators != null) {
3105 if (IsPredefinedUserOperator (l, user_oper)) {
3106 union = right_operators.OverloadResolve (ec, ref args, true, loc);
3107 if (union == null)
3108 union = left_operators;
3109 } else if (IsPredefinedUserOperator (r, user_oper)) {
3110 union = left_operators.OverloadResolve (ec, ref args, true, loc);
3111 if (union == null)
3112 union = right_operators;
3113 } else {
3114 union = MethodGroupExpr.MakeUnionSet (left_operators, right_operators, loc);
3116 } else if (left_operators != null) {
3117 union = left_operators;
3118 } else {
3119 union = right_operators;
3122 union = union.OverloadResolve (ec, ref args, true, loc);
3123 if (union == null)
3124 return null;
3126 Expression oper_expr;
3128 // TODO: CreateExpressionTree is allocated every time
3129 if (user_oper != oper) {
3130 oper_expr = new ConditionalLogicalOperator (union, args, CreateExpressionTree,
3131 oper == Operator.LogicalAnd, loc).Resolve (ec);
3132 } else {
3133 oper_expr = new UserOperatorCall (union, args, CreateExpressionTree, loc);
3136 // This is used to check if a test 'x == null' can be optimized to a reference equals,
3137 // and not invoke user operator
3139 if ((oper & Operator.EqualityMask) != 0) {
3140 if ((left is NullLiteral && IsBuildInEqualityOperator (r)) ||
3141 (right is NullLiteral && IsBuildInEqualityOperator (l))) {
3142 type = TypeManager.bool_type;
3143 if (left is NullLiteral || right is NullLiteral)
3144 oper_expr = ReducedExpression.Create (this, oper_expr).Resolve (ec);
3145 } else if (l != r) {
3146 MethodInfo mi = (MethodInfo) union;
3149 // Two System.Delegate(s) are never equal
3151 if (mi.DeclaringType == TypeManager.multicast_delegate_type)
3152 return null;
3157 left = larg.Expr;
3158 right = rarg.Expr;
3159 return oper_expr;
3162 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
3164 return null;
3167 private void CheckUselessComparison (Constant c, Type type)
3169 if (c == null || !IsTypeIntegral (type)
3170 || c is StringConstant
3171 || c is BoolConstant
3172 || c is FloatConstant
3173 || c is DoubleConstant
3174 || c is DecimalConstant
3176 return;
3178 long value = 0;
3180 if (c is ULongConstant) {
3181 ulong uvalue = ((ULongConstant) c).Value;
3182 if (uvalue > long.MaxValue) {
3183 if (type == TypeManager.byte_type ||
3184 type == TypeManager.sbyte_type ||
3185 type == TypeManager.short_type ||
3186 type == TypeManager.ushort_type ||
3187 type == TypeManager.int32_type ||
3188 type == TypeManager.uint32_type ||
3189 type == TypeManager.int64_type ||
3190 type == TypeManager.char_type)
3191 WarnUselessComparison (type);
3192 return;
3194 value = (long) uvalue;
3196 else if (c is ByteConstant)
3197 value = ((ByteConstant) c).Value;
3198 else if (c is SByteConstant)
3199 value = ((SByteConstant) c).Value;
3200 else if (c is ShortConstant)
3201 value = ((ShortConstant) c).Value;
3202 else if (c is UShortConstant)
3203 value = ((UShortConstant) c).Value;
3204 else if (c is IntConstant)
3205 value = ((IntConstant) c).Value;
3206 else if (c is UIntConstant)
3207 value = ((UIntConstant) c).Value;
3208 else if (c is LongConstant)
3209 value = ((LongConstant) c).Value;
3210 else if (c is CharConstant)
3211 value = ((CharConstant)c).Value;
3213 if (value == 0)
3214 return;
3216 if (IsValueOutOfRange (value, type))
3217 WarnUselessComparison (type);
3220 static bool IsValueOutOfRange (long value, Type type)
3222 if (IsTypeUnsigned (type) && value < 0)
3223 return true;
3224 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3225 type == TypeManager.byte_type && value >= 0x100 ||
3226 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3227 type == TypeManager.ushort_type && value >= 0x10000 ||
3228 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3229 type == TypeManager.uint32_type && value >= 0x100000000;
3232 static bool IsBuildInEqualityOperator (Type t)
3234 return t == TypeManager.object_type || t == TypeManager.string_type ||
3235 t == TypeManager.delegate_type || TypeManager.IsDelegateType (t);
3238 static bool IsPredefinedUserOperator (Type t, Operator op)
3241 // Some predefined types have user operators
3243 return (op & Operator.EqualityMask) != 0 && (t == TypeManager.string_type || t == TypeManager.decimal_type);
3246 private static bool IsTypeIntegral (Type type)
3248 return type == TypeManager.uint64_type ||
3249 type == TypeManager.int64_type ||
3250 type == TypeManager.uint32_type ||
3251 type == TypeManager.int32_type ||
3252 type == TypeManager.ushort_type ||
3253 type == TypeManager.short_type ||
3254 type == TypeManager.sbyte_type ||
3255 type == TypeManager.byte_type ||
3256 type == TypeManager.char_type;
3259 private static bool IsTypeUnsigned (Type type)
3261 return type == TypeManager.uint64_type ||
3262 type == TypeManager.uint32_type ||
3263 type == TypeManager.ushort_type ||
3264 type == TypeManager.byte_type ||
3265 type == TypeManager.char_type;
3268 private void WarnUselessComparison (Type type)
3270 Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
3271 TypeManager.CSharpName (type));
3274 /// <remarks>
3275 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3276 /// context of a conditional bool expression. This function will return
3277 /// false if it is was possible to use EmitBranchable, or true if it was.
3279 /// The expression's code is generated, and we will generate a branch to `target'
3280 /// if the resulting expression value is equal to isTrue
3281 /// </remarks>
3282 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3284 ILGenerator ig = ec.ig;
3287 // This is more complicated than it looks, but its just to avoid
3288 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3289 // but on top of that we want for == and != to use a special path
3290 // if we are comparing against null
3292 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
3293 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3296 // put the constant on the rhs, for simplicity
3298 if (left is Constant) {
3299 Expression swap = right;
3300 right = left;
3301 left = swap;
3304 if (((Constant) right).IsZeroInteger) {
3305 left.EmitBranchable (ec, target, my_on_true);
3306 return;
3308 if (right.Type == TypeManager.bool_type) {
3309 // right is a boolean, and it's not 'false' => it is 'true'
3310 left.EmitBranchable (ec, target, !my_on_true);
3311 return;
3314 } else if (oper == Operator.LogicalAnd) {
3316 if (on_true) {
3317 Label tests_end = ig.DefineLabel ();
3319 left.EmitBranchable (ec, tests_end, false);
3320 right.EmitBranchable (ec, target, true);
3321 ig.MarkLabel (tests_end);
3322 } else {
3324 // This optimizes code like this
3325 // if (true && i > 4)
3327 if (!(left is Constant))
3328 left.EmitBranchable (ec, target, false);
3330 if (!(right is Constant))
3331 right.EmitBranchable (ec, target, false);
3334 return;
3336 } else if (oper == Operator.LogicalOr){
3337 if (on_true) {
3338 left.EmitBranchable (ec, target, true);
3339 right.EmitBranchable (ec, target, true);
3341 } else {
3342 Label tests_end = ig.DefineLabel ();
3343 left.EmitBranchable (ec, tests_end, true);
3344 right.EmitBranchable (ec, target, false);
3345 ig.MarkLabel (tests_end);
3348 return;
3350 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
3351 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
3352 oper == Operator.Equality || oper == Operator.Inequality)) {
3353 base.EmitBranchable (ec, target, on_true);
3354 return;
3357 left.Emit (ec);
3358 right.Emit (ec);
3360 Type t = left.Type;
3361 bool is_float = IsFloat (t);
3362 bool is_unsigned = is_float || IsUnsigned (t);
3364 switch (oper){
3365 case Operator.Equality:
3366 if (on_true)
3367 ig.Emit (OpCodes.Beq, target);
3368 else
3369 ig.Emit (OpCodes.Bne_Un, target);
3370 break;
3372 case Operator.Inequality:
3373 if (on_true)
3374 ig.Emit (OpCodes.Bne_Un, target);
3375 else
3376 ig.Emit (OpCodes.Beq, target);
3377 break;
3379 case Operator.LessThan:
3380 if (on_true)
3381 if (is_unsigned && !is_float)
3382 ig.Emit (OpCodes.Blt_Un, target);
3383 else
3384 ig.Emit (OpCodes.Blt, target);
3385 else
3386 if (is_unsigned)
3387 ig.Emit (OpCodes.Bge_Un, target);
3388 else
3389 ig.Emit (OpCodes.Bge, target);
3390 break;
3392 case Operator.GreaterThan:
3393 if (on_true)
3394 if (is_unsigned && !is_float)
3395 ig.Emit (OpCodes.Bgt_Un, target);
3396 else
3397 ig.Emit (OpCodes.Bgt, target);
3398 else
3399 if (is_unsigned)
3400 ig.Emit (OpCodes.Ble_Un, target);
3401 else
3402 ig.Emit (OpCodes.Ble, target);
3403 break;
3405 case Operator.LessThanOrEqual:
3406 if (on_true)
3407 if (is_unsigned && !is_float)
3408 ig.Emit (OpCodes.Ble_Un, target);
3409 else
3410 ig.Emit (OpCodes.Ble, target);
3411 else
3412 if (is_unsigned)
3413 ig.Emit (OpCodes.Bgt_Un, target);
3414 else
3415 ig.Emit (OpCodes.Bgt, target);
3416 break;
3419 case Operator.GreaterThanOrEqual:
3420 if (on_true)
3421 if (is_unsigned && !is_float)
3422 ig.Emit (OpCodes.Bge_Un, target);
3423 else
3424 ig.Emit (OpCodes.Bge, target);
3425 else
3426 if (is_unsigned)
3427 ig.Emit (OpCodes.Blt_Un, target);
3428 else
3429 ig.Emit (OpCodes.Blt, target);
3430 break;
3431 default:
3432 throw new InternalErrorException (oper.ToString ());
3436 public override void Emit (EmitContext ec)
3438 EmitOperator (ec, left.Type);
3441 protected virtual void EmitOperator (EmitContext ec, Type l)
3443 ILGenerator ig = ec.ig;
3446 // Handle short-circuit operators differently
3447 // than the rest
3449 if ((oper & Operator.LogicalMask) != 0) {
3450 Label load_result = ig.DefineLabel ();
3451 Label end = ig.DefineLabel ();
3453 bool is_or = oper == Operator.LogicalOr;
3454 left.EmitBranchable (ec, load_result, is_or);
3455 right.Emit (ec);
3456 ig.Emit (OpCodes.Br_S, end);
3458 ig.MarkLabel (load_result);
3459 ig.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3460 ig.MarkLabel (end);
3461 return;
3464 left.Emit (ec);
3467 // Optimize zero-based operations
3469 // TODO: Implement more optimizations, but it should probably go to PredefinedOperators
3471 if ((oper & Operator.ShiftMask) != 0 || oper == Operator.Addition || oper == Operator.Subtraction) {
3472 Constant rc = right as Constant;
3473 if (rc != null && rc.IsDefaultValue) {
3474 return;
3478 right.Emit (ec);
3479 EmitOperatorOpcode (ec, oper, l);
3482 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3483 // expression because that would wrap lifted binary operation
3485 if (enum_conversion != null)
3486 enum_conversion.Emit (ec);
3489 public override void EmitSideEffect (EmitContext ec)
3491 if ((oper & Operator.LogicalMask) != 0 ||
3492 (ec.CheckState && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3493 base.EmitSideEffect (ec);
3494 } else {
3495 left.EmitSideEffect (ec);
3496 right.EmitSideEffect (ec);
3500 protected override void CloneTo (CloneContext clonectx, Expression t)
3502 Binary target = (Binary) t;
3504 target.left = left.Clone (clonectx);
3505 target.right = right.Clone (clonectx);
3508 public Expression CreateCallSiteBinder (EmitContext ec, Arguments args)
3510 Arguments binder_args = new Arguments (4);
3512 MemberAccess sle = new MemberAccess (new MemberAccess (
3513 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3515 MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace (loc);
3517 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3518 binder_args.Add (new Argument (new BoolLiteral (ec.CheckState, loc)));
3520 bool member_access = left is DynamicMemberBinder || right is DynamicMemberBinder;
3521 binder_args.Add (new Argument (new BoolLiteral (member_access, loc)));
3522 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (), loc)));
3524 return new New (new MemberAccess (binder, "CSharpBinaryOperationBinder", loc), binder_args, loc);
3527 public override Expression CreateExpressionTree (EmitContext ec)
3529 return CreateExpressionTree (ec, null);
3532 Expression CreateExpressionTree (EmitContext ec, MethodGroupExpr method)
3534 string method_name;
3535 bool lift_arg = false;
3537 switch (oper) {
3538 case Operator.Addition:
3539 if (method == null && ec.CheckState && !IsFloat (type))
3540 method_name = "AddChecked";
3541 else
3542 method_name = "Add";
3543 break;
3544 case Operator.BitwiseAnd:
3545 method_name = "And";
3546 break;
3547 case Operator.BitwiseOr:
3548 method_name = "Or";
3549 break;
3550 case Operator.Division:
3551 method_name = "Divide";
3552 break;
3553 case Operator.Equality:
3554 method_name = "Equal";
3555 lift_arg = true;
3556 break;
3557 case Operator.ExclusiveOr:
3558 method_name = "ExclusiveOr";
3559 break;
3560 case Operator.GreaterThan:
3561 method_name = "GreaterThan";
3562 lift_arg = true;
3563 break;
3564 case Operator.GreaterThanOrEqual:
3565 method_name = "GreaterThanOrEqual";
3566 lift_arg = true;
3567 break;
3568 case Operator.Inequality:
3569 method_name = "NotEqual";
3570 lift_arg = true;
3571 break;
3572 case Operator.LeftShift:
3573 method_name = "LeftShift";
3574 break;
3575 case Operator.LessThan:
3576 method_name = "LessThan";
3577 lift_arg = true;
3578 break;
3579 case Operator.LessThanOrEqual:
3580 method_name = "LessThanOrEqual";
3581 lift_arg = true;
3582 break;
3583 case Operator.LogicalAnd:
3584 method_name = "AndAlso";
3585 break;
3586 case Operator.LogicalOr:
3587 method_name = "OrElse";
3588 break;
3589 case Operator.Modulus:
3590 method_name = "Modulo";
3591 break;
3592 case Operator.Multiply:
3593 if (method == null && ec.CheckState && !IsFloat (type))
3594 method_name = "MultiplyChecked";
3595 else
3596 method_name = "Multiply";
3597 break;
3598 case Operator.RightShift:
3599 method_name = "RightShift";
3600 break;
3601 case Operator.Subtraction:
3602 if (method == null && ec.CheckState && !IsFloat (type))
3603 method_name = "SubtractChecked";
3604 else
3605 method_name = "Subtract";
3606 break;
3608 default:
3609 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3612 Arguments args = new Arguments (2);
3613 args.Add (new Argument (left.CreateExpressionTree (ec)));
3614 args.Add (new Argument (right.CreateExpressionTree (ec)));
3615 if (method != null) {
3616 if (lift_arg)
3617 args.Add (new Argument (new BoolConstant (false, loc)));
3619 args.Add (new Argument (method.CreateExpressionTree (ec)));
3622 return CreateExpressionFactoryCall (method_name, args);
3627 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3628 // b, c, d... may be strings or objects.
3630 public class StringConcat : Expression {
3631 Arguments arguments;
3633 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3635 this.loc = loc;
3636 type = TypeManager.string_type;
3637 eclass = ExprClass.Value;
3639 arguments = new Arguments (2);
3640 Append (ec, left);
3641 Append (ec, right);
3644 public override Expression CreateExpressionTree (EmitContext ec)
3646 Argument arg = arguments [0];
3647 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3651 // Creates nested calls tree from an array of arguments used for IL emit
3653 Expression CreateExpressionAddCall (EmitContext ec, Argument left, Expression left_etree, int pos)
3655 Arguments concat_args = new Arguments (2);
3656 Arguments add_args = new Arguments (3);
3658 concat_args.Add (left);
3659 add_args.Add (new Argument (left_etree));
3661 concat_args.Add (arguments [pos]);
3662 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3664 MethodGroupExpr method = CreateConcatMemberExpression ().Resolve (ec) as MethodGroupExpr;
3665 if (method == null)
3666 return null;
3668 method = method.OverloadResolve (ec, ref concat_args, false, loc);
3669 if (method == null)
3670 return null;
3672 add_args.Add (new Argument (method.CreateExpressionTree (ec)));
3674 Expression expr = CreateExpressionFactoryCall ("Add", add_args);
3675 if (++pos == arguments.Count)
3676 return expr;
3678 left = new Argument (new EmptyExpression (((MethodInfo)method).ReturnType));
3679 return CreateExpressionAddCall (ec, left, expr, pos);
3682 public override Expression DoResolve (EmitContext ec)
3684 return this;
3687 public void Append (EmitContext ec, Expression operand)
3690 // Constant folding
3692 StringConstant sc = operand as StringConstant;
3693 if (sc != null) {
3694 if (arguments.Count != 0) {
3695 Argument last_argument = arguments [arguments.Count - 1];
3696 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3697 if (last_expr_constant != null) {
3698 last_argument.Expr = new StringConstant (
3699 last_expr_constant.Value + sc.Value, sc.Location);
3700 return;
3703 } else {
3705 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3707 StringConcat concat_oper = operand as StringConcat;
3708 if (concat_oper != null) {
3709 arguments.AddRange (concat_oper.arguments);
3710 return;
3714 arguments.Add (new Argument (operand));
3717 Expression CreateConcatMemberExpression ()
3719 return new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "String", loc), "Concat", loc);
3722 public override void Emit (EmitContext ec)
3724 Expression concat = new Invocation (CreateConcatMemberExpression (), arguments, true);
3725 concat = concat.Resolve (ec);
3726 if (concat != null)
3727 concat.Emit (ec);
3730 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3732 arguments.MutateHoistedGenericType (storey);
3737 // User-defined conditional logical operator
3739 public class ConditionalLogicalOperator : UserOperatorCall {
3740 readonly bool is_and;
3741 Expression oper;
3743 public ConditionalLogicalOperator (MethodGroupExpr oper_method, Arguments arguments,
3744 ExpressionTreeExpression expr_tree, bool is_and, Location loc)
3745 : base (oper_method, arguments, expr_tree, loc)
3747 this.is_and = is_and;
3750 public override Expression DoResolve (EmitContext ec)
3752 MethodInfo method = (MethodInfo)mg;
3753 type = TypeManager.TypeToCoreType (method.ReturnType);
3754 AParametersCollection pd = TypeManager.GetParameterData (method);
3755 if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
3756 Report.Error (217, loc,
3757 "A user-defined operator `{0}' must have parameters and return values of the same type in order to be applicable as a short circuit operator",
3758 TypeManager.CSharpSignature (method));
3759 return null;
3762 Expression left_dup = new EmptyExpression (type);
3763 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3764 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3765 if (op_true == null || op_false == null) {
3766 Report.Error (218, loc,
3767 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3768 TypeManager.CSharpName (type), TypeManager.CSharpSignature (method));
3769 return null;
3772 oper = is_and ? op_false : op_true;
3773 eclass = ExprClass.Value;
3774 return this;
3777 public override void Emit (EmitContext ec)
3779 ILGenerator ig = ec.ig;
3780 Label end_target = ig.DefineLabel ();
3783 // Emit and duplicate left argument
3785 arguments [0].Expr.Emit (ec);
3786 ig.Emit (OpCodes.Dup);
3787 arguments.RemoveAt (0);
3789 oper.EmitBranchable (ec, end_target, true);
3790 base.Emit (ec);
3791 ig.MarkLabel (end_target);
3795 public class PointerArithmetic : Expression {
3796 Expression left, right;
3797 Binary.Operator op;
3800 // We assume that `l' is always a pointer
3802 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, Type t, Location loc)
3804 type = t;
3805 this.loc = loc;
3806 left = l;
3807 right = r;
3808 this.op = op;
3811 public override Expression CreateExpressionTree (EmitContext ec)
3813 Error_PointerInsideExpressionTree ();
3814 return null;
3817 public override Expression DoResolve (EmitContext ec)
3819 eclass = ExprClass.Variable;
3821 if (left.Type == TypeManager.void_ptr_type) {
3822 Error (242, "The operation in question is undefined on void pointers");
3823 return null;
3826 return this;
3829 public override void Emit (EmitContext ec)
3831 Type op_type = left.Type;
3832 ILGenerator ig = ec.ig;
3834 // It must be either array or fixed buffer
3835 Type element;
3836 if (TypeManager.HasElementType (op_type)) {
3837 element = TypeManager.GetElementType (op_type);
3838 } else {
3839 FieldExpr fe = left as FieldExpr;
3840 if (fe != null)
3841 element = AttributeTester.GetFixedBuffer (fe.FieldInfo).ElementType;
3842 else
3843 element = op_type;
3846 int size = GetTypeSize (element);
3847 Type rtype = right.Type;
3849 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
3851 // handle (pointer - pointer)
3853 left.Emit (ec);
3854 right.Emit (ec);
3855 ig.Emit (OpCodes.Sub);
3857 if (size != 1){
3858 if (size == 0)
3859 ig.Emit (OpCodes.Sizeof, element);
3860 else
3861 IntLiteral.EmitInt (ig, size);
3862 ig.Emit (OpCodes.Div);
3864 ig.Emit (OpCodes.Conv_I8);
3865 } else {
3867 // handle + and - on (pointer op int)
3869 Constant left_const = left as Constant;
3870 if (left_const != null) {
3872 // Optimize ((T*)null) pointer operations
3874 if (left_const.IsDefaultValue) {
3875 left = EmptyExpression.Null;
3876 } else {
3877 left_const = null;
3881 left.Emit (ec);
3883 Constant right_const = right as Constant;
3884 if (right_const != null) {
3886 // Optimize 0-based arithmetic
3888 if (right_const.IsDefaultValue)
3889 return;
3891 if (size != 0) {
3892 right = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size, right.Location), right_const, loc);
3893 if (right == null)
3894 return;
3895 } else {
3896 ig.Emit (OpCodes.Sizeof, element);
3897 right = EmptyExpression.Null;
3901 right.Emit (ec);
3902 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
3903 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
3904 ig.Emit (OpCodes.Conv_I);
3905 } else if (rtype == TypeManager.uint32_type) {
3906 ig.Emit (OpCodes.Conv_U);
3909 if (right_const == null && size != 1){
3910 if (size == 0)
3911 ig.Emit (OpCodes.Sizeof, element);
3912 else
3913 IntLiteral.EmitInt (ig, size);
3914 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3915 ig.Emit (OpCodes.Conv_I8);
3917 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
3920 if (left_const == null) {
3921 if (rtype == TypeManager.int64_type)
3922 ig.Emit (OpCodes.Conv_I);
3923 else if (rtype == TypeManager.uint64_type)
3924 ig.Emit (OpCodes.Conv_U);
3926 Binary.EmitOperatorOpcode (ec, op, op_type);
3932 /// <summary>
3933 /// Implements the ternary conditional operator (?:)
3934 /// </summary>
3935 public class Conditional : Expression {
3936 Expression expr, true_expr, false_expr;
3938 public Conditional (Expression expr, Expression true_expr, Expression false_expr)
3940 this.expr = expr;
3941 this.true_expr = true_expr;
3942 this.false_expr = false_expr;
3943 this.loc = expr.Location;
3946 public Expression Expr {
3947 get {
3948 return expr;
3952 public Expression TrueExpr {
3953 get {
3954 return true_expr;
3958 public Expression FalseExpr {
3959 get {
3960 return false_expr;
3964 public override Expression CreateExpressionTree (EmitContext ec)
3966 Arguments args = new Arguments (3);
3967 args.Add (new Argument (expr.CreateExpressionTree (ec)));
3968 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
3969 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
3970 return CreateExpressionFactoryCall ("Condition", args);
3973 public override Expression DoResolve (EmitContext ec)
3975 expr = Expression.ResolveBoolean (ec, expr, loc);
3977 Assign ass = expr as Assign;
3978 if (ass != null && ass.Source is Constant) {
3979 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
3982 true_expr = true_expr.Resolve (ec);
3983 false_expr = false_expr.Resolve (ec);
3985 if (true_expr == null || false_expr == null || expr == null)
3986 return null;
3988 eclass = ExprClass.Value;
3989 Type true_type = true_expr.Type;
3990 Type false_type = false_expr.Type;
3991 type = true_type;
3994 // First, if an implicit conversion exists from true_expr
3995 // to false_expr, then the result type is of type false_expr.Type
3997 if (!TypeManager.IsEqual (true_type, false_type)) {
3998 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
3999 if (conv != null) {
4001 // Check if both can convert implicitl to each other's type
4003 if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4004 Error (172,
4005 "Can not compute type of conditional expression " +
4006 "as `" + TypeManager.CSharpName (true_expr.Type) +
4007 "' and `" + TypeManager.CSharpName (false_expr.Type) +
4008 "' convert implicitly to each other");
4009 return null;
4011 type = false_type;
4012 true_expr = conv;
4013 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4014 false_expr = conv;
4015 } else {
4016 Report.Error (173, loc,
4017 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4018 true_expr.GetSignatureForError (), false_expr.GetSignatureForError ());
4019 return null;
4023 // Dead code optimalization
4024 Constant c = expr as Constant;
4025 if (c != null){
4026 bool is_false = c.IsDefaultValue;
4027 Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4028 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4031 return this;
4034 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4036 expr.MutateHoistedGenericType (storey);
4037 true_expr.MutateHoistedGenericType (storey);
4038 false_expr.MutateHoistedGenericType (storey);
4039 type = storey.MutateType (type);
4042 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
4044 return null;
4047 public override void Emit (EmitContext ec)
4049 ILGenerator ig = ec.ig;
4050 Label false_target = ig.DefineLabel ();
4051 Label end_target = ig.DefineLabel ();
4053 expr.EmitBranchable (ec, false_target, false);
4054 true_expr.Emit (ec);
4056 if (type.IsInterface) {
4057 LocalBuilder temp = ec.GetTemporaryLocal (type);
4058 ig.Emit (OpCodes.Stloc, temp);
4059 ig.Emit (OpCodes.Ldloc, temp);
4060 ec.FreeTemporaryLocal (temp, type);
4063 ig.Emit (OpCodes.Br, end_target);
4064 ig.MarkLabel (false_target);
4065 false_expr.Emit (ec);
4066 ig.MarkLabel (end_target);
4069 protected override void CloneTo (CloneContext clonectx, Expression t)
4071 Conditional target = (Conditional) t;
4073 target.expr = expr.Clone (clonectx);
4074 target.true_expr = true_expr.Clone (clonectx);
4075 target.false_expr = false_expr.Clone (clonectx);
4079 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4080 LocalTemporary temp;
4082 #region Abstract
4083 public abstract HoistedVariable GetHoistedVariable (EmitContext ec);
4084 public abstract bool IsFixed { get; }
4085 public abstract bool IsRef { get; }
4086 public abstract string Name { get; }
4087 public abstract void SetHasAddressTaken ();
4090 // Variable IL data, it has to be protected to encapsulate hoisted variables
4092 protected abstract ILocalVariable Variable { get; }
4095 // Variable flow-analysis data
4097 public abstract VariableInfo VariableInfo { get; }
4098 #endregion
4100 public void AddressOf (EmitContext ec, AddressOp mode)
4102 HoistedVariable hv = GetHoistedVariable (ec);
4103 if (hv != null) {
4104 hv.AddressOf (ec, mode);
4105 return;
4108 Variable.EmitAddressOf (ec);
4111 public override void Emit (EmitContext ec)
4113 Emit (ec, false);
4116 public override void EmitSideEffect (EmitContext ec)
4118 // do nothing
4122 // This method is used by parameters that are references, that are
4123 // being passed as references: we only want to pass the pointer (that
4124 // is already stored in the parameter, not the address of the pointer,
4125 // and not the value of the variable).
4127 public void EmitLoad (EmitContext ec)
4129 Variable.Emit (ec);
4132 public void Emit (EmitContext ec, bool leave_copy)
4134 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4136 HoistedVariable hv = GetHoistedVariable (ec);
4137 if (hv != null) {
4138 hv.Emit (ec, leave_copy);
4139 return;
4142 EmitLoad (ec);
4144 if (IsRef) {
4146 // If we are a reference, we loaded on the stack a pointer
4147 // Now lets load the real value
4149 LoadFromPtr (ec.ig, type);
4152 if (leave_copy) {
4153 ec.ig.Emit (OpCodes.Dup);
4155 if (IsRef) {
4156 temp = new LocalTemporary (Type);
4157 temp.Store (ec);
4162 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4163 bool prepare_for_load)
4165 HoistedVariable hv = GetHoistedVariable (ec);
4166 if (hv != null) {
4167 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4168 return;
4171 New n_source = source as New;
4172 if (n_source != null) {
4173 if (!n_source.Emit (ec, this)) {
4174 if (leave_copy)
4175 EmitLoad (ec);
4176 return;
4178 } else {
4179 if (IsRef)
4180 EmitLoad (ec);
4182 source.Emit (ec);
4185 if (leave_copy) {
4186 ec.ig.Emit (OpCodes.Dup);
4187 if (IsRef) {
4188 temp = new LocalTemporary (Type);
4189 temp.Store (ec);
4193 if (IsRef)
4194 StoreFromPtr (ec.ig, type);
4195 else
4196 Variable.EmitAssign (ec);
4198 if (temp != null) {
4199 temp.Emit (ec);
4200 temp.Release (ec);
4204 public bool IsHoisted {
4205 get { return GetHoistedVariable (null) != null; }
4208 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4210 type = storey.MutateType (type);
4214 /// <summary>
4215 /// Local variables
4216 /// </summary>
4217 public class LocalVariableReference : VariableReference {
4218 readonly string name;
4219 public Block Block;
4220 public LocalInfo local_info;
4221 bool is_readonly;
4222 bool resolved; // TODO: merge with eclass
4224 public LocalVariableReference (Block block, string name, Location l)
4226 Block = block;
4227 this.name = name;
4228 loc = l;
4232 // Setting `is_readonly' to false will allow you to create a writable
4233 // reference to a read-only variable. This is used by foreach and using.
4235 public LocalVariableReference (Block block, string name, Location l,
4236 LocalInfo local_info, bool is_readonly)
4237 : this (block, name, l)
4239 this.local_info = local_info;
4240 this.is_readonly = is_readonly;
4243 public override VariableInfo VariableInfo {
4244 get { return local_info.VariableInfo; }
4247 public override HoistedVariable GetHoistedVariable (EmitContext ec)
4249 return local_info.HoistedVariableReference;
4253 // A local variable is always fixed
4255 public override bool IsFixed {
4256 get { return true; }
4259 public override bool IsRef {
4260 get { return false; }
4263 public bool IsReadOnly {
4264 get { return is_readonly; }
4267 public override string Name {
4268 get { return name; }
4271 public bool VerifyAssigned (EmitContext ec)
4273 VariableInfo variable_info = local_info.VariableInfo;
4274 return variable_info == null || variable_info.IsAssigned (ec, loc);
4277 void ResolveLocalInfo ()
4279 if (local_info == null) {
4280 local_info = Block.GetLocalInfo (Name);
4281 type = local_info.VariableType;
4282 is_readonly = local_info.ReadOnly;
4286 public override void SetHasAddressTaken ()
4288 local_info.AddressTaken = true;
4291 public override Expression CreateExpressionTree (EmitContext ec)
4293 HoistedVariable hv = GetHoistedVariable (ec);
4294 if (hv != null)
4295 return hv.CreateExpressionTree (ec);
4297 Arguments arg = new Arguments (1);
4298 arg.Add (new Argument (this));
4299 return CreateExpressionFactoryCall ("Constant", arg);
4302 Expression DoResolveBase (EmitContext ec)
4304 type = local_info.VariableType;
4306 Expression e = Block.GetConstantExpression (Name);
4307 if (e != null)
4308 return e.Resolve (ec);
4310 VerifyAssigned (ec);
4313 // If we are referencing a variable from the external block
4314 // flag it for capturing
4316 if (ec.MustCaptureVariable (local_info)) {
4317 if (local_info.AddressTaken)
4318 AnonymousMethodExpression.Error_AddressOfCapturedVar (this, loc);
4320 if (ec.IsVariableCapturingRequired) {
4321 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4322 storey.CaptureLocalVariable (ec, local_info);
4326 resolved |= ec.DoFlowAnalysis;
4327 eclass = ExprClass.Variable;
4328 return this;
4331 public override Expression DoResolve (EmitContext ec)
4333 if (resolved)
4334 return this;
4336 ResolveLocalInfo ();
4337 local_info.Used = true;
4339 if (type == null && local_info.Type is VarExpr) {
4340 local_info.VariableType = TypeManager.object_type;
4341 Error_VariableIsUsedBeforeItIsDeclared (Name);
4342 return null;
4345 return DoResolveBase (ec);
4348 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4350 ResolveLocalInfo ();
4352 // is out param
4353 if (right_side == EmptyExpression.OutAccess)
4354 local_info.Used = true;
4356 // Infer implicitly typed local variable
4357 if (type == null) {
4358 VarExpr ve = local_info.Type as VarExpr;
4359 if (ve != null) {
4360 if (!ve.InferType (ec, right_side))
4361 return null;
4362 type = local_info.VariableType = ve.Type;
4366 if (is_readonly) {
4367 int code;
4368 string msg;
4369 if (right_side == EmptyExpression.OutAccess) {
4370 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4371 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4372 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4373 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4374 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4375 } else if (right_side == EmptyExpression.UnaryAddress) {
4376 code = 459; msg = "Cannot take the address of {1} `{0}'";
4377 } else {
4378 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4380 Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4381 } else if (VariableInfo != null) {
4382 VariableInfo.SetAssigned (ec);
4385 return DoResolveBase (ec);
4388 public override int GetHashCode ()
4390 return Name.GetHashCode ();
4393 public override bool Equals (object obj)
4395 LocalVariableReference lvr = obj as LocalVariableReference;
4396 if (lvr == null)
4397 return false;
4399 return Name == lvr.Name && Block == lvr.Block;
4402 protected override ILocalVariable Variable {
4403 get { return local_info; }
4406 public override string ToString ()
4408 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4411 protected override void CloneTo (CloneContext clonectx, Expression t)
4413 LocalVariableReference target = (LocalVariableReference) t;
4415 target.Block = clonectx.LookupBlock (Block);
4416 if (local_info != null)
4417 target.local_info = clonectx.LookupVariable (local_info);
4421 /// <summary>
4422 /// This represents a reference to a parameter in the intermediate
4423 /// representation.
4424 /// </summary>
4425 public class ParameterReference : VariableReference {
4426 readonly ToplevelParameterInfo pi;
4428 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4430 this.pi = pi;
4431 this.loc = loc;
4434 public override bool IsRef {
4435 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4438 bool HasOutModifier {
4439 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4442 public override HoistedVariable GetHoistedVariable (EmitContext ec)
4444 return pi.Parameter.HoistedVariableReference;
4448 // A ref or out parameter is classified as a moveable variable, even
4449 // if the argument given for the parameter is a fixed variable
4451 public override bool IsFixed {
4452 get { return !IsRef; }
4455 public override string Name {
4456 get { return Parameter.Name; }
4459 public Parameter Parameter {
4460 get { return pi.Parameter; }
4463 public override VariableInfo VariableInfo {
4464 get { return pi.VariableInfo; }
4467 protected override ILocalVariable Variable {
4468 get { return Parameter; }
4471 public bool IsAssigned (EmitContext ec, Location loc)
4473 // HACK: Variables are not captured in probing mode
4474 if (ec.IsInProbingMode)
4475 return true;
4477 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4478 return true;
4480 Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4481 return false;
4484 public override void SetHasAddressTaken ()
4486 Parameter.HasAddressTaken = true;
4489 void SetAssigned (EmitContext ec)
4491 if (HasOutModifier && ec.DoFlowAnalysis)
4492 ec.CurrentBranching.SetAssigned (VariableInfo);
4495 bool DoResolveBase (EmitContext ec)
4497 type = pi.ParameterType;
4498 eclass = ExprClass.Variable;
4500 AnonymousExpression am = ec.CurrentAnonymousMethod;
4501 if (am == null)
4502 return true;
4504 Block b = ec.CurrentBlock;
4505 while (b != null) {
4506 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4507 for (int i = 0; i < p.Length; ++i) {
4508 if (p [i] != Parameter)
4509 continue;
4512 // Skip closest anonymous method parameters
4514 if (b == ec.CurrentBlock && !am.IsIterator)
4515 return true;
4517 if (IsRef) {
4518 Report.Error (1628, loc,
4519 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4520 Name, am.ContainerType);
4523 b = null;
4524 break;
4527 if (b != null)
4528 b = b.Toplevel.Parent;
4531 if (pi.Parameter.HasAddressTaken)
4532 AnonymousMethodExpression.Error_AddressOfCapturedVar (this, loc);
4534 if (ec.IsVariableCapturingRequired) {
4535 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4536 storey.CaptureParameter (ec, this);
4539 return true;
4542 public override int GetHashCode ()
4544 return Name.GetHashCode ();
4547 public override bool Equals (object obj)
4549 ParameterReference pr = obj as ParameterReference;
4550 if (pr == null)
4551 return false;
4553 return Name == pr.Name;
4556 protected override void CloneTo (CloneContext clonectx, Expression target)
4558 // Nothing to clone
4561 public override Expression CreateExpressionTree (EmitContext ec)
4563 HoistedVariable hv = GetHoistedVariable (ec);
4564 if (hv != null)
4565 return hv.CreateExpressionTree (ec);
4567 return Parameter.ExpressionTreeVariableReference ();
4571 // Notice that for ref/out parameters, the type exposed is not the
4572 // same type exposed externally.
4574 // for "ref int a":
4575 // externally we expose "int&"
4576 // here we expose "int".
4578 // We record this in "is_ref". This means that the type system can treat
4579 // the type as it is expected, but when we generate the code, we generate
4580 // the alternate kind of code.
4582 public override Expression DoResolve (EmitContext ec)
4584 if (!DoResolveBase (ec))
4585 return null;
4587 // HACK: Variables are not captured in probing mode
4588 if (ec.IsInProbingMode)
4589 return this;
4591 if (HasOutModifier && ec.DoFlowAnalysis &&
4592 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4593 return null;
4595 return this;
4598 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4600 if (!DoResolveBase (ec))
4601 return null;
4603 // HACK: parameters are not captured when probing is on
4604 if (!ec.IsInProbingMode)
4605 SetAssigned (ec);
4607 return this;
4610 static public void EmitLdArg (ILGenerator ig, int x)
4612 switch (x) {
4613 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4614 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4615 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4616 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4617 default:
4618 if (x > byte.MaxValue)
4619 ig.Emit (OpCodes.Ldarg, x);
4620 else
4621 ig.Emit (OpCodes.Ldarg_S, (byte) x);
4622 break;
4627 /// <summary>
4628 /// Invocation of methods or delegates.
4629 /// </summary>
4630 public class Invocation : ExpressionStatement
4632 protected Arguments arguments;
4633 protected Expression expr;
4634 protected MethodGroupExpr mg;
4635 bool arguments_resolved;
4638 // arguments is an ArrayList, but we do not want to typecast,
4639 // as it might be null.
4641 public Invocation (Expression expr, Arguments arguments)
4643 SimpleName sn = expr as SimpleName;
4644 if (sn != null)
4645 this.expr = sn.GetMethodGroup ();
4646 else
4647 this.expr = expr;
4649 this.arguments = arguments;
4650 if (expr != null)
4651 loc = expr.Location;
4654 public Invocation (Expression expr, Arguments arguments, bool arguments_resolved)
4655 : this (expr, arguments)
4657 this.arguments_resolved = arguments_resolved;
4660 public override Expression CreateExpressionTree (EmitContext ec)
4662 Arguments args;
4665 // Special conversion for nested expression trees
4667 if (TypeManager.DropGenericTypeArguments (type) == TypeManager.expression_type) {
4668 args = new Arguments (1);
4669 args.Add (new Argument (this));
4670 return CreateExpressionFactoryCall ("Quote", args);
4673 Expression instance = mg.IsInstance ?
4674 mg.InstanceExpression.CreateExpressionTree (ec) :
4675 new NullLiteral (loc);
4677 args = Arguments.CreateForExpressionTree (ec, arguments,
4678 instance,
4679 mg.CreateExpressionTree (ec));
4681 if (mg.IsBase)
4682 MemberExpr.Error_BaseAccessInExpressionTree (loc);
4684 return CreateExpressionFactoryCall ("Call", args);
4687 public override Expression DoResolve (EmitContext ec)
4689 // Don't resolve already resolved expression
4690 if (eclass != ExprClass.Invalid)
4691 return this;
4693 Expression expr_resolved = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4694 if (expr_resolved == null)
4695 return null;
4697 mg = expr_resolved as MethodGroupExpr;
4698 if (mg == null) {
4699 Type expr_type = expr_resolved.Type;
4701 if (expr_type == InternalType.Dynamic) {
4702 Arguments args = ((DynamicMemberBinder) expr_resolved).Arguments;
4703 return new DynamicInvocation (expr as MemberAccess, args, loc).Resolve (ec);
4706 if (expr_type != null && TypeManager.IsDelegateType (expr_type)){
4707 return (new DelegateInvocation (
4708 expr_resolved, arguments, loc)).Resolve (ec);
4711 MemberExpr me = expr_resolved as MemberExpr;
4712 if (me == null) {
4713 expr_resolved.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
4714 return null;
4717 mg = ec.TypeContainer.LookupExtensionMethod (me.Type, me.Name, loc);
4718 if (mg == null) {
4719 Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4720 expr_resolved.GetSignatureForError ());
4721 return null;
4724 ((ExtensionMethodGroupExpr)mg).ExtensionExpression = me.InstanceExpression;
4728 // Next, evaluate all the expressions in the argument list
4730 if (arguments != null && !arguments_resolved) {
4731 arguments.Resolve (ec);
4734 mg = DoResolveOverload (ec);
4735 if (mg == null)
4736 return null;
4738 MethodInfo method = (MethodInfo)mg;
4739 if (method != null) {
4740 type = TypeManager.TypeToCoreType (method.ReturnType);
4742 // TODO: this is a copy of mg.ResolveMemberAccess method
4743 Expression iexpr = mg.InstanceExpression;
4744 if (method.IsStatic) {
4745 if (iexpr == null ||
4746 iexpr is This || iexpr is EmptyExpression ||
4747 mg.IdenticalTypeName) {
4748 mg.InstanceExpression = null;
4749 } else {
4750 MemberExpr.error176 (loc, mg.GetSignatureForError ());
4751 return null;
4753 } else {
4754 if (iexpr == null || iexpr == EmptyExpression.Null) {
4755 SimpleName.Error_ObjectRefRequired (ec, loc, mg.GetSignatureForError ());
4760 if (type.IsPointer){
4761 if (!ec.InUnsafe){
4762 UnsafeError (loc);
4763 return null;
4768 // Only base will allow this invocation to happen.
4770 if (mg.IsBase && method.IsAbstract){
4771 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
4772 return null;
4775 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4776 if (mg.IsBase)
4777 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4778 else
4779 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4780 return null;
4783 IsSpecialMethodInvocation (method, loc);
4785 if (mg.InstanceExpression != null)
4786 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4788 eclass = ExprClass.Value;
4789 return this;
4792 protected virtual MethodGroupExpr DoResolveOverload (EmitContext ec)
4794 return mg.OverloadResolve (ec, ref arguments, false, loc);
4797 public static bool IsSpecialMethodInvocation (MethodBase method, Location loc)
4799 if (!TypeManager.IsSpecialMethod (method))
4800 return false;
4802 Report.SymbolRelatedToPreviousError (method);
4803 Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
4804 TypeManager.CSharpSignature (method, true));
4806 return true;
4809 static Type[] GetVarargsTypes (MethodBase mb, Arguments arguments)
4811 AParametersCollection pd = TypeManager.GetParameterData (mb);
4813 Argument a = arguments [pd.Count - 1];
4814 Arglist list = (Arglist) a.Expr;
4816 return list.ArgumentTypes;
4819 /// <summary>
4820 /// This checks the ConditionalAttribute on the method
4821 /// </summary>
4822 public static bool IsMethodExcluded (MethodBase method, Location loc)
4824 if (method.IsConstructor)
4825 return false;
4827 method = TypeManager.DropGenericMethodArguments (method);
4828 if (method.DeclaringType.Module == RootContext.ToplevelTypes.Builder) {
4829 IMethodData md = TypeManager.GetMethod (method);
4830 if (md != null)
4831 return md.IsExcluded ();
4833 // For some methods (generated by delegate class) GetMethod returns null
4834 // because they are not included in builder_to_method table
4835 return false;
4838 return AttributeTester.IsConditionalMethodExcluded (method, loc);
4841 /// <remarks>
4842 /// is_base tells whether we want to force the use of the `call'
4843 /// opcode instead of using callvirt. Call is required to call
4844 /// a specific method, while callvirt will always use the most
4845 /// recent method in the vtable.
4847 /// is_static tells whether this is an invocation on a static method
4849 /// instance_expr is an expression that represents the instance
4850 /// it must be non-null if is_static is false.
4852 /// method is the method to invoke.
4854 /// Arguments is the list of arguments to pass to the method or constructor.
4855 /// </remarks>
4856 public static void EmitCall (EmitContext ec, bool is_base,
4857 Expression instance_expr,
4858 MethodBase method, Arguments Arguments, Location loc)
4860 EmitCall (ec, is_base, instance_expr, method, Arguments, loc, false, false);
4863 // `dup_args' leaves an extra copy of the arguments on the stack
4864 // `omit_args' does not leave any arguments at all.
4865 // So, basically, you could make one call with `dup_args' set to true,
4866 // and then another with `omit_args' set to true, and the two calls
4867 // would have the same set of arguments. However, each argument would
4868 // only have been evaluated once.
4869 public static void EmitCall (EmitContext ec, bool is_base,
4870 Expression instance_expr,
4871 MethodBase method, Arguments Arguments, Location loc,
4872 bool dup_args, bool omit_args)
4874 ILGenerator ig = ec.ig;
4875 bool struct_call = false;
4876 bool this_call = false;
4877 LocalTemporary this_arg = null;
4879 Type decl_type = method.DeclaringType;
4881 if (IsMethodExcluded (method, loc))
4882 return;
4884 bool is_static = method.IsStatic;
4885 if (!is_static){
4886 this_call = instance_expr is This;
4887 if (TypeManager.IsStruct (decl_type) || TypeManager.IsEnumType (decl_type))
4888 struct_call = true;
4891 // If this is ourselves, push "this"
4893 if (!omit_args) {
4894 Type t = null;
4895 Type iexpr_type = instance_expr.Type;
4898 // Push the instance expression
4900 if (TypeManager.IsValueType (iexpr_type) || TypeManager.IsGenericParameter (iexpr_type)) {
4902 // Special case: calls to a function declared in a
4903 // reference-type with a value-type argument need
4904 // to have their value boxed.
4905 if (TypeManager.IsStruct (decl_type) ||
4906 TypeManager.IsGenericParameter (iexpr_type)) {
4908 // If the expression implements IMemoryLocation, then
4909 // we can optimize and use AddressOf on the
4910 // return.
4912 // If not we have to use some temporary storage for
4913 // it.
4914 if (instance_expr is IMemoryLocation) {
4915 ((IMemoryLocation)instance_expr).
4916 AddressOf (ec, AddressOp.LoadStore);
4917 } else {
4918 LocalTemporary temp = new LocalTemporary (iexpr_type);
4919 instance_expr.Emit (ec);
4920 temp.Store (ec);
4921 temp.AddressOf (ec, AddressOp.Load);
4924 // avoid the overhead of doing this all the time.
4925 if (dup_args)
4926 t = TypeManager.GetReferenceType (iexpr_type);
4927 } else {
4928 instance_expr.Emit (ec);
4930 // FIXME: should use instance_expr is IMemoryLocation + constraint.
4931 // to help JIT to produce better code
4932 ig.Emit (OpCodes.Box, instance_expr.Type);
4933 t = TypeManager.object_type;
4935 } else {
4936 instance_expr.Emit (ec);
4937 t = instance_expr.Type;
4940 if (dup_args) {
4941 ig.Emit (OpCodes.Dup);
4942 if (Arguments != null && Arguments.Count != 0) {
4943 this_arg = new LocalTemporary (t);
4944 this_arg.Store (ec);
4950 if (!omit_args && Arguments != null)
4951 Arguments.Emit (ec, dup_args, this_arg);
4953 OpCode call_op;
4954 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual)) {
4955 call_op = OpCodes.Call;
4956 } else {
4957 call_op = OpCodes.Callvirt;
4959 #if GMCS_SOURCE
4960 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
4961 ig.Emit (OpCodes.Constrained, instance_expr.Type);
4962 #endif
4965 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
4966 Type[] varargs_types = GetVarargsTypes (method, Arguments);
4967 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
4968 return;
4972 // If you have:
4973 // this.DoFoo ();
4974 // and DoFoo is not virtual, you can omit the callvirt,
4975 // because you don't need the null checking behavior.
4977 if (method is MethodInfo)
4978 ig.Emit (call_op, (MethodInfo) method);
4979 else
4980 ig.Emit (call_op, (ConstructorInfo) method);
4983 public override void Emit (EmitContext ec)
4985 mg.EmitCall (ec, arguments);
4988 public override void EmitStatement (EmitContext ec)
4990 Emit (ec);
4993 // Pop the return value if there is one
4995 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
4996 ec.ig.Emit (OpCodes.Pop);
4999 protected override void CloneTo (CloneContext clonectx, Expression t)
5001 Invocation target = (Invocation) t;
5003 if (arguments != null)
5004 target.arguments = arguments.Clone (clonectx);
5006 target.expr = expr.Clone (clonectx);
5009 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5011 mg.MutateHoistedGenericType (storey);
5012 if (arguments != null) {
5013 arguments.MutateHoistedGenericType (storey);
5019 // It's either a cast or delegate invocation
5021 public class InvocationOrCast : ExpressionStatement
5023 Expression expr;
5024 Expression argument;
5026 public InvocationOrCast (Expression expr, Expression argument)
5028 this.expr = expr;
5029 this.argument = argument;
5030 this.loc = expr.Location;
5033 public override Expression CreateExpressionTree (EmitContext ec)
5035 throw new NotSupportedException ("ET");
5038 public override Expression DoResolve (EmitContext ec)
5040 Expression e = ResolveCore (ec);
5041 if (e == null)
5042 return null;
5044 return e.Resolve (ec);
5047 Expression ResolveCore (EmitContext ec)
5050 // First try to resolve it as a cast.
5052 TypeExpr te = expr.ResolveAsBaseTerminal (ec, true);
5053 if (te != null) {
5054 return new Cast (te, argument, loc);
5058 // This can either be a type or a delegate invocation.
5059 // Let's just resolve it and see what we'll get.
5061 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5062 if (expr == null)
5063 return null;
5066 // Ok, so it's a Cast.
5068 if (expr.eclass == ExprClass.Type || expr.eclass == ExprClass.TypeParameter) {
5069 return new Cast (expr, argument, loc);
5072 if (expr.eclass == ExprClass.Namespace) {
5073 expr.Error_UnexpectedKind (null, "type", loc);
5074 return null;
5078 // It's a delegate invocation.
5080 if (!TypeManager.IsDelegateType (expr.Type)) {
5081 Error (149, "Method name expected");
5082 return null;
5085 ArrayList args = new ArrayList (1);
5086 args.Add (new Argument (argument, Argument.AType.Expression));
5087 return new DelegateInvocation (expr, args, loc);
5090 public override ExpressionStatement ResolveStatement (EmitContext ec)
5092 Expression e = ResolveCore (ec);
5093 if (e == null)
5094 return null;
5096 ExpressionStatement s = e as ExpressionStatement;
5097 if (s == null) {
5098 Error_InvalidExpressionStatement ();
5099 return null;
5102 return s.ResolveStatement (ec);
5105 public override void Emit (EmitContext ec)
5107 throw new Exception ("Cannot happen");
5110 public override void EmitStatement (EmitContext ec)
5112 throw new Exception ("Cannot happen");
5115 protected override void CloneTo (CloneContext clonectx, Expression t)
5117 InvocationOrCast target = (InvocationOrCast) t;
5119 target.expr = expr.Clone (clonectx);
5120 target.argument = argument.Clone (clonectx);
5125 /// <summary>
5126 /// Implements the new expression
5127 /// </summary>
5128 public class New : ExpressionStatement, IMemoryLocation {
5129 Arguments Arguments;
5132 // During bootstrap, it contains the RequestedType,
5133 // but if `type' is not null, it *might* contain a NewDelegate
5134 // (because of field multi-initialization)
5136 Expression RequestedType;
5138 MethodGroupExpr method;
5140 bool is_type_parameter;
5142 public New (Expression requested_type, Arguments arguments, Location l)
5144 RequestedType = requested_type;
5145 Arguments = arguments;
5146 loc = l;
5149 /// <summary>
5150 /// Converts complex core type syntax like 'new int ()' to simple constant
5151 /// </summary>
5152 public static Constant Constantify (Type t)
5154 if (t == TypeManager.int32_type)
5155 return new IntConstant (0, Location.Null);
5156 if (t == TypeManager.uint32_type)
5157 return new UIntConstant (0, Location.Null);
5158 if (t == TypeManager.int64_type)
5159 return new LongConstant (0, Location.Null);
5160 if (t == TypeManager.uint64_type)
5161 return new ULongConstant (0, Location.Null);
5162 if (t == TypeManager.float_type)
5163 return new FloatConstant (0, Location.Null);
5164 if (t == TypeManager.double_type)
5165 return new DoubleConstant (0, Location.Null);
5166 if (t == TypeManager.short_type)
5167 return new ShortConstant (0, Location.Null);
5168 if (t == TypeManager.ushort_type)
5169 return new UShortConstant (0, Location.Null);
5170 if (t == TypeManager.sbyte_type)
5171 return new SByteConstant (0, Location.Null);
5172 if (t == TypeManager.byte_type)
5173 return new ByteConstant (0, Location.Null);
5174 if (t == TypeManager.char_type)
5175 return new CharConstant ('\0', Location.Null);
5176 if (t == TypeManager.bool_type)
5177 return new BoolConstant (false, Location.Null);
5178 if (t == TypeManager.decimal_type)
5179 return new DecimalConstant (0, Location.Null);
5180 if (TypeManager.IsEnumType (t))
5181 return new EnumConstant (Constantify (TypeManager.GetEnumUnderlyingType (t)), t);
5182 if (TypeManager.IsNullableType (t))
5183 return Nullable.LiftedNull.Create (t, Location.Null);
5185 return null;
5189 // Checks whether the type is an interface that has the
5190 // [ComImport, CoClass] attributes and must be treated
5191 // specially
5193 public Expression CheckComImport (EmitContext ec)
5195 if (!type.IsInterface)
5196 return null;
5199 // Turn the call into:
5200 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5202 Type real_class = AttributeTester.GetCoClassAttribute (type);
5203 if (real_class == null)
5204 return null;
5206 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5207 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5208 return cast.Resolve (ec);
5211 public override Expression CreateExpressionTree (EmitContext ec)
5213 Arguments args;
5214 if (method == null) {
5215 args = new Arguments (1);
5216 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5217 } else {
5218 args = Arguments.CreateForExpressionTree (ec, Arguments,
5219 method.CreateExpressionTree (ec));
5222 return CreateExpressionFactoryCall ("New", args);
5225 public override Expression DoResolve (EmitContext ec)
5228 // The New DoResolve might be called twice when initializing field
5229 // expressions (see EmitFieldInitializers, the call to
5230 // GetInitializerExpression will perform a resolve on the expression,
5231 // and later the assign will trigger another resolution
5233 // This leads to bugs (#37014)
5235 if (type != null){
5236 if (RequestedType is NewDelegate)
5237 return RequestedType;
5238 return this;
5241 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5242 if (texpr == null)
5243 return null;
5245 type = texpr.Type;
5247 if (type.IsPointer) {
5248 Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5249 TypeManager.CSharpName (type));
5250 return null;
5253 if (Arguments == null) {
5254 Constant c = Constantify (type);
5255 if (c != null)
5256 return ReducedExpression.Create (c, this);
5259 if (TypeManager.IsDelegateType (type)) {
5260 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5263 if (TypeManager.IsGenericParameter (type)) {
5264 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
5266 if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
5267 Error (304, String.Format (
5268 "Cannot create an instance of the " +
5269 "variable type '{0}' because it " +
5270 "doesn't have the new() constraint",
5271 type));
5272 return null;
5275 if ((Arguments != null) && (Arguments.Count != 0)) {
5276 Error (417, String.Format (
5277 "`{0}': cannot provide arguments " +
5278 "when creating an instance of a " +
5279 "variable type.", type));
5280 return null;
5283 if (TypeManager.activator_create_instance == null) {
5284 Type activator_type = TypeManager.CoreLookupType ("System", "Activator", Kind.Class, true);
5285 if (activator_type != null) {
5286 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5287 activator_type, "CreateInstance", loc, Type.EmptyTypes);
5291 is_type_parameter = true;
5292 eclass = ExprClass.Value;
5293 return this;
5296 if (type.IsAbstract && type.IsSealed) {
5297 Report.SymbolRelatedToPreviousError (type);
5298 Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5299 return null;
5302 if (type.IsInterface || type.IsAbstract){
5303 if (!TypeManager.IsGenericType (type)) {
5304 RequestedType = CheckComImport (ec);
5305 if (RequestedType != null)
5306 return RequestedType;
5309 Report.SymbolRelatedToPreviousError (type);
5310 Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5311 return null;
5314 bool is_struct = TypeManager.IsStruct (type);
5315 eclass = ExprClass.Value;
5318 // SRE returns a match for .ctor () on structs (the object constructor),
5319 // so we have to manually ignore it.
5321 if (is_struct && Arguments == null)
5322 return this;
5324 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5325 Expression ml = MemberLookupFinal (ec, type, type, ".ctor",
5326 MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5328 if (Arguments != null)
5329 Arguments.Resolve (ec);
5331 if (ml == null)
5332 return null;
5334 method = ml as MethodGroupExpr;
5335 if (method == null) {
5336 ml.Error_UnexpectedKind (ec.DeclContainer, "method group", loc);
5337 return null;
5340 method = method.OverloadResolve (ec, ref Arguments, false, loc);
5341 if (method == null)
5342 return null;
5344 return this;
5347 bool DoEmitTypeParameter (EmitContext ec)
5349 #if GMCS_SOURCE
5350 ILGenerator ig = ec.ig;
5351 // IMemoryLocation ml;
5353 MethodInfo ci = TypeManager.activator_create_instance.MakeGenericMethod (
5354 new Type [] { type });
5356 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
5357 if (gc.HasReferenceTypeConstraint || gc.HasClassConstraint) {
5358 ig.Emit (OpCodes.Call, ci);
5359 return true;
5362 // Allow DoEmit() to be called multiple times.
5363 // We need to create a new LocalTemporary each time since
5364 // you can't share LocalBuilders among ILGeneators.
5365 LocalTemporary temp = new LocalTemporary (type);
5367 Label label_activator = ig.DefineLabel ();
5368 Label label_end = ig.DefineLabel ();
5370 temp.AddressOf (ec, AddressOp.Store);
5371 ig.Emit (OpCodes.Initobj, type);
5373 temp.Emit (ec);
5374 ig.Emit (OpCodes.Box, type);
5375 ig.Emit (OpCodes.Brfalse, label_activator);
5377 temp.AddressOf (ec, AddressOp.Store);
5378 ig.Emit (OpCodes.Initobj, type);
5379 temp.Emit (ec);
5380 ig.Emit (OpCodes.Br_S, label_end);
5382 ig.MarkLabel (label_activator);
5384 ig.Emit (OpCodes.Call, ci);
5385 ig.MarkLabel (label_end);
5386 return true;
5387 #else
5388 throw new InternalErrorException ();
5389 #endif
5393 // This Emit can be invoked in two contexts:
5394 // * As a mechanism that will leave a value on the stack (new object)
5395 // * As one that wont (init struct)
5397 // If we are dealing with a ValueType, we have a few
5398 // situations to deal with:
5400 // * The target is a ValueType, and we have been provided
5401 // the instance (this is easy, we are being assigned).
5403 // * The target of New is being passed as an argument,
5404 // to a boxing operation or a function that takes a
5405 // ValueType.
5407 // In this case, we need to create a temporary variable
5408 // that is the argument of New.
5410 // Returns whether a value is left on the stack
5412 // *** Implementation note ***
5414 // To benefit from this optimization, each assignable expression
5415 // has to manually cast to New and call this Emit.
5417 // TODO: It's worth to implement it for arrays and fields
5419 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5421 bool is_value_type = TypeManager.IsValueType (type);
5422 ILGenerator ig = ec.ig;
5423 VariableReference vr = target as VariableReference;
5425 if (target != null && is_value_type && (vr != null || method == null)) {
5426 target.AddressOf (ec, AddressOp.Store);
5427 } else if (vr != null && vr.IsRef) {
5428 vr.EmitLoad (ec);
5431 if (is_type_parameter)
5432 return DoEmitTypeParameter (ec);
5434 if (Arguments != null)
5435 Arguments.Emit (ec);
5437 if (is_value_type) {
5438 if (method == null) {
5439 ig.Emit (OpCodes.Initobj, type);
5440 return false;
5443 if (vr != null) {
5444 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5445 return false;
5449 ConstructorInfo ci = (ConstructorInfo) method;
5450 #if MS_COMPATIBLE
5451 if (TypeManager.IsGenericType (type))
5452 ci = TypeBuilder.GetConstructor (type, ci);
5453 #endif
5455 ig.Emit (OpCodes.Newobj, ci);
5456 return true;
5459 public override void Emit (EmitContext ec)
5461 LocalTemporary v = null;
5462 if (method == null && TypeManager.IsValueType (type)) {
5463 // TODO: Use temporary variable from pool
5464 v = new LocalTemporary (type);
5467 if (!Emit (ec, v))
5468 v.Emit (ec);
5471 public override void EmitStatement (EmitContext ec)
5473 LocalTemporary v = null;
5474 if (method == null && TypeManager.IsValueType (type)) {
5475 // TODO: Use temporary variable from pool
5476 v = new LocalTemporary (type);
5479 if (Emit (ec, v))
5480 ec.ig.Emit (OpCodes.Pop);
5483 public bool IsDefaultValueType {
5484 get {
5485 return TypeManager.IsValueType (type) && !HasInitializer && Arguments == null;
5489 public virtual bool HasInitializer {
5490 get {
5491 return false;
5495 public void AddressOf (EmitContext ec, AddressOp mode)
5497 EmitAddressOf (ec, mode);
5500 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5502 LocalTemporary value_target = new LocalTemporary (type);
5504 if (is_type_parameter) {
5505 DoEmitTypeParameter (ec);
5506 value_target.Store (ec);
5507 value_target.AddressOf (ec, mode);
5508 return value_target;
5511 if (!TypeManager.IsStruct (type)){
5513 // We throw an exception. So far, I believe we only need to support
5514 // value types:
5515 // foreach (int j in new StructType ())
5516 // see bug 42390
5518 throw new Exception ("AddressOf should not be used for classes");
5521 value_target.AddressOf (ec, AddressOp.Store);
5523 if (method == null) {
5524 ec.ig.Emit (OpCodes.Initobj, type);
5525 } else {
5526 if (Arguments != null)
5527 Arguments.Emit (ec);
5529 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5532 value_target.AddressOf (ec, mode);
5533 return value_target;
5536 protected override void CloneTo (CloneContext clonectx, Expression t)
5538 New target = (New) t;
5540 target.RequestedType = RequestedType.Clone (clonectx);
5541 if (Arguments != null){
5542 target.Arguments = Arguments.Clone (clonectx);
5546 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5548 if (method != null) {
5549 method.MutateHoistedGenericType (storey);
5550 if (Arguments != null) {
5551 Arguments.MutateHoistedGenericType (storey);
5555 type = storey.MutateType (type);
5559 /// <summary>
5560 /// 14.5.10.2: Represents an array creation expression.
5561 /// </summary>
5563 /// <remarks>
5564 /// There are two possible scenarios here: one is an array creation
5565 /// expression that specifies the dimensions and optionally the
5566 /// initialization data and the other which does not need dimensions
5567 /// specified but where initialization data is mandatory.
5568 /// </remarks>
5569 public class ArrayCreation : Expression {
5570 FullNamedExpression requested_base_type;
5571 ArrayList initializers;
5574 // The list of Argument types.
5575 // This is used to construct the `newarray' or constructor signature
5577 protected ArrayList arguments;
5579 protected Type array_element_type;
5580 bool expect_initializers = false;
5581 int num_arguments = 0;
5582 protected int dimensions;
5583 protected readonly string rank;
5585 protected ArrayList array_data;
5587 IDictionary bounds;
5589 // The number of constants in array initializers
5590 int const_initializers_count;
5591 bool only_constant_initializers;
5593 public ArrayCreation (FullNamedExpression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5595 this.requested_base_type = requested_base_type;
5596 this.initializers = initializers;
5597 this.rank = rank;
5598 loc = l;
5600 arguments = new ArrayList (exprs.Count);
5602 foreach (Expression e in exprs) {
5603 arguments.Add (e);
5604 num_arguments++;
5608 public ArrayCreation (FullNamedExpression requested_base_type, string rank, ArrayList initializers, Location l)
5610 this.requested_base_type = requested_base_type;
5611 this.initializers = initializers;
5612 this.rank = rank;
5613 loc = l;
5615 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5617 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5619 //dimensions = tmp.Length - 1;
5620 expect_initializers = true;
5623 public static void Error_IncorrectArrayInitializer (Location loc)
5625 Report.Error (178, loc, "Invalid rank specifier: expected `,' or `]'");
5628 protected override void Error_NegativeArrayIndex (Location loc)
5630 Report.Error (248, loc, "Cannot create an array with a negative size");
5633 bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims, int child_bounds)
5635 if (specified_dims) {
5636 Expression a = (Expression) arguments [idx];
5637 a = a.Resolve (ec);
5638 if (a == null)
5639 return false;
5641 Constant c = a as Constant;
5642 if (c != null) {
5643 c = c.ImplicitConversionRequired (ec, TypeManager.int32_type, a.Location);
5646 if (c == null) {
5647 Report.Error (150, a.Location, "A constant value is expected");
5648 return false;
5651 int value = (int) c.GetValue ();
5653 if (value != probe.Count) {
5654 Report.Error (847, loc, "An array initializer of length `{0}' was expected", value);
5655 return false;
5658 bounds [idx] = value;
5661 only_constant_initializers = true;
5662 for (int i = 0; i < probe.Count; ++i) {
5663 object o = probe [i];
5664 if (o is ArrayList) {
5665 ArrayList sub_probe = o as ArrayList;
5666 if (idx + 1 >= dimensions){
5667 Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5668 return false;
5671 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5672 if (!ret)
5673 return false;
5674 } else if (child_bounds > 1) {
5675 Report.Error (846, ((Expression) o).Location, "A nested array initializer was expected");
5676 } else {
5677 Expression element = ResolveArrayElement (ec, (Expression) o);
5678 if (element == null)
5679 continue;
5681 // Initializers with the default values can be ignored
5682 Constant c = element as Constant;
5683 if (c != null) {
5684 if (c.IsDefaultInitializer (array_element_type)) {
5685 element = null;
5687 else {
5688 ++const_initializers_count;
5690 } else {
5691 only_constant_initializers = false;
5694 array_data.Add (element);
5698 return true;
5701 public override Expression CreateExpressionTree (EmitContext ec)
5703 Arguments args;
5705 if (array_data == null) {
5706 args = new Arguments (arguments.Count + 1);
5707 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5708 foreach (Expression a in arguments) {
5709 if (arguments.Count == 1) {
5710 Constant c = a as Constant;
5711 if (c.IsDefaultValue)
5712 return CreateExpressionFactoryCall ("NewArrayInit", args);
5714 args.Add (new Argument (a.CreateExpressionTree (ec)));
5717 return CreateExpressionFactoryCall ("NewArrayBounds", args);
5720 if (dimensions > 1) {
5721 Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5722 return null;
5725 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5726 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5727 if (array_data != null) {
5728 for (int i = 0; i < array_data.Count; ++i) {
5729 Expression e = (Expression) array_data [i];
5730 if (e == null)
5731 e = Convert.ImplicitConversion (ec, (Expression) initializers [i], array_element_type, loc);
5733 args.Add (new Argument (e.CreateExpressionTree (ec)));
5737 return CreateExpressionFactoryCall ("NewArrayInit", args);
5740 public void UpdateIndices ()
5742 int i = 0;
5743 for (ArrayList probe = initializers; probe != null;) {
5744 if (probe.Count > 0 && probe [0] is ArrayList) {
5745 Expression e = new IntConstant (probe.Count, Location.Null);
5746 arguments.Add (e);
5748 bounds [i++] = probe.Count;
5750 probe = (ArrayList) probe [0];
5752 } else {
5753 Expression e = new IntConstant (probe.Count, Location.Null);
5754 arguments.Add (e);
5756 bounds [i++] = probe.Count;
5757 return;
5763 Expression first_emit;
5764 LocalTemporary first_emit_temp;
5766 protected virtual Expression ResolveArrayElement (EmitContext ec, Expression element)
5768 element = element.Resolve (ec);
5769 if (element == null)
5770 return null;
5772 if (element is CompoundAssign.TargetExpression) {
5773 if (first_emit != null)
5774 throw new InternalErrorException ("Can only handle one mutator at a time");
5775 first_emit = element;
5776 element = first_emit_temp = new LocalTemporary (element.Type);
5779 return Convert.ImplicitConversionRequired (
5780 ec, element, array_element_type, loc);
5783 protected bool ResolveInitializers (EmitContext ec)
5785 if (initializers == null) {
5786 return !expect_initializers;
5790 // We use this to store all the date values in the order in which we
5791 // will need to store them in the byte blob later
5793 array_data = new ArrayList ();
5794 bounds = new System.Collections.Specialized.HybridDictionary ();
5796 if (arguments != null)
5797 return CheckIndices (ec, initializers, 0, true, dimensions);
5799 arguments = new ArrayList ();
5801 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5802 return false;
5804 UpdateIndices ();
5806 return true;
5810 // Resolved the type of the array
5812 bool ResolveArrayType (EmitContext ec)
5814 if (requested_base_type == null) {
5815 Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5816 return false;
5819 if (requested_base_type is VarExpr) {
5820 Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5821 return false;
5824 StringBuilder array_qualifier = new StringBuilder (rank);
5827 // `In the first form allocates an array instace of the type that results
5828 // from deleting each of the individual expression from the expression list'
5830 if (num_arguments > 0) {
5831 array_qualifier.Append ("[");
5832 for (int i = num_arguments-1; i > 0; i--)
5833 array_qualifier.Append (",");
5834 array_qualifier.Append ("]");
5838 // Lookup the type
5840 TypeExpr array_type_expr;
5841 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5842 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5843 if (array_type_expr == null)
5844 return false;
5846 type = array_type_expr.Type;
5847 array_element_type = TypeManager.GetElementType (type);
5848 dimensions = type.GetArrayRank ();
5850 return true;
5853 public override Expression DoResolve (EmitContext ec)
5855 if (type != null)
5856 return this;
5858 if (!ResolveArrayType (ec))
5859 return null;
5862 // First step is to validate the initializers and fill
5863 // in any missing bits
5865 if (!ResolveInitializers (ec))
5866 return null;
5868 for (int i = 0; i < arguments.Count; ++i) {
5869 Expression e = ((Expression) arguments[i]).Resolve (ec);
5870 if (e == null)
5871 continue;
5873 arguments [i] = ConvertExpressionToArrayIndex (ec, e);
5876 eclass = ExprClass.Value;
5877 return this;
5880 MethodInfo GetArrayMethod (int arguments)
5882 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
5884 Type[] arg_types = new Type[arguments];
5885 for (int i = 0; i < arguments; i++)
5886 arg_types[i] = TypeManager.int32_type;
5888 MethodInfo mi = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5889 arg_types);
5891 if (mi == null) {
5892 Report.Error (-6, "New invocation: Can not find a constructor for " +
5893 "this argument list");
5894 return null;
5897 return mi;
5900 byte [] MakeByteBlob ()
5902 int factor;
5903 byte [] data;
5904 byte [] element;
5905 int count = array_data.Count;
5907 if (TypeManager.IsEnumType (array_element_type))
5908 array_element_type = TypeManager.GetEnumUnderlyingType (array_element_type);
5910 factor = GetTypeSize (array_element_type);
5911 if (factor == 0)
5912 throw new Exception ("unrecognized type in MakeByteBlob: " + array_element_type);
5914 data = new byte [(count * factor + 3) & ~3];
5915 int idx = 0;
5917 for (int i = 0; i < count; ++i) {
5918 object v = array_data [i];
5920 if (v is EnumConstant)
5921 v = ((EnumConstant) v).Child;
5923 if (v is Constant && !(v is StringConstant))
5924 v = ((Constant) v).GetValue ();
5925 else {
5926 idx += factor;
5927 continue;
5930 if (array_element_type == TypeManager.int64_type){
5931 if (!(v is Expression)){
5932 long val = (long) v;
5934 for (int j = 0; j < factor; ++j) {
5935 data [idx + j] = (byte) (val & 0xFF);
5936 val = (val >> 8);
5939 } else if (array_element_type == TypeManager.uint64_type){
5940 if (!(v is Expression)){
5941 ulong val = (ulong) v;
5943 for (int j = 0; j < factor; ++j) {
5944 data [idx + j] = (byte) (val & 0xFF);
5945 val = (val >> 8);
5948 } else if (array_element_type == TypeManager.float_type) {
5949 if (!(v is Expression)){
5950 element = BitConverter.GetBytes ((float) v);
5952 for (int j = 0; j < factor; ++j)
5953 data [idx + j] = element [j];
5954 if (!BitConverter.IsLittleEndian)
5955 System.Array.Reverse (data, idx, 4);
5957 } else if (array_element_type == TypeManager.double_type) {
5958 if (!(v is Expression)){
5959 element = BitConverter.GetBytes ((double) v);
5961 for (int j = 0; j < factor; ++j)
5962 data [idx + j] = element [j];
5964 // FIXME: Handle the ARM float format.
5965 if (!BitConverter.IsLittleEndian)
5966 System.Array.Reverse (data, idx, 8);
5968 } else if (array_element_type == TypeManager.char_type){
5969 if (!(v is Expression)){
5970 int val = (int) ((char) v);
5972 data [idx] = (byte) (val & 0xff);
5973 data [idx+1] = (byte) (val >> 8);
5975 } else if (array_element_type == TypeManager.short_type){
5976 if (!(v is Expression)){
5977 int val = (int) ((short) v);
5979 data [idx] = (byte) (val & 0xff);
5980 data [idx+1] = (byte) (val >> 8);
5982 } else if (array_element_type == TypeManager.ushort_type){
5983 if (!(v is Expression)){
5984 int val = (int) ((ushort) v);
5986 data [idx] = (byte) (val & 0xff);
5987 data [idx+1] = (byte) (val >> 8);
5989 } else if (array_element_type == TypeManager.int32_type) {
5990 if (!(v is Expression)){
5991 int val = (int) v;
5993 data [idx] = (byte) (val & 0xff);
5994 data [idx+1] = (byte) ((val >> 8) & 0xff);
5995 data [idx+2] = (byte) ((val >> 16) & 0xff);
5996 data [idx+3] = (byte) (val >> 24);
5998 } else if (array_element_type == TypeManager.uint32_type) {
5999 if (!(v is Expression)){
6000 uint val = (uint) v;
6002 data [idx] = (byte) (val & 0xff);
6003 data [idx+1] = (byte) ((val >> 8) & 0xff);
6004 data [idx+2] = (byte) ((val >> 16) & 0xff);
6005 data [idx+3] = (byte) (val >> 24);
6007 } else if (array_element_type == TypeManager.sbyte_type) {
6008 if (!(v is Expression)){
6009 sbyte val = (sbyte) v;
6010 data [idx] = (byte) val;
6012 } else if (array_element_type == TypeManager.byte_type) {
6013 if (!(v is Expression)){
6014 byte val = (byte) v;
6015 data [idx] = (byte) val;
6017 } else if (array_element_type == TypeManager.bool_type) {
6018 if (!(v is Expression)){
6019 bool val = (bool) v;
6020 data [idx] = (byte) (val ? 1 : 0);
6022 } else if (array_element_type == TypeManager.decimal_type){
6023 if (!(v is Expression)){
6024 int [] bits = Decimal.GetBits ((decimal) v);
6025 int p = idx;
6027 // FIXME: For some reason, this doesn't work on the MS runtime.
6028 int [] nbits = new int [4];
6029 nbits [0] = bits [3];
6030 nbits [1] = bits [2];
6031 nbits [2] = bits [0];
6032 nbits [3] = bits [1];
6034 for (int j = 0; j < 4; j++){
6035 data [p++] = (byte) (nbits [j] & 0xff);
6036 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6037 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6038 data [p++] = (byte) (nbits [j] >> 24);
6041 } else
6042 throw new Exception ("Unrecognized type in MakeByteBlob: " + array_element_type);
6044 idx += factor;
6047 return data;
6050 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
6052 array_element_type = storey.MutateType (array_element_type);
6053 type = storey.MutateType (type);
6054 if (arguments != null) {
6055 foreach (Expression e in arguments)
6056 e.MutateHoistedGenericType (storey);
6059 if (array_data != null) {
6060 foreach (Expression e in array_data) {
6061 // Don't mutate values optimized away
6062 if (e == null)
6063 continue;
6065 e.MutateHoistedGenericType (storey);
6071 // Emits the initializers for the array
6073 void EmitStaticInitializers (EmitContext ec)
6075 // FIXME: This should go to Resolve !
6076 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6077 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6078 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6079 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6080 if (TypeManager.void_initializearray_array_fieldhandle == null)
6081 return;
6085 // First, the static data
6087 FieldBuilder fb;
6088 ILGenerator ig = ec.ig;
6090 byte [] data = MakeByteBlob ();
6092 fb = RootContext.MakeStaticData (data);
6094 ig.Emit (OpCodes.Dup);
6095 ig.Emit (OpCodes.Ldtoken, fb);
6096 ig.Emit (OpCodes.Call,
6097 TypeManager.void_initializearray_array_fieldhandle);
6101 // Emits pieces of the array that can not be computed at compile
6102 // time (variables and string locations).
6104 // This always expect the top value on the stack to be the array
6106 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6108 ILGenerator ig = ec.ig;
6109 int dims = bounds.Count;
6110 int [] current_pos = new int [dims];
6112 MethodInfo set = null;
6114 if (dims != 1){
6115 Type [] args = new Type [dims + 1];
6117 for (int j = 0; j < dims; j++)
6118 args [j] = TypeManager.int32_type;
6119 args [dims] = array_element_type;
6121 set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
6122 type, "Set",
6123 CallingConventions.HasThis | CallingConventions.Standard,
6124 TypeManager.void_type, args);
6127 for (int i = 0; i < array_data.Count; i++){
6129 Expression e = (Expression)array_data [i];
6131 // Constant can be initialized via StaticInitializer
6132 if (e != null && !(!emitConstants && e is Constant)) {
6133 Type etype = e.Type;
6135 ig.Emit (OpCodes.Dup);
6137 for (int idx = 0; idx < dims; idx++)
6138 IntConstant.EmitInt (ig, current_pos [idx]);
6141 // If we are dealing with a struct, get the
6142 // address of it, so we can store it.
6144 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6145 (!TypeManager.IsBuiltinOrEnum (etype) ||
6146 etype == TypeManager.decimal_type)) {
6148 ig.Emit (OpCodes.Ldelema, etype);
6151 e.Emit (ec);
6153 if (dims == 1) {
6154 bool is_stobj, has_type_arg;
6155 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj, out has_type_arg);
6156 if (is_stobj)
6157 ig.Emit (OpCodes.Stobj, etype);
6158 else if (has_type_arg)
6159 ig.Emit (op, etype);
6160 else
6161 ig.Emit (op);
6162 } else
6163 ig.Emit (OpCodes.Call, set);
6168 // Advance counter
6170 for (int j = dims - 1; j >= 0; j--){
6171 current_pos [j]++;
6172 if (current_pos [j] < (int) bounds [j])
6173 break;
6174 current_pos [j] = 0;
6179 public override void Emit (EmitContext ec)
6181 ILGenerator ig = ec.ig;
6183 if (first_emit != null) {
6184 first_emit.Emit (ec);
6185 first_emit_temp.Store (ec);
6188 foreach (Expression e in arguments)
6189 e.Emit (ec);
6191 if (arguments.Count == 1)
6192 ig.Emit (OpCodes.Newarr, array_element_type);
6193 else {
6194 ig.Emit (OpCodes.Newobj, GetArrayMethod (arguments.Count));
6197 if (initializers == null)
6198 return;
6200 // Emit static initializer for arrays which have contain more than 4 items and
6201 // the static initializer will initialize at least 25% of array values.
6202 // NOTE: const_initializers_count does not contain default constant values.
6203 if (const_initializers_count >= 4 && const_initializers_count * 4 > (array_data.Count) &&
6204 TypeManager.IsPrimitiveType (array_element_type)) {
6205 EmitStaticInitializers (ec);
6207 if (!only_constant_initializers)
6208 EmitDynamicInitializers (ec, false);
6209 } else {
6210 EmitDynamicInitializers (ec, true);
6213 if (first_emit_temp != null)
6214 first_emit_temp.Release (ec);
6217 public override bool GetAttributableValue (EmitContext ec, Type value_type, out object value)
6219 if (arguments.Count != 1) {
6220 // Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6221 return base.GetAttributableValue (ec, null, out value);
6224 if (array_data == null) {
6225 Constant c = (Constant) arguments [0];
6226 if (c.IsDefaultValue) {
6227 value = Array.CreateInstance (array_element_type, 0);
6228 return true;
6230 // Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6231 return base.GetAttributableValue (ec, null, out value);
6234 Array ret = Array.CreateInstance (array_element_type, array_data.Count);
6235 object element_value;
6236 for (int i = 0; i < ret.Length; ++i)
6238 Expression e = (Expression)array_data [i];
6240 // Is null when an initializer is optimized (value == predefined value)
6241 if (e == null)
6242 continue;
6244 if (!e.GetAttributableValue (ec, array_element_type, out element_value)) {
6245 value = null;
6246 return false;
6248 ret.SetValue (element_value, i);
6250 value = ret;
6251 return true;
6254 protected override void CloneTo (CloneContext clonectx, Expression t)
6256 ArrayCreation target = (ArrayCreation) t;
6258 if (requested_base_type != null)
6259 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6261 if (arguments != null){
6262 target.arguments = new ArrayList (arguments.Count);
6263 foreach (Expression e in arguments)
6264 target.arguments.Add (e.Clone (clonectx));
6267 if (initializers != null){
6268 target.initializers = new ArrayList (initializers.Count);
6269 foreach (object initializer in initializers)
6270 if (initializer is ArrayList) {
6271 ArrayList this_al = (ArrayList)initializer;
6272 ArrayList al = new ArrayList (this_al.Count);
6273 target.initializers.Add (al);
6274 foreach (Expression e in this_al)
6275 al.Add (e.Clone (clonectx));
6276 } else {
6277 target.initializers.Add (((Expression)initializer).Clone (clonectx));
6284 // Represents an implicitly typed array epxression
6286 public class ImplicitlyTypedArrayCreation : ArrayCreation
6288 public ImplicitlyTypedArrayCreation (string rank, ArrayList initializers, Location loc)
6289 : base (null, rank, initializers, loc)
6291 if (RootContext.Version <= LanguageVersion.ISO_2)
6292 Report.FeatureIsNotAvailable (loc, "implicitly typed arrays");
6294 if (rank.Length > 2) {
6295 while (rank [++dimensions] == ',');
6296 } else {
6297 dimensions = 1;
6301 public override Expression DoResolve (EmitContext ec)
6303 if (type != null)
6304 return this;
6306 if (!ResolveInitializers (ec))
6307 return null;
6309 if (array_element_type == null || array_element_type == TypeManager.null_type ||
6310 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6311 arguments.Count != dimensions) {
6312 Error_NoBestType ();
6313 return null;
6317 // At this point we found common base type for all initializer elements
6318 // but we have to be sure that all static initializer elements are of
6319 // same type
6321 UnifyInitializerElement (ec);
6323 type = TypeManager.GetConstructedType (array_element_type, rank);
6324 eclass = ExprClass.Value;
6325 return this;
6328 void Error_NoBestType ()
6330 Report.Error (826, loc,
6331 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6335 // Converts static initializer only
6337 void UnifyInitializerElement (EmitContext ec)
6339 for (int i = 0; i < array_data.Count; ++i) {
6340 Expression e = (Expression)array_data[i];
6341 if (e != null)
6342 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6346 protected override Expression ResolveArrayElement (EmitContext ec, Expression element)
6348 element = element.Resolve (ec);
6349 if (element == null)
6350 return null;
6352 if (array_element_type == null) {
6353 if (element.Type != TypeManager.null_type)
6354 array_element_type = element.Type;
6356 return element;
6359 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6360 return element;
6363 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6364 array_element_type = element.Type;
6365 return element;
6368 Error_NoBestType ();
6369 return null;
6373 public sealed class CompilerGeneratedThis : This
6375 public static This Instance = new CompilerGeneratedThis ();
6377 private CompilerGeneratedThis ()
6378 : base (Location.Null)
6382 public CompilerGeneratedThis (Type type, Location loc)
6383 : base (loc)
6385 this.type = type;
6388 public override Expression DoResolve (EmitContext ec)
6390 eclass = ExprClass.Variable;
6391 if (type == null)
6392 type = ec.ContainerType;
6393 return this;
6396 public override HoistedVariable GetHoistedVariable (EmitContext ec)
6398 return null;
6402 /// <summary>
6403 /// Represents the `this' construct
6404 /// </summary>
6406 public class This : VariableReference
6408 sealed class ThisVariable : ILocalVariable
6410 public static readonly ILocalVariable Instance = new ThisVariable ();
6412 public void Emit (EmitContext ec)
6414 ec.ig.Emit (OpCodes.Ldarg_0);
6417 public void EmitAssign (EmitContext ec)
6419 throw new InvalidOperationException ();
6422 public void EmitAddressOf (EmitContext ec)
6424 ec.ig.Emit (OpCodes.Ldarg_0);
6428 Block block;
6429 VariableInfo variable_info;
6430 bool is_struct;
6432 public This (Block block, Location loc)
6434 this.loc = loc;
6435 this.block = block;
6438 public This (Location loc)
6440 this.loc = loc;
6443 public override VariableInfo VariableInfo {
6444 get { return variable_info; }
6447 public override bool IsFixed {
6448 get { return false; }
6451 public override HoistedVariable GetHoistedVariable (EmitContext ec)
6453 // Is null when probing IsHoisted
6454 if (ec == null)
6455 return null;
6457 if (ec.CurrentAnonymousMethod == null)
6458 return null;
6460 AnonymousMethodStorey storey = ec.CurrentAnonymousMethod.Storey;
6461 while (storey != null) {
6462 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6463 if (temp == null)
6464 return storey.HoistedThis;
6466 storey = temp;
6469 return null;
6472 public override bool IsRef {
6473 get { return is_struct; }
6476 protected override ILocalVariable Variable {
6477 get { return ThisVariable.Instance; }
6480 public static bool IsThisAvailable (EmitContext ec)
6482 if (ec.IsStatic || ec.IsInFieldInitializer)
6483 return false;
6485 if (ec.CurrentAnonymousMethod == null)
6486 return true;
6488 if (ec.TypeContainer is Struct && ec.CurrentIterator == null)
6489 return false;
6491 return true;
6494 public bool ResolveBase (EmitContext ec)
6496 if (eclass != ExprClass.Invalid)
6497 return true;
6499 eclass = ExprClass.Variable;
6501 if (ec.TypeContainer.CurrentType != null)
6502 type = ec.TypeContainer.CurrentType;
6503 else
6504 type = ec.ContainerType;
6506 if (!IsThisAvailable (ec)) {
6507 if (ec.IsStatic) {
6508 Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6509 } else {
6510 Report.Error (1673, loc,
6511 "Anonymous methods inside structs cannot access instance members of `this'. " +
6512 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6516 is_struct = ec.TypeContainer is Struct;
6518 if (block != null) {
6519 if (block.Toplevel.ThisVariable != null)
6520 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6522 AnonymousExpression am = ec.CurrentAnonymousMethod;
6523 if (am != null && ec.IsVariableCapturingRequired) {
6524 am.SetHasThisAccess ();
6528 return true;
6532 // Called from Invocation to check if the invocation is correct
6534 public override void CheckMarshalByRefAccess (EmitContext ec)
6536 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6537 !variable_info.IsAssigned (ec)) {
6538 Error (188, "The `this' object cannot be used before all of its " +
6539 "fields are assigned to");
6540 variable_info.SetAssigned (ec);
6544 public override Expression CreateExpressionTree (EmitContext ec)
6546 Arguments args = new Arguments (1);
6547 args.Add (new Argument (this));
6549 // Use typeless constant for ldarg.0 to save some
6550 // space and avoid problems with anonymous stories
6551 return CreateExpressionFactoryCall ("Constant", args);
6554 public override Expression DoResolve (EmitContext ec)
6556 if (!ResolveBase (ec))
6557 return null;
6560 if (ec.IsInFieldInitializer) {
6561 Error (27, "Keyword `this' is not available in the current context");
6562 return null;
6565 return this;
6568 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6570 if (!ResolveBase (ec))
6571 return null;
6573 if (variable_info != null)
6574 variable_info.SetAssigned (ec);
6576 if (ec.TypeContainer is Class){
6577 if (right_side == EmptyExpression.UnaryAddress)
6578 Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6579 else if (right_side == EmptyExpression.OutAccess)
6580 Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6581 else
6582 Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6585 return this;
6588 public override int GetHashCode()
6590 return block.GetHashCode ();
6593 public override string Name {
6594 get { return "this"; }
6597 public override bool Equals (object obj)
6599 This t = obj as This;
6600 if (t == null)
6601 return false;
6603 return block == t.block;
6606 protected override void CloneTo (CloneContext clonectx, Expression t)
6608 This target = (This) t;
6610 target.block = clonectx.LookupBlock (block);
6613 public override void SetHasAddressTaken ()
6615 // Nothing
6619 /// <summary>
6620 /// Represents the `__arglist' construct
6621 /// </summary>
6622 public class ArglistAccess : Expression
6624 public ArglistAccess (Location loc)
6626 this.loc = loc;
6629 public override Expression CreateExpressionTree (EmitContext ec)
6631 throw new NotSupportedException ("ET");
6634 public override Expression DoResolve (EmitContext ec)
6636 eclass = ExprClass.Variable;
6637 type = TypeManager.runtime_argument_handle_type;
6639 if (ec.IsInFieldInitializer || !ec.CurrentBlock.Toplevel.Parameters.HasArglist)
6641 Error (190, "The __arglist construct is valid only within " +
6642 "a variable argument method");
6643 return this;
6646 return this;
6649 public override void Emit (EmitContext ec)
6651 ec.ig.Emit (OpCodes.Arglist);
6654 protected override void CloneTo (CloneContext clonectx, Expression target)
6656 // nothing.
6660 /// <summary>
6661 /// Represents the `__arglist (....)' construct
6662 /// </summary>
6663 class Arglist : Expression
6665 Arguments Arguments;
6667 public Arglist (Location loc)
6668 : this (null, loc)
6672 public Arglist (Arguments args, Location l)
6674 Arguments = args;
6675 loc = l;
6678 public Type[] ArgumentTypes {
6679 get {
6680 if (Arguments == null)
6681 return Type.EmptyTypes;
6683 Type[] retval = new Type [Arguments.Count];
6684 for (int i = 0; i < retval.Length; i++)
6685 retval [i] = Arguments [i].Expr.Type;
6687 return retval;
6691 public override Expression CreateExpressionTree (EmitContext ec)
6693 Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6694 return null;
6697 public override Expression DoResolve (EmitContext ec)
6699 eclass = ExprClass.Variable;
6700 type = InternalType.Arglist;
6701 if (Arguments != null)
6702 Arguments.Resolve (ec);
6704 return this;
6707 public override void Emit (EmitContext ec)
6709 if (Arguments != null)
6710 Arguments.Emit (ec);
6713 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
6715 if (Arguments != null)
6716 Arguments.MutateHoistedGenericType (storey);
6719 protected override void CloneTo (CloneContext clonectx, Expression t)
6721 Arglist target = (Arglist) t;
6723 if (Arguments != null)
6724 target.Arguments = Arguments.Clone (clonectx);
6728 /// <summary>
6729 /// Implements the typeof operator
6730 /// </summary>
6731 public class TypeOf : Expression {
6732 Expression QueriedType;
6733 protected Type typearg;
6735 public TypeOf (Expression queried_type, Location l)
6737 QueriedType = queried_type;
6738 loc = l;
6741 public override Expression CreateExpressionTree (EmitContext ec)
6743 Arguments args = new Arguments (2);
6744 args.Add (new Argument (this));
6745 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6746 return CreateExpressionFactoryCall ("Constant", args);
6749 public override Expression DoResolve (EmitContext ec)
6751 if (eclass != ExprClass.Invalid)
6752 return this;
6754 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6755 if (texpr == null)
6756 return null;
6758 typearg = texpr.Type;
6760 if (typearg == TypeManager.void_type) {
6761 Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6762 return null;
6765 if (typearg.IsPointer && !ec.InUnsafe){
6766 UnsafeError (loc);
6767 return null;
6770 type = TypeManager.type_type;
6772 return DoResolveBase ();
6775 protected Expression DoResolveBase ()
6777 if (TypeManager.system_type_get_type_from_handle == null) {
6778 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6779 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6782 // Even though what is returned is a type object, it's treated as a value by the compiler.
6783 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6784 eclass = ExprClass.Value;
6785 return this;
6788 public override void Emit (EmitContext ec)
6790 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6791 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6794 public override bool GetAttributableValue (EmitContext ec, Type value_type, out object value)
6796 if (TypeManager.ContainsGenericParameters (typearg) &&
6797 !TypeManager.IsGenericTypeDefinition (typearg)) {
6798 Report.SymbolRelatedToPreviousError (typearg);
6799 Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6800 TypeManager.CSharpName (typearg));
6801 value = null;
6802 return false;
6805 if (value_type == TypeManager.object_type) {
6806 value = (object)typearg;
6807 return true;
6809 value = typearg;
6810 return true;
6813 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
6815 typearg = storey.MutateType (typearg);
6818 public Type TypeArgument {
6819 get {
6820 return typearg;
6824 protected override void CloneTo (CloneContext clonectx, Expression t)
6826 TypeOf target = (TypeOf) t;
6827 if (QueriedType != null)
6828 target.QueriedType = QueriedType.Clone (clonectx);
6832 /// <summary>
6833 /// Implements the `typeof (void)' operator
6834 /// </summary>
6835 public class TypeOfVoid : TypeOf {
6836 public TypeOfVoid (Location l) : base (null, l)
6838 loc = l;
6841 public override Expression DoResolve (EmitContext ec)
6843 type = TypeManager.type_type;
6844 typearg = TypeManager.void_type;
6846 return DoResolveBase ();
6850 class TypeOfMethodInfo : TypeOfMethod
6852 public TypeOfMethodInfo (MethodBase method, Location loc)
6853 : base (method, loc)
6857 public override Expression DoResolve (EmitContext ec)
6859 type = typeof (MethodInfo);
6860 return base.DoResolve (ec);
6863 public override void Emit (EmitContext ec)
6865 ec.ig.Emit (OpCodes.Ldtoken, (MethodInfo) method);
6866 base.Emit (ec);
6867 ec.ig.Emit (OpCodes.Castclass, type);
6871 class TypeOfConstructorInfo : TypeOfMethod
6873 public TypeOfConstructorInfo (MethodBase method, Location loc)
6874 : base (method, loc)
6878 public override Expression DoResolve (EmitContext ec)
6880 type = typeof (ConstructorInfo);
6881 return base.DoResolve (ec);
6884 public override void Emit (EmitContext ec)
6886 ec.ig.Emit (OpCodes.Ldtoken, (ConstructorInfo) method);
6887 base.Emit (ec);
6888 ec.ig.Emit (OpCodes.Castclass, type);
6892 abstract class TypeOfMethod : Expression
6894 protected readonly MethodBase method;
6896 protected TypeOfMethod (MethodBase method, Location loc)
6898 this.method = method;
6899 this.loc = loc;
6902 public override Expression CreateExpressionTree (EmitContext ec)
6904 Arguments args = new Arguments (2);
6905 args.Add (new Argument (this));
6906 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6907 return CreateExpressionFactoryCall ("Constant", args);
6910 public override Expression DoResolve (EmitContext ec)
6912 bool is_generic = TypeManager.IsGenericType (method.DeclaringType);
6913 MethodInfo mi = is_generic ?
6914 TypeManager.methodbase_get_type_from_handle_generic :
6915 TypeManager.methodbase_get_type_from_handle;
6917 if (mi == null) {
6918 Type t = TypeManager.CoreLookupType ("System.Reflection", "MethodBase", Kind.Class, true);
6919 Type handle_type = TypeManager.CoreLookupType ("System", "RuntimeMethodHandle", Kind.Class, true);
6921 if (t == null || handle_type == null)
6922 return null;
6924 mi = TypeManager.GetPredefinedMethod (t, "GetMethodFromHandle", loc,
6925 is_generic ?
6926 new Type[] { handle_type, TypeManager.runtime_handle_type } :
6927 new Type[] { handle_type } );
6929 if (is_generic)
6930 TypeManager.methodbase_get_type_from_handle_generic = mi;
6931 else
6932 TypeManager.methodbase_get_type_from_handle = mi;
6935 eclass = ExprClass.Value;
6936 return this;
6939 public override void Emit (EmitContext ec)
6941 bool is_generic = TypeManager.IsGenericType (method.DeclaringType);
6942 MethodInfo mi;
6943 if (is_generic) {
6944 mi = TypeManager.methodbase_get_type_from_handle_generic;
6945 ec.ig.Emit (OpCodes.Ldtoken, method.DeclaringType);
6946 } else {
6947 mi = TypeManager.methodbase_get_type_from_handle;
6950 ec.ig.Emit (OpCodes.Call, mi);
6954 internal class TypeOfField : Expression
6956 readonly FieldInfo field;
6958 public TypeOfField (FieldInfo field, Location loc)
6960 this.field = field;
6961 this.loc = loc;
6964 public override Expression CreateExpressionTree (EmitContext ec)
6966 throw new NotSupportedException ("ET");
6969 public override Expression DoResolve (EmitContext ec)
6971 if (TypeManager.fieldinfo_get_field_from_handle == null) {
6972 Type t = TypeManager.CoreLookupType ("System.Reflection", "FieldInfo", Kind.Class, true);
6973 Type handle_type = TypeManager.CoreLookupType ("System", "RuntimeFieldHandle", Kind.Class, true);
6975 if (t != null && handle_type != null)
6976 TypeManager.fieldinfo_get_field_from_handle = TypeManager.GetPredefinedMethod (t,
6977 "GetFieldFromHandle", loc, handle_type);
6980 type = typeof (FieldInfo);
6981 eclass = ExprClass.Value;
6982 return this;
6985 public override void Emit (EmitContext ec)
6987 ec.ig.Emit (OpCodes.Ldtoken, field);
6988 ec.ig.Emit (OpCodes.Call, TypeManager.fieldinfo_get_field_from_handle);
6992 /// <summary>
6993 /// Implements the sizeof expression
6994 /// </summary>
6995 public class SizeOf : Expression {
6996 readonly Expression QueriedType;
6997 Type type_queried;
6999 public SizeOf (Expression queried_type, Location l)
7001 this.QueriedType = queried_type;
7002 loc = l;
7005 public override Expression CreateExpressionTree (EmitContext ec)
7007 Error_PointerInsideExpressionTree ();
7008 return null;
7011 public override Expression DoResolve (EmitContext ec)
7013 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7014 if (texpr == null)
7015 return null;
7017 type_queried = texpr.Type;
7018 if (TypeManager.IsEnumType (type_queried))
7019 type_queried = TypeManager.GetEnumUnderlyingType (type_queried);
7021 int size_of = GetTypeSize (type_queried);
7022 if (size_of > 0) {
7023 return new IntConstant (size_of, loc);
7026 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
7027 return null;
7030 if (!ec.InUnsafe) {
7031 Report.Error (233, loc,
7032 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7033 TypeManager.CSharpName (type_queried));
7036 type = TypeManager.int32_type;
7037 eclass = ExprClass.Value;
7038 return this;
7041 public override void Emit (EmitContext ec)
7043 int size = GetTypeSize (type_queried);
7045 if (size == 0)
7046 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7047 else
7048 IntConstant.EmitInt (ec.ig, size);
7051 protected override void CloneTo (CloneContext clonectx, Expression t)
7056 /// <summary>
7057 /// Implements the qualified-alias-member (::) expression.
7058 /// </summary>
7059 public class QualifiedAliasMember : MemberAccess
7061 readonly string alias;
7062 public static readonly string GlobalAlias = "global";
7064 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7065 : base (null, identifier, targs, l)
7067 this.alias = alias;
7070 public QualifiedAliasMember (string alias, string identifier, Location l)
7071 : base (null, identifier, l)
7073 this.alias = alias;
7076 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
7078 if (alias == GlobalAlias) {
7079 expr = GlobalRootNamespace.Instance;
7080 return base.ResolveAsTypeStep (ec, silent);
7083 int errors = Report.Errors;
7084 expr = ec.DeclContainer.NamespaceEntry.LookupAlias (alias);
7085 if (expr == null) {
7086 if (errors == Report.Errors)
7087 Report.Error (432, loc, "Alias `{0}' not found", alias);
7088 return null;
7091 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7092 if (fne == null)
7093 return null;
7095 if (expr.eclass == ExprClass.Type) {
7096 if (!silent) {
7097 Report.Error (431, loc,
7098 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7100 return null;
7103 return fne;
7106 public override Expression DoResolve (EmitContext ec)
7108 return ResolveAsTypeStep (ec, false);
7111 protected override void Error_IdentifierNotFound (IResolveContext rc, FullNamedExpression expr_type, string identifier)
7113 Report.Error (687, loc,
7114 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7115 GetSignatureForError ());
7118 public override string GetSignatureForError ()
7120 string name = Name;
7121 if (targs != null) {
7122 name = TypeManager.RemoveGenericArity (Name) + "<" +
7123 targs.GetSignatureForError () + ">";
7126 return alias + "::" + name;
7129 protected override void CloneTo (CloneContext clonectx, Expression t)
7131 // Nothing
7135 /// <summary>
7136 /// Implements the member access expression
7137 /// </summary>
7138 public class MemberAccess : ATypeNameExpression {
7139 protected Expression expr;
7141 public MemberAccess (Expression expr, string id)
7142 : base (id, expr.Location)
7144 this.expr = expr;
7147 public MemberAccess (Expression expr, string identifier, Location loc)
7148 : base (identifier, loc)
7150 this.expr = expr;
7153 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7154 : base (identifier, args, loc)
7156 this.expr = expr;
7159 Expression DoResolve (EmitContext ec, Expression right_side)
7161 if (type != null)
7162 throw new Exception ();
7165 // Resolve the expression with flow analysis turned off, we'll do the definite
7166 // assignment checks later. This is because we don't know yet what the expression
7167 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7168 // definite assignment check on the actual field and not on the whole struct.
7171 SimpleName original = expr as SimpleName;
7172 Expression expr_resolved = expr.Resolve (ec,
7173 ResolveFlags.VariableOrValue | ResolveFlags.Type |
7174 ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);
7176 if (expr_resolved == null)
7177 return null;
7179 string LookupIdentifier = MemberName.MakeName (Name, targs);
7181 Namespace ns = expr_resolved as Namespace;
7182 if (ns != null) {
7183 FullNamedExpression retval = ns.Lookup (ec.DeclContainer, LookupIdentifier, loc);
7185 if (retval == null)
7186 ns.Error_NamespaceDoesNotExist (ec.DeclContainer, loc, LookupIdentifier);
7187 else if (targs != null)
7188 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
7190 return retval;
7193 Type expr_type = expr_resolved.Type;
7194 if (expr_type == InternalType.Dynamic) {
7195 Arguments args = new Arguments (2);
7196 args.Add (new Argument (expr_resolved.Resolve (ec)));
7197 if (right_side != null)
7198 args.Add (new Argument (right_side));
7200 return new DynamicMemberBinder (right_side != null, Name, args, loc).Resolve (ec);
7203 if (expr_type.IsPointer || expr_type == TypeManager.void_type ||
7204 expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod) {
7205 Unary.Error_OperatorCannotBeApplied (loc, ".", expr_type);
7206 return null;
7209 Constant c = expr_resolved as Constant;
7210 if (c != null && c.GetValue () == null) {
7211 Report.Warning (1720, 1, loc, "Expression will always cause a `{0}'",
7212 "System.NullReferenceException");
7215 if (targs != null) {
7216 if (!targs.Resolve (ec))
7217 return null;
7220 Expression member_lookup;
7221 member_lookup = MemberLookup (
7222 ec.ContainerType, expr_type, expr_type, Name, loc);
7224 if (member_lookup == null && targs != null) {
7225 member_lookup = MemberLookup (
7226 ec.ContainerType, expr_type, expr_type, LookupIdentifier, loc);
7229 if (member_lookup == null) {
7230 ExprClass expr_eclass = expr_resolved.eclass;
7233 // Extension methods are not allowed on all expression types
7235 if (expr_eclass == ExprClass.Value || expr_eclass == ExprClass.Variable ||
7236 expr_eclass == ExprClass.IndexerAccess || expr_eclass == ExprClass.PropertyAccess ||
7237 expr_eclass == ExprClass.EventAccess) {
7238 ExtensionMethodGroupExpr ex_method_lookup = ec.TypeContainer.LookupExtensionMethod (expr_type, Name, loc);
7239 if (ex_method_lookup != null) {
7240 ex_method_lookup.ExtensionExpression = expr_resolved;
7242 if (targs != null) {
7243 ex_method_lookup.SetTypeArguments (targs);
7246 return ex_method_lookup.DoResolve (ec);
7250 expr = expr_resolved;
7251 member_lookup = Error_MemberLookupFailed (
7252 ec.ContainerType, expr_type, expr_type, Name, null,
7253 AllMemberTypes, AllBindingFlags);
7254 if (member_lookup == null)
7255 return null;
7258 TypeExpr texpr = member_lookup as TypeExpr;
7259 if (texpr != null) {
7260 if (!(expr_resolved is TypeExpr) &&
7261 (original == null || !original.IdenticalNameAndTypeName (ec, expr_resolved, loc))) {
7262 Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7263 Name, member_lookup.GetSignatureForError ());
7264 return null;
7267 if (!texpr.CheckAccessLevel (ec.DeclContainer)) {
7268 Report.SymbolRelatedToPreviousError (member_lookup.Type);
7269 ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type));
7270 return null;
7273 GenericTypeExpr ct = expr_resolved as GenericTypeExpr;
7274 if (ct != null) {
7276 // When looking up a nested type in a generic instance
7277 // via reflection, we always get a generic type definition
7278 // and not a generic instance - so we have to do this here.
7280 // See gtest-172-lib.cs and gtest-172.cs for an example.
7282 ct = new GenericTypeExpr (
7283 member_lookup.Type, ct.TypeArguments, loc);
7285 return ct.ResolveAsTypeStep (ec, false);
7288 return member_lookup;
7291 MemberExpr me = (MemberExpr) member_lookup;
7292 me = me.ResolveMemberAccess (ec, expr_resolved, loc, original);
7293 if (me == null)
7294 return null;
7296 if (targs != null) {
7297 me.SetTypeArguments (targs);
7300 if (original != null && !TypeManager.IsValueType (expr_type)) {
7301 if (me.IsInstance) {
7302 LocalVariableReference var = expr_resolved as LocalVariableReference;
7303 if (var != null && !var.VerifyAssigned (ec))
7304 return null;
7308 // The following DoResolve/DoResolveLValue will do the definite assignment
7309 // check.
7311 if (right_side != null)
7312 return me.DoResolveLValue (ec, right_side);
7313 else
7314 return me.DoResolve (ec);
7317 public override Expression DoResolve (EmitContext ec)
7319 return DoResolve (ec, null);
7322 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7324 return DoResolve (ec, right_side);
7327 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
7329 return ResolveNamespaceOrType (ec, silent);
7332 public FullNamedExpression ResolveNamespaceOrType (IResolveContext rc, bool silent)
7334 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7336 if (expr_resolved == null)
7337 return null;
7339 string LookupIdentifier = MemberName.MakeName (Name, targs);
7341 Namespace ns = expr_resolved as Namespace;
7342 if (ns != null) {
7343 FullNamedExpression retval = ns.Lookup (rc.DeclContainer, LookupIdentifier, loc);
7345 if (retval == null && !silent)
7346 ns.Error_NamespaceDoesNotExist (rc.DeclContainer, loc, LookupIdentifier);
7347 else if (targs != null)
7348 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7350 return retval;
7353 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7354 if (tnew_expr == null)
7355 return null;
7357 if (tnew_expr is TypeParameterExpr) {
7358 Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7359 tnew_expr.GetSignatureForError ());
7360 return null;
7363 Type expr_type = tnew_expr.Type;
7364 Expression member_lookup = MemberLookup (
7365 rc.DeclContainer.TypeBuilder, expr_type, expr_type, LookupIdentifier,
7366 MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
7367 if (member_lookup == null) {
7368 if (silent)
7369 return null;
7371 Error_IdentifierNotFound (rc, expr_resolved, LookupIdentifier);
7372 return null;
7375 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (rc, false);
7376 if (texpr == null)
7377 return null;
7379 TypeArguments the_args = targs;
7380 Type declaring_type = texpr.Type.DeclaringType;
7381 if (TypeManager.HasGenericArguments (declaring_type) && !TypeManager.IsGenericTypeDefinition (expr_type)) {
7382 while (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (expr_type), declaring_type)) {
7383 expr_type = expr_type.BaseType;
7386 TypeArguments new_args = new TypeArguments ();
7387 foreach (Type decl in TypeManager.GetTypeArguments (expr_type))
7388 new_args.Add (new TypeExpression (decl, loc));
7390 if (targs != null)
7391 new_args.Add (targs);
7393 the_args = new_args;
7396 if (the_args != null) {
7397 GenericTypeExpr ctype = new GenericTypeExpr (texpr.Type, the_args, loc);
7398 return ctype.ResolveAsTypeStep (rc, false);
7401 return texpr;
7404 protected virtual void Error_IdentifierNotFound (IResolveContext rc, FullNamedExpression expr_type, string identifier)
7406 Expression member_lookup = MemberLookup (
7407 rc.DeclContainer.TypeBuilder, expr_type.Type, expr_type.Type, SimpleName.RemoveGenericArity (identifier),
7408 MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
7410 if (member_lookup != null) {
7411 expr_type = member_lookup.ResolveAsTypeTerminal (rc, false);
7412 if (expr_type == null)
7413 return;
7415 Namespace.Error_TypeArgumentsCannotBeUsed (expr_type, loc);
7416 return;
7419 member_lookup = MemberLookup (
7420 rc.DeclContainer.TypeBuilder, expr_type.Type, expr_type.Type, identifier,
7421 MemberTypes.All, BindingFlags.Public | BindingFlags.NonPublic, loc);
7423 if (member_lookup == null) {
7424 Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7425 Name, expr_type.GetSignatureForError ());
7426 } else {
7427 // TODO: Report.SymbolRelatedToPreviousError
7428 member_lookup.Error_UnexpectedKind (null, "type", loc);
7432 protected override void Error_TypeDoesNotContainDefinition (Type type, string name)
7434 if (RootContext.Version > LanguageVersion.ISO_2 &&
7435 ((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
7436 Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
7437 "extension method `{1}' of type `{0}' could be found " +
7438 "(are you missing a using directive or an assembly reference?)",
7439 TypeManager.CSharpName (type), name);
7440 return;
7443 base.Error_TypeDoesNotContainDefinition (type, name);
7446 public override string GetSignatureForError ()
7448 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7451 protected override void CloneTo (CloneContext clonectx, Expression t)
7453 MemberAccess target = (MemberAccess) t;
7455 target.expr = expr.Clone (clonectx);
7459 /// <summary>
7460 /// Implements checked expressions
7461 /// </summary>
7462 public class CheckedExpr : Expression {
7464 public Expression Expr;
7466 public CheckedExpr (Expression e, Location l)
7468 Expr = e;
7469 loc = l;
7472 public override Expression CreateExpressionTree (EmitContext ec)
7474 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
7475 return Expr.CreateExpressionTree (ec);
7478 public override Expression DoResolve (EmitContext ec)
7480 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
7481 Expr = Expr.Resolve (ec);
7483 if (Expr == null)
7484 return null;
7486 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7487 return Expr;
7489 eclass = Expr.eclass;
7490 type = Expr.Type;
7491 return this;
7494 public override void Emit (EmitContext ec)
7496 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
7497 Expr.Emit (ec);
7500 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7502 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
7503 Expr.EmitBranchable (ec, target, on_true);
7506 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
7508 Expr.MutateHoistedGenericType (storey);
7511 protected override void CloneTo (CloneContext clonectx, Expression t)
7513 CheckedExpr target = (CheckedExpr) t;
7515 target.Expr = Expr.Clone (clonectx);
7519 /// <summary>
7520 /// Implements the unchecked expression
7521 /// </summary>
7522 public class UnCheckedExpr : Expression {
7524 public Expression Expr;
7526 public UnCheckedExpr (Expression e, Location l)
7528 Expr = e;
7529 loc = l;
7532 public override Expression CreateExpressionTree (EmitContext ec)
7534 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
7535 return Expr.CreateExpressionTree (ec);
7538 public override Expression DoResolve (EmitContext ec)
7540 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
7541 Expr = Expr.Resolve (ec);
7543 if (Expr == null)
7544 return null;
7546 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7547 return Expr;
7549 eclass = Expr.eclass;
7550 type = Expr.Type;
7551 return this;
7554 public override void Emit (EmitContext ec)
7556 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
7557 Expr.Emit (ec);
7560 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7562 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
7563 Expr.EmitBranchable (ec, target, on_true);
7566 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
7568 Expr.MutateHoistedGenericType (storey);
7571 protected override void CloneTo (CloneContext clonectx, Expression t)
7573 UnCheckedExpr target = (UnCheckedExpr) t;
7575 target.Expr = Expr.Clone (clonectx);
7579 /// <summary>
7580 /// An Element Access expression.
7582 /// During semantic analysis these are transformed into
7583 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7584 /// </summary>
7585 public class ElementAccess : Expression {
7586 public Arguments Arguments;
7587 public Expression Expr;
7589 public ElementAccess (Expression e, Arguments args)
7591 Expr = e;
7592 loc = e.Location;
7593 this.Arguments = args;
7596 bool CommonResolve (EmitContext ec)
7598 Expr = Expr.Resolve (ec);
7600 if (Arguments != null)
7601 Arguments.Resolve (ec);
7603 return Expr != null;
7606 public override Expression CreateExpressionTree (EmitContext ec)
7608 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7609 Expr.CreateExpressionTree (ec));
7611 return CreateExpressionFactoryCall ("ArrayIndex", args);
7614 Expression MakePointerAccess (EmitContext ec, Type t)
7616 if (Arguments.Count != 1){
7617 Error (196, "A pointer must be indexed by only one value");
7618 return null;
7621 if (Arguments [0] is NamedArgument)
7622 Error_NamedArgument ((NamedArgument) Arguments[0]);
7624 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr, t, loc).Resolve (ec);
7625 if (p == null)
7626 return null;
7627 return new Indirection (p, loc).Resolve (ec);
7630 public override Expression DoResolve (EmitContext ec)
7632 if (!CommonResolve (ec))
7633 return null;
7636 // We perform some simple tests, and then to "split" the emit and store
7637 // code we create an instance of a different class, and return that.
7639 // I am experimenting with this pattern.
7641 Type t = Expr.Type;
7643 if (t == TypeManager.array_type){
7644 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7645 return null;
7648 if (t.IsArray)
7649 return (new ArrayAccess (this, loc)).Resolve (ec);
7650 if (t.IsPointer)
7651 return MakePointerAccess (ec, t);
7653 if (t == InternalType.Dynamic) {
7654 Arguments args = new Arguments (Arguments.Count + 1);
7655 args.Add (new Argument (Expr));
7656 args.AddRange (Arguments);
7657 return new DynamicIndexBinder (false, args, loc).Resolve (ec);
7660 FieldExpr fe = Expr as FieldExpr;
7661 if (fe != null) {
7662 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7663 if (ff != null) {
7664 return MakePointerAccess (ec, ff.ElementType);
7667 return (new IndexerAccess (this, loc)).Resolve (ec);
7670 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7672 if (!CommonResolve (ec))
7673 return null;
7675 type = Expr.Type;
7676 if (type.IsArray)
7677 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7679 if (type.IsPointer)
7680 return MakePointerAccess (ec, type);
7682 if (type == InternalType.Dynamic) {
7683 Arguments args = new Arguments (Arguments.Count + 2);
7684 args.Add (new Argument (Expr));
7685 args.AddRange (Arguments);
7686 args.Add (new Argument (right_side));
7687 return new DynamicIndexBinder (true, args, loc).Resolve (ec);
7690 if (Expr.eclass != ExprClass.Variable && TypeManager.IsStruct (type))
7691 Error_CannotModifyIntermediateExpressionValue (ec);
7693 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7696 public override void Emit (EmitContext ec)
7698 throw new Exception ("Should never be reached");
7701 public static void Error_NamedArgument (NamedArgument na)
7703 Report.Error (1742, na.Name.Location, "An element access expression cannot use named argument");
7706 public override string GetSignatureForError ()
7708 return Expr.GetSignatureForError ();
7711 protected override void CloneTo (CloneContext clonectx, Expression t)
7713 ElementAccess target = (ElementAccess) t;
7715 target.Expr = Expr.Clone (clonectx);
7716 if (Arguments != null)
7717 target.Arguments = Arguments.Clone (clonectx);
7721 /// <summary>
7722 /// Implements array access
7723 /// </summary>
7724 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7726 // Points to our "data" repository
7728 ElementAccess ea;
7730 LocalTemporary temp;
7732 bool prepared;
7734 public ArrayAccess (ElementAccess ea_data, Location l)
7736 ea = ea_data;
7737 loc = l;
7740 public override Expression CreateExpressionTree (EmitContext ec)
7742 return ea.CreateExpressionTree (ec);
7745 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7747 return DoResolve (ec);
7750 public override Expression DoResolve (EmitContext ec)
7752 #if false
7753 ExprClass eclass = ea.Expr.eclass;
7755 // As long as the type is valid
7756 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7757 eclass == ExprClass.Value)) {
7758 ea.Expr.Error_UnexpectedKind ("variable or value");
7759 return null;
7761 #endif
7763 if (eclass != ExprClass.Invalid)
7764 return this;
7766 Type t = ea.Expr.Type;
7767 int rank = ea.Arguments.Count;
7768 if (t.GetArrayRank () != rank) {
7769 Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7770 ea.Arguments.Count.ToString (), t.GetArrayRank ().ToString ());
7771 return null;
7774 type = TypeManager.GetElementType (t);
7775 if (type.IsPointer && !ec.InUnsafe) {
7776 UnsafeError (ea.Location);
7777 return null;
7780 foreach (Argument a in ea.Arguments) {
7781 if (a is NamedArgument)
7782 ElementAccess.Error_NamedArgument ((NamedArgument) a);
7784 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7787 eclass = ExprClass.Variable;
7789 return this;
7792 /// <summary>
7793 /// Emits the right opcode to load an object of Type `t'
7794 /// from an array of T
7795 /// </summary>
7796 void EmitLoadOpcode (ILGenerator ig, Type type, int rank)
7798 if (rank > 1) {
7799 MethodInfo get = FetchGetMethod ();
7800 ig.Emit (OpCodes.Call, get);
7801 return;
7804 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7805 ig.Emit (OpCodes.Ldelem_U1);
7806 else if (type == TypeManager.sbyte_type)
7807 ig.Emit (OpCodes.Ldelem_I1);
7808 else if (type == TypeManager.short_type)
7809 ig.Emit (OpCodes.Ldelem_I2);
7810 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7811 ig.Emit (OpCodes.Ldelem_U2);
7812 else if (type == TypeManager.int32_type)
7813 ig.Emit (OpCodes.Ldelem_I4);
7814 else if (type == TypeManager.uint32_type)
7815 ig.Emit (OpCodes.Ldelem_U4);
7816 else if (type == TypeManager.uint64_type)
7817 ig.Emit (OpCodes.Ldelem_I8);
7818 else if (type == TypeManager.int64_type)
7819 ig.Emit (OpCodes.Ldelem_I8);
7820 else if (type == TypeManager.float_type)
7821 ig.Emit (OpCodes.Ldelem_R4);
7822 else if (type == TypeManager.double_type)
7823 ig.Emit (OpCodes.Ldelem_R8);
7824 else if (type == TypeManager.intptr_type)
7825 ig.Emit (OpCodes.Ldelem_I);
7826 else if (TypeManager.IsEnumType (type)){
7827 EmitLoadOpcode (ig, TypeManager.GetEnumUnderlyingType (type), rank);
7828 } else if (TypeManager.IsStruct (type)){
7829 ig.Emit (OpCodes.Ldelema, type);
7830 ig.Emit (OpCodes.Ldobj, type);
7831 #if GMCS_SOURCE
7832 } else if (type.IsGenericParameter) {
7833 ig.Emit (OpCodes.Ldelem, type);
7834 #endif
7835 } else if (type.IsPointer)
7836 ig.Emit (OpCodes.Ldelem_I);
7837 else
7838 ig.Emit (OpCodes.Ldelem_Ref);
7841 protected override void Error_NegativeArrayIndex (Location loc)
7843 Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7846 /// <summary>
7847 /// Returns the right opcode to store an object of Type `t'
7848 /// from an array of T.
7849 /// </summary>
7850 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
7852 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7853 has_type_arg = false; is_stobj = false;
7854 t = TypeManager.TypeToCoreType (t);
7855 if (TypeManager.IsEnumType (t))
7856 t = TypeManager.GetEnumUnderlyingType (t);
7857 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7858 t == TypeManager.bool_type)
7859 return OpCodes.Stelem_I1;
7860 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7861 t == TypeManager.char_type)
7862 return OpCodes.Stelem_I2;
7863 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7864 return OpCodes.Stelem_I4;
7865 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7866 return OpCodes.Stelem_I8;
7867 else if (t == TypeManager.float_type)
7868 return OpCodes.Stelem_R4;
7869 else if (t == TypeManager.double_type)
7870 return OpCodes.Stelem_R8;
7871 else if (t == TypeManager.intptr_type) {
7872 has_type_arg = true;
7873 is_stobj = true;
7874 return OpCodes.Stobj;
7875 } else if (TypeManager.IsStruct (t)) {
7876 has_type_arg = true;
7877 is_stobj = true;
7878 return OpCodes.Stobj;
7879 #if GMCS_SOURCE
7880 } else if (t.IsGenericParameter) {
7881 has_type_arg = true;
7882 return OpCodes.Stelem;
7883 #endif
7885 } else if (t.IsPointer)
7886 return OpCodes.Stelem_I;
7887 else
7888 return OpCodes.Stelem_Ref;
7891 MethodInfo FetchGetMethod ()
7893 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
7894 int arg_count = ea.Arguments.Count;
7895 Type [] args = new Type [arg_count];
7896 MethodInfo get;
7898 for (int i = 0; i < arg_count; i++){
7899 //args [i++] = a.Type;
7900 args [i] = TypeManager.int32_type;
7903 get = mb.GetArrayMethod (
7904 ea.Expr.Type, "Get",
7905 CallingConventions.HasThis |
7906 CallingConventions.Standard,
7907 type, args);
7908 return get;
7912 MethodInfo FetchAddressMethod ()
7914 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
7915 int arg_count = ea.Arguments.Count;
7916 Type [] args = new Type [arg_count];
7917 MethodInfo address;
7918 Type ret_type;
7920 ret_type = TypeManager.GetReferenceType (type);
7922 for (int i = 0; i < arg_count; i++){
7923 //args [i++] = a.Type;
7924 args [i] = TypeManager.int32_type;
7927 address = mb.GetArrayMethod (
7928 ea.Expr.Type, "Address",
7929 CallingConventions.HasThis |
7930 CallingConventions.Standard,
7931 ret_type, args);
7933 return address;
7937 // Load the array arguments into the stack.
7939 void LoadArrayAndArguments (EmitContext ec)
7941 ea.Expr.Emit (ec);
7943 for (int i = 0; i < ea.Arguments.Count; ++i) {
7944 ea.Arguments [i].Emit (ec);
7948 public void Emit (EmitContext ec, bool leave_copy)
7950 int rank = ea.Expr.Type.GetArrayRank ();
7951 ILGenerator ig = ec.ig;
7953 if (prepared) {
7954 LoadFromPtr (ig, this.type);
7955 } else {
7956 LoadArrayAndArguments (ec);
7957 EmitLoadOpcode (ig, type, rank);
7960 if (leave_copy) {
7961 ig.Emit (OpCodes.Dup);
7962 temp = new LocalTemporary (this.type);
7963 temp.Store (ec);
7967 public override void Emit (EmitContext ec)
7969 Emit (ec, false);
7972 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7974 int rank = ea.Expr.Type.GetArrayRank ();
7975 ILGenerator ig = ec.ig;
7976 Type t = source.Type;
7977 prepared = prepare_for_load;
7979 if (prepared) {
7980 AddressOf (ec, AddressOp.LoadStore);
7981 ec.ig.Emit (OpCodes.Dup);
7982 } else {
7983 LoadArrayAndArguments (ec);
7986 if (rank == 1) {
7987 bool is_stobj, has_type_arg;
7988 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
7990 if (!prepared) {
7992 // The stobj opcode used by value types will need
7993 // an address on the stack, not really an array/array
7994 // pair
7996 if (is_stobj)
7997 ig.Emit (OpCodes.Ldelema, t);
8000 source.Emit (ec);
8001 if (leave_copy) {
8002 ec.ig.Emit (OpCodes.Dup);
8003 temp = new LocalTemporary (this.type);
8004 temp.Store (ec);
8007 if (prepared)
8008 StoreFromPtr (ig, t);
8009 else if (is_stobj)
8010 ig.Emit (OpCodes.Stobj, t);
8011 else if (has_type_arg)
8012 ig.Emit (op, t);
8013 else
8014 ig.Emit (op);
8015 } else {
8016 source.Emit (ec);
8017 if (leave_copy) {
8018 ec.ig.Emit (OpCodes.Dup);
8019 temp = new LocalTemporary (this.type);
8020 temp.Store (ec);
8023 if (prepared) {
8024 StoreFromPtr (ig, t);
8025 } else {
8026 int arg_count = ea.Arguments.Count;
8027 Type [] args = new Type [arg_count + 1];
8028 for (int i = 0; i < arg_count; i++) {
8029 //args [i++] = a.Type;
8030 args [i] = TypeManager.int32_type;
8032 args [arg_count] = type;
8034 MethodInfo set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
8035 ea.Expr.Type, "Set",
8036 CallingConventions.HasThis |
8037 CallingConventions.Standard,
8038 TypeManager.void_type, args);
8040 ig.Emit (OpCodes.Call, set);
8044 if (temp != null) {
8045 temp.Emit (ec);
8046 temp.Release (ec);
8050 public void EmitNew (EmitContext ec, New source, bool leave_copy)
8052 if (!source.Emit (ec, this)) {
8053 if (leave_copy)
8054 throw new NotImplementedException ();
8056 return;
8059 throw new NotImplementedException ();
8062 public void AddressOf (EmitContext ec, AddressOp mode)
8064 int rank = ea.Expr.Type.GetArrayRank ();
8065 ILGenerator ig = ec.ig;
8067 LoadArrayAndArguments (ec);
8069 if (rank == 1){
8070 ig.Emit (OpCodes.Ldelema, type);
8071 } else {
8072 MethodInfo address = FetchAddressMethod ();
8073 ig.Emit (OpCodes.Call, address);
8077 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
8079 type = storey.MutateType (type);
8080 ea.Expr.Type = storey.MutateType (ea.Expr.Type);
8084 /// <summary>
8085 /// Expressions that represent an indexer call.
8086 /// </summary>
8087 public class IndexerAccess : Expression, IAssignMethod
8089 class IndexerMethodGroupExpr : MethodGroupExpr
8091 public IndexerMethodGroupExpr (Indexers indexers, Location loc)
8092 : base (null, loc)
8094 Methods = (MethodBase []) indexers.Methods.ToArray (typeof (MethodBase));
8097 public override string Name {
8098 get {
8099 return "this";
8103 protected override int GetApplicableParametersCount (MethodBase method, AParametersCollection parameters)
8106 // Here is the trick, decrease number of arguments by 1 when only
8107 // available property method is setter. This makes overload resolution
8108 // work correctly for indexers.
8111 if (method.Name [0] == 'g')
8112 return parameters.Count;
8114 return parameters.Count - 1;
8118 class Indexers
8120 // Contains either property getter or setter
8121 public ArrayList Methods;
8122 public ArrayList Properties;
8124 Indexers ()
8128 void Append (Type caller_type, MemberInfo [] mi)
8130 if (mi == null)
8131 return;
8133 foreach (PropertyInfo property in mi) {
8134 MethodInfo accessor = property.GetGetMethod (true);
8135 if (accessor == null)
8136 accessor = property.GetSetMethod (true);
8138 if (Methods == null) {
8139 Methods = new ArrayList ();
8140 Properties = new ArrayList ();
8143 Methods.Add (accessor);
8144 Properties.Add (property);
8148 static MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8150 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8152 return TypeManager.MemberLookup (
8153 caller_type, caller_type, lookup_type, MemberTypes.Property,
8154 BindingFlags.Public | BindingFlags.Instance |
8155 BindingFlags.DeclaredOnly, p_name, null);
8158 public static Indexers GetIndexersForType (Type caller_type, Type lookup_type)
8160 Indexers ix = new Indexers ();
8162 if (TypeManager.IsGenericParameter (lookup_type)) {
8163 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (lookup_type);
8164 if (gc == null)
8165 return ix;
8167 if (gc.HasClassConstraint) {
8168 Type class_contraint = gc.ClassConstraint;
8169 while (class_contraint != TypeManager.object_type && class_contraint != null) {
8170 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, class_contraint));
8171 class_contraint = class_contraint.BaseType;
8175 Type[] ifaces = gc.InterfaceConstraints;
8176 foreach (Type itype in ifaces)
8177 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8179 return ix;
8182 Type copy = lookup_type;
8183 while (copy != TypeManager.object_type && copy != null){
8184 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
8185 copy = copy.BaseType;
8188 if (lookup_type.IsInterface) {
8189 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8190 if (ifaces != null) {
8191 foreach (Type itype in ifaces)
8192 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8196 return ix;
8200 enum AccessorType
8202 Get,
8207 // Points to our "data" repository
8209 MethodInfo get, set;
8210 bool is_base_indexer;
8211 bool prepared;
8212 LocalTemporary temp;
8213 LocalTemporary prepared_value;
8214 Expression set_expr;
8216 protected Type indexer_type;
8217 protected Type current_type;
8218 protected Expression instance_expr;
8219 protected Arguments arguments;
8221 public IndexerAccess (ElementAccess ea, Location loc)
8222 : this (ea.Expr, false, loc)
8224 this.arguments = ea.Arguments;
8227 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8228 Location loc)
8230 this.instance_expr = instance_expr;
8231 this.is_base_indexer = is_base_indexer;
8232 this.eclass = ExprClass.Value;
8233 this.loc = loc;
8236 static string GetAccessorName (AccessorType at)
8238 if (at == AccessorType.Set)
8239 return "set";
8241 if (at == AccessorType.Get)
8242 return "get";
8244 throw new NotImplementedException (at.ToString ());
8247 public override Expression CreateExpressionTree (EmitContext ec)
8249 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8250 instance_expr.CreateExpressionTree (ec),
8251 new TypeOfMethodInfo (get, loc));
8253 return CreateExpressionFactoryCall ("Call", args);
8256 protected virtual bool CommonResolve (EmitContext ec)
8258 indexer_type = instance_expr.Type;
8259 current_type = ec.ContainerType;
8261 return true;
8264 public override Expression DoResolve (EmitContext ec)
8266 return ResolveAccessor (ec, AccessorType.Get);
8269 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8271 if (right_side == EmptyExpression.OutAccess) {
8272 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
8273 GetSignatureForError ());
8274 return null;
8277 // if the indexer returns a value type, and we try to set a field in it
8278 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
8279 Error_CannotModifyIntermediateExpressionValue (ec);
8282 Expression e = ResolveAccessor (ec, AccessorType.Set);
8283 if (e == null)
8284 return null;
8286 set_expr = Convert.ImplicitConversion (ec, right_side, type, loc);
8287 return e;
8290 Expression ResolveAccessor (EmitContext ec, AccessorType accessorType)
8292 if (!CommonResolve (ec))
8293 return null;
8295 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type);
8296 if (ilist.Methods == null) {
8297 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8298 TypeManager.CSharpName (indexer_type));
8299 return null;
8302 MethodGroupExpr mg = new IndexerMethodGroupExpr (ilist, loc);
8303 mg = mg.OverloadResolve (ec, ref arguments, false, loc);
8304 if (mg == null)
8305 return null;
8307 MethodInfo mi = (MethodInfo) mg;
8308 PropertyInfo pi = null;
8309 for (int i = 0; i < ilist.Methods.Count; ++i) {
8310 if (ilist.Methods [i] == mi) {
8311 pi = (PropertyInfo) ilist.Properties [i];
8312 break;
8316 type = TypeManager.TypeToCoreType (pi.PropertyType);
8317 if (type.IsPointer && !ec.InUnsafe)
8318 UnsafeError (loc);
8320 MethodInfo accessor;
8321 if (accessorType == AccessorType.Get) {
8322 accessor = get = pi.GetGetMethod (true);
8323 } else {
8324 accessor = set = pi.GetSetMethod (true);
8325 if (accessor == null && pi.GetGetMethod (true) != null) {
8326 Report.SymbolRelatedToPreviousError (pi);
8327 Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
8328 TypeManager.GetFullNameSignature (pi));
8329 return null;
8333 if (accessor == null) {
8334 Report.SymbolRelatedToPreviousError (pi);
8335 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
8336 TypeManager.GetFullNameSignature (pi), GetAccessorName (accessorType));
8337 return null;
8341 // Only base will allow this invocation to happen.
8343 if (accessor.IsAbstract && this is BaseIndexerAccess) {
8344 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (pi));
8347 bool must_do_cs1540_check;
8348 if (!IsAccessorAccessible (ec.ContainerType, accessor, out must_do_cs1540_check)) {
8349 if (set == null)
8350 set = pi.GetSetMethod (true);
8351 else
8352 get = pi.GetGetMethod (true);
8354 if (set != null && get != null &&
8355 (set.Attributes & MethodAttributes.MemberAccessMask) != (get.Attributes & MethodAttributes.MemberAccessMask)) {
8356 Report.SymbolRelatedToPreviousError (accessor);
8357 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
8358 TypeManager.GetFullNameSignature (pi), GetAccessorName (accessorType));
8359 } else {
8360 Report.SymbolRelatedToPreviousError (pi);
8361 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (pi));
8365 instance_expr.CheckMarshalByRefAccess (ec);
8366 eclass = ExprClass.IndexerAccess;
8367 return this;
8370 public void Emit (EmitContext ec, bool leave_copy)
8372 if (prepared) {
8373 prepared_value.Emit (ec);
8374 } else {
8375 Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
8376 arguments, loc, false, false);
8379 if (leave_copy) {
8380 ec.ig.Emit (OpCodes.Dup);
8381 temp = new LocalTemporary (Type);
8382 temp.Store (ec);
8387 // source is ignored, because we already have a copy of it from the
8388 // LValue resolution and we have already constructed a pre-cached
8389 // version of the arguments (ea.set_arguments);
8391 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8393 prepared = prepare_for_load;
8394 Expression value = set_expr;
8396 if (prepared) {
8397 Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
8398 arguments, loc, true, false);
8400 prepared_value = new LocalTemporary (type);
8401 prepared_value.Store (ec);
8402 source.Emit (ec);
8403 prepared_value.Release (ec);
8405 if (leave_copy) {
8406 ec.ig.Emit (OpCodes.Dup);
8407 temp = new LocalTemporary (Type);
8408 temp.Store (ec);
8410 } else if (leave_copy) {
8411 temp = new LocalTemporary (Type);
8412 source.Emit (ec);
8413 temp.Store (ec);
8414 value = temp;
8417 if (!prepared)
8418 arguments.Add (new Argument (value));
8420 Invocation.EmitCall (ec, is_base_indexer, instance_expr, set, arguments, loc, false, prepared);
8422 if (temp != null) {
8423 temp.Emit (ec);
8424 temp.Release (ec);
8428 public override void Emit (EmitContext ec)
8430 Emit (ec, false);
8433 public override string GetSignatureForError ()
8435 return TypeManager.CSharpSignature (get != null ? get : set, false);
8438 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
8440 if (get != null)
8441 get = storey.MutateGenericMethod (get);
8442 if (set != null)
8443 set = storey.MutateGenericMethod (set);
8445 instance_expr.MutateHoistedGenericType (storey);
8446 if (arguments != null)
8447 arguments.MutateHoistedGenericType (storey);
8449 type = storey.MutateType (type);
8452 protected override void CloneTo (CloneContext clonectx, Expression t)
8454 IndexerAccess target = (IndexerAccess) t;
8456 if (arguments != null)
8457 target.arguments = arguments.Clone (clonectx);
8459 if (instance_expr != null)
8460 target.instance_expr = instance_expr.Clone (clonectx);
8464 /// <summary>
8465 /// The base operator for method names
8466 /// </summary>
8467 public class BaseAccess : Expression {
8468 public readonly string Identifier;
8469 TypeArguments args;
8471 public BaseAccess (string member, Location l)
8473 this.Identifier = member;
8474 loc = l;
8477 public BaseAccess (string member, TypeArguments args, Location l)
8478 : this (member, l)
8480 this.args = args;
8483 public override Expression CreateExpressionTree (EmitContext ec)
8485 throw new NotSupportedException ("ET");
8488 public override Expression DoResolve (EmitContext ec)
8490 Expression c = CommonResolve (ec);
8492 if (c == null)
8493 return null;
8496 // MethodGroups use this opportunity to flag an error on lacking ()
8498 if (!(c is MethodGroupExpr))
8499 return c.Resolve (ec);
8500 return c;
8503 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8505 Expression c = CommonResolve (ec);
8507 if (c == null)
8508 return null;
8511 // MethodGroups use this opportunity to flag an error on lacking ()
8513 if (! (c is MethodGroupExpr))
8514 return c.DoResolveLValue (ec, right_side);
8516 return c;
8519 Expression CommonResolve (EmitContext ec)
8521 Expression member_lookup;
8522 Type current_type = ec.ContainerType;
8523 Type base_type = current_type.BaseType;
8525 if (!This.IsThisAvailable (ec)) {
8526 if (ec.IsStatic) {
8527 Error (1511, "Keyword `base' is not available in a static method");
8528 } else {
8529 Error (1512, "Keyword `base' is not available in the current context");
8531 return null;
8534 member_lookup = MemberLookup (ec.ContainerType, null, base_type, Identifier,
8535 AllMemberTypes, AllBindingFlags, loc);
8536 if (member_lookup == null) {
8537 Error_MemberLookupFailed (ec.ContainerType, base_type, base_type, Identifier,
8538 null, AllMemberTypes, AllBindingFlags);
8539 return null;
8542 Expression left;
8544 if (ec.IsStatic)
8545 left = new TypeExpression (base_type, loc);
8546 else
8547 left = ec.GetThis (loc);
8549 MemberExpr me = (MemberExpr) member_lookup;
8550 me = me.ResolveMemberAccess (ec, left, loc, null);
8551 if (me == null)
8552 return null;
8554 me.IsBase = true;
8555 if (args != null) {
8556 args.Resolve (ec);
8557 me.SetTypeArguments (args);
8560 return me;
8563 public override void Emit (EmitContext ec)
8565 throw new Exception ("Should never be called");
8568 protected override void CloneTo (CloneContext clonectx, Expression t)
8570 BaseAccess target = (BaseAccess) t;
8572 if (args != null)
8573 target.args = args.Clone ();
8577 /// <summary>
8578 /// The base indexer operator
8579 /// </summary>
8580 public class BaseIndexerAccess : IndexerAccess {
8581 public BaseIndexerAccess (Arguments args, Location loc)
8582 : base (null, true, loc)
8584 this.arguments = args;
8587 protected override bool CommonResolve (EmitContext ec)
8589 instance_expr = ec.GetThis (loc);
8591 current_type = ec.ContainerType.BaseType;
8592 indexer_type = current_type;
8594 arguments.Resolve (ec);
8596 return true;
8599 public override Expression CreateExpressionTree (EmitContext ec)
8601 MemberExpr.Error_BaseAccessInExpressionTree (loc);
8602 return base.CreateExpressionTree (ec);
8606 /// <summary>
8607 /// This class exists solely to pass the Type around and to be a dummy
8608 /// that can be passed to the conversion functions (this is used by
8609 /// foreach implementation to typecast the object return value from
8610 /// get_Current into the proper type. All code has been generated and
8611 /// we only care about the side effect conversions to be performed
8613 /// This is also now used as a placeholder where a no-action expression
8614 /// is needed (the `New' class).
8615 /// </summary>
8616 public class EmptyExpression : Expression {
8617 public static readonly Expression Null = new EmptyExpression ();
8619 public static readonly EmptyExpression OutAccess = new EmptyExpression ();
8620 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8621 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8622 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8624 static EmptyExpression temp = new EmptyExpression ();
8625 public static EmptyExpression Grab ()
8627 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8628 temp = null;
8629 return retval;
8632 public static void Release (EmptyExpression e)
8634 temp = e;
8637 EmptyExpression ()
8639 // FIXME: Don't set to object
8640 type = TypeManager.object_type;
8641 eclass = ExprClass.Value;
8642 loc = Location.Null;
8645 public EmptyExpression (Type t)
8647 type = t;
8648 eclass = ExprClass.Value;
8649 loc = Location.Null;
8652 public override Expression CreateExpressionTree (EmitContext ec)
8654 throw new NotSupportedException ("ET");
8657 public override Expression DoResolve (EmitContext ec)
8659 return this;
8662 public override void Emit (EmitContext ec)
8664 // nothing, as we only exist to not do anything.
8667 public override void EmitSideEffect (EmitContext ec)
8672 // This is just because we might want to reuse this bad boy
8673 // instead of creating gazillions of EmptyExpressions.
8674 // (CanImplicitConversion uses it)
8676 public void SetType (Type t)
8678 type = t;
8683 // Empty statement expression
8685 public sealed class EmptyExpressionStatement : ExpressionStatement
8687 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8689 private EmptyExpressionStatement ()
8691 eclass = ExprClass.Value;
8692 loc = Location.Null;
8695 public override Expression CreateExpressionTree (EmitContext ec)
8697 return null;
8700 public override void EmitStatement (EmitContext ec)
8702 // Do nothing
8705 public override Expression DoResolve (EmitContext ec)
8707 type = TypeManager.object_type;
8708 return this;
8711 public override void Emit (EmitContext ec)
8713 // Do nothing
8717 public class UserCast : Expression {
8718 MethodInfo method;
8719 Expression source;
8721 public UserCast (MethodInfo method, Expression source, Location l)
8723 this.method = method;
8724 this.source = source;
8725 type = TypeManager.TypeToCoreType (method.ReturnType);
8726 loc = l;
8729 public Expression Source {
8730 get {
8731 return source;
8735 public override Expression CreateExpressionTree (EmitContext ec)
8737 Arguments args = new Arguments (3);
8738 args.Add (new Argument (source.CreateExpressionTree (ec)));
8739 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8740 args.Add (new Argument (new TypeOfMethodInfo (method, loc)));
8741 return CreateExpressionFactoryCall ("Convert", args);
8744 public override Expression DoResolve (EmitContext ec)
8746 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
8747 if (oa != null)
8748 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
8750 eclass = ExprClass.Value;
8751 return this;
8754 public override void Emit (EmitContext ec)
8756 source.Emit (ec);
8757 ec.ig.Emit (OpCodes.Call, method);
8760 public override string GetSignatureForError ()
8762 return TypeManager.CSharpSignature (method);
8765 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
8767 source.MutateHoistedGenericType (storey);
8768 method = storey.MutateGenericMethod (method);
8772 // <summary>
8773 // This class is used to "construct" the type during a typecast
8774 // operation. Since the Type.GetType class in .NET can parse
8775 // the type specification, we just use this to construct the type
8776 // one bit at a time.
8777 // </summary>
8778 public class ComposedCast : TypeExpr {
8779 FullNamedExpression left;
8780 string dim;
8782 public ComposedCast (FullNamedExpression left, string dim)
8783 : this (left, dim, left.Location)
8787 public ComposedCast (FullNamedExpression left, string dim, Location l)
8789 this.left = left;
8790 this.dim = dim;
8791 loc = l;
8794 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
8796 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8797 if (lexpr == null)
8798 return null;
8800 Type ltype = lexpr.Type;
8801 if ((dim.Length > 0) && (dim [0] == '?')) {
8802 TypeExpr nullable = new Nullable.NullableType (lexpr, loc);
8803 if (dim.Length > 1)
8804 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8805 return nullable.ResolveAsTypeTerminal (ec, false);
8808 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc))
8809 return null;
8811 if (dim.Length != 0 && dim [0] == '[') {
8812 if (TypeManager.IsSpecialType (ltype)) {
8813 Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (ltype));
8814 return null;
8817 if ((ltype.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
8818 Report.SymbolRelatedToPreviousError (ltype);
8819 Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8820 TypeManager.CSharpName (ltype));
8824 if (dim != "")
8825 type = TypeManager.GetConstructedType (ltype, dim);
8826 else
8827 type = ltype;
8829 if (type == null)
8830 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8832 if (type.IsPointer && !ec.IsInUnsafeScope){
8833 UnsafeError (loc);
8836 eclass = ExprClass.Type;
8837 return this;
8840 public override string GetSignatureForError ()
8842 return left.GetSignatureForError () + dim;
8845 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
8847 return ResolveAsBaseTerminal (ec, silent);
8851 public class FixedBufferPtr : Expression {
8852 Expression array;
8854 public FixedBufferPtr (Expression array, Type array_type, Location l)
8856 this.array = array;
8857 this.loc = l;
8859 type = TypeManager.GetPointerType (array_type);
8860 eclass = ExprClass.Value;
8863 public override Expression CreateExpressionTree (EmitContext ec)
8865 Error_PointerInsideExpressionTree ();
8866 return null;
8869 public override void Emit(EmitContext ec)
8871 array.Emit (ec);
8874 public override Expression DoResolve (EmitContext ec)
8877 // We are born fully resolved
8879 return this;
8885 // This class is used to represent the address of an array, used
8886 // only by the Fixed statement, this generates "&a [0]" construct
8887 // for fixed (char *pa = a)
8889 public class ArrayPtr : FixedBufferPtr {
8890 Type array_type;
8892 public ArrayPtr (Expression array, Type array_type, Location l):
8893 base (array, array_type, l)
8895 this.array_type = array_type;
8898 public override void Emit (EmitContext ec)
8900 base.Emit (ec);
8902 ILGenerator ig = ec.ig;
8903 IntLiteral.EmitInt (ig, 0);
8904 ig.Emit (OpCodes.Ldelema, array_type);
8909 // Encapsulates a conversion rules required for array indexes
8911 public class ArrayIndexCast : TypeCast
8913 public ArrayIndexCast (Expression expr)
8914 : base (expr, expr.Type)
8918 public override Expression CreateExpressionTree (EmitContext ec)
8920 Arguments args = new Arguments (2);
8921 args.Add (new Argument (child.CreateExpressionTree (ec)));
8922 args.Add (new Argument (new TypeOf (new TypeExpression (TypeManager.int32_type, loc), loc)));
8923 return CreateExpressionFactoryCall ("ConvertChecked", args);
8926 public override void Emit (EmitContext ec)
8928 child.Emit (ec);
8930 if (type == TypeManager.int32_type)
8931 return;
8933 if (type == TypeManager.uint32_type)
8934 ec.ig.Emit (OpCodes.Conv_U);
8935 else if (type == TypeManager.int64_type)
8936 ec.ig.Emit (OpCodes.Conv_Ovf_I);
8937 else if (type == TypeManager.uint64_type)
8938 ec.ig.Emit (OpCodes.Conv_Ovf_I_Un);
8939 else
8940 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8945 // Implements the `stackalloc' keyword
8947 public class StackAlloc : Expression {
8948 Type otype;
8949 Expression t;
8950 Expression count;
8952 public StackAlloc (Expression type, Expression count, Location l)
8954 t = type;
8955 this.count = count;
8956 loc = l;
8959 public override Expression CreateExpressionTree (EmitContext ec)
8961 throw new NotSupportedException ("ET");
8964 public override Expression DoResolve (EmitContext ec)
8966 count = count.Resolve (ec);
8967 if (count == null)
8968 return null;
8970 if (count.Type != TypeManager.uint32_type){
8971 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8972 if (count == null)
8973 return null;
8976 Constant c = count as Constant;
8977 if (c != null && c.IsNegative) {
8978 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8979 return null;
8982 if (ec.InCatch || ec.InFinally) {
8983 Error (255, "Cannot use stackalloc in finally or catch");
8984 return null;
8987 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8988 if (texpr == null)
8989 return null;
8991 otype = texpr.Type;
8993 if (!TypeManager.VerifyUnManaged (otype, loc))
8994 return null;
8996 type = TypeManager.GetPointerType (otype);
8997 eclass = ExprClass.Value;
8999 return this;
9002 public override void Emit (EmitContext ec)
9004 int size = GetTypeSize (otype);
9005 ILGenerator ig = ec.ig;
9007 count.Emit (ec);
9009 if (size == 0)
9010 ig.Emit (OpCodes.Sizeof, otype);
9011 else
9012 IntConstant.EmitInt (ig, size);
9014 ig.Emit (OpCodes.Mul_Ovf_Un);
9015 ig.Emit (OpCodes.Localloc);
9018 protected override void CloneTo (CloneContext clonectx, Expression t)
9020 StackAlloc target = (StackAlloc) t;
9021 target.count = count.Clone (clonectx);
9022 target.t = t.Clone (clonectx);
9027 // An object initializer expression
9029 public class ElementInitializer : Assign
9031 public readonly string Name;
9033 public ElementInitializer (string name, Expression initializer, Location loc)
9034 : base (null, initializer, loc)
9036 this.Name = name;
9039 protected override void CloneTo (CloneContext clonectx, Expression t)
9041 ElementInitializer target = (ElementInitializer) t;
9042 target.source = source.Clone (clonectx);
9045 public override Expression CreateExpressionTree (EmitContext ec)
9047 Arguments args = new Arguments (2);
9048 FieldExpr fe = target as FieldExpr;
9049 if (fe != null)
9050 args.Add (new Argument (fe.CreateTypeOfExpression ()));
9051 else
9052 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
9054 args.Add (new Argument (source.CreateExpressionTree (ec)));
9055 return CreateExpressionFactoryCall (
9056 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
9057 args);
9060 public override Expression DoResolve (EmitContext ec)
9062 if (source == null)
9063 return EmptyExpressionStatement.Instance;
9065 MemberExpr me = MemberLookupFinal (ec, ec.CurrentInitializerVariable.Type, ec.CurrentInitializerVariable.Type,
9066 Name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance, loc) as MemberExpr;
9068 if (me == null)
9069 return null;
9071 target = me;
9072 me.InstanceExpression = ec.CurrentInitializerVariable;
9074 if (source is CollectionOrObjectInitializers) {
9075 Expression previous = ec.CurrentInitializerVariable;
9076 ec.CurrentInitializerVariable = target;
9077 source = source.Resolve (ec);
9078 ec.CurrentInitializerVariable = previous;
9079 if (source == null)
9080 return null;
9082 eclass = source.eclass;
9083 type = source.Type;
9084 return this;
9087 Expression expr = base.DoResolve (ec);
9088 if (expr == null)
9089 return null;
9092 // Ignore field initializers with default value
9094 Constant c = source as Constant;
9095 if (c != null && c.IsDefaultInitializer (type) && target.eclass == ExprClass.Variable)
9096 return EmptyExpressionStatement.Instance.DoResolve (ec);
9098 return expr;
9101 protected override Expression Error_MemberLookupFailed (Type type, MemberInfo[] members)
9103 MemberInfo member = members [0];
9104 if (member.MemberType != MemberTypes.Property && member.MemberType != MemberTypes.Field)
9105 Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
9106 "initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
9107 else
9108 Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
9109 TypeManager.GetFullNameSignature (member));
9111 return null;
9114 public override void EmitStatement (EmitContext ec)
9116 if (source is CollectionOrObjectInitializers)
9117 source.Emit (ec);
9118 else
9119 base.EmitStatement (ec);
9124 // A collection initializer expression
9126 class CollectionElementInitializer : Invocation
9128 public class ElementInitializerArgument : Argument
9130 public ElementInitializerArgument (Expression e)
9131 : base (e)
9136 sealed class AddMemberAccess : MemberAccess
9138 public AddMemberAccess (Expression expr, Location loc)
9139 : base (expr, "Add", loc)
9143 protected override void Error_TypeDoesNotContainDefinition (Type type, string name)
9145 if (TypeManager.HasElementType (type))
9146 return;
9148 base.Error_TypeDoesNotContainDefinition (type, name);
9152 public CollectionElementInitializer (Expression argument)
9153 : base (null, new Arguments (1), true)
9155 base.arguments.Add (new ElementInitializerArgument (argument));
9156 this.loc = argument.Location;
9159 public CollectionElementInitializer (ArrayList arguments, Location loc)
9160 : base (null, new Arguments (arguments.Count), true)
9162 foreach (Expression e in arguments)
9163 base.arguments.Add (new ElementInitializerArgument (e));
9165 this.loc = loc;
9168 public override Expression CreateExpressionTree (EmitContext ec)
9170 Arguments args = new Arguments (2);
9171 args.Add (new Argument (mg.CreateExpressionTree (ec)));
9173 ArrayList expr_initializers = new ArrayList (arguments.Count);
9174 foreach (Argument a in arguments)
9175 expr_initializers.Add (a.CreateExpressionTree (ec));
9177 args.Add (new Argument (new ArrayCreation (
9178 CreateExpressionTypeExpression (loc), "[]", expr_initializers, loc)));
9179 return CreateExpressionFactoryCall ("ElementInit", args);
9182 protected override void CloneTo (CloneContext clonectx, Expression t)
9184 CollectionElementInitializer target = (CollectionElementInitializer) t;
9185 if (arguments != null)
9186 target.arguments = arguments.Clone (clonectx);
9189 public override Expression DoResolve (EmitContext ec)
9191 if (eclass != ExprClass.Invalid)
9192 return this;
9194 // TODO: We could call a constructor which takes element count argument,
9195 // for known types like List<T>, Dictionary<T, U>
9197 arguments.Resolve (ec);
9199 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
9201 return base.DoResolve (ec);
9206 // A block of object or collection initializers
9208 public class CollectionOrObjectInitializers : ExpressionStatement
9210 ArrayList initializers;
9211 bool is_collection_initialization;
9213 public static readonly CollectionOrObjectInitializers Empty =
9214 new CollectionOrObjectInitializers (new ArrayList (0), Location.Null);
9216 public CollectionOrObjectInitializers (ArrayList initializers, Location loc)
9218 this.initializers = initializers;
9219 this.loc = loc;
9222 public bool IsEmpty {
9223 get {
9224 return initializers.Count == 0;
9228 public bool IsCollectionInitializer {
9229 get {
9230 return is_collection_initialization;
9234 protected override void CloneTo (CloneContext clonectx, Expression target)
9236 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
9238 t.initializers = new ArrayList (initializers.Count);
9239 foreach (Expression e in initializers)
9240 t.initializers.Add (e.Clone (clonectx));
9243 public override Expression CreateExpressionTree (EmitContext ec)
9245 ArrayList expr_initializers = new ArrayList (initializers.Count);
9246 foreach (Expression e in initializers) {
9247 Expression expr = e.CreateExpressionTree (ec);
9248 if (expr != null)
9249 expr_initializers.Add (expr);
9252 return new ImplicitlyTypedArrayCreation ("[]", expr_initializers, loc);
9255 public override Expression DoResolve (EmitContext ec)
9257 if (eclass != ExprClass.Invalid)
9258 return this;
9260 ArrayList element_names = null;
9261 for (int i = 0; i < initializers.Count; ++i) {
9262 Expression initializer = (Expression) initializers [i];
9263 ElementInitializer element_initializer = initializer as ElementInitializer;
9265 if (i == 0) {
9266 if (element_initializer != null) {
9267 element_names = new ArrayList (initializers.Count);
9268 element_names.Add (element_initializer.Name);
9269 } else if (initializer is CompletingExpression){
9270 initializer.Resolve (ec);
9271 throw new InternalErrorException ("This line should never be reached");
9272 } else {
9273 if (!TypeManager.ImplementsInterface (ec.CurrentInitializerVariable.Type, TypeManager.ienumerable_type)) {
9274 Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9275 "object initializer because type `{1}' does not implement `{2}' interface",
9276 ec.CurrentInitializerVariable.GetSignatureForError (),
9277 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9278 TypeManager.CSharpName (TypeManager.ienumerable_type));
9279 return null;
9281 is_collection_initialization = true;
9283 } else {
9284 if (is_collection_initialization != (element_initializer == null)) {
9285 Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9286 is_collection_initialization ? "collection initializer" : "object initializer");
9287 continue;
9290 if (!is_collection_initialization) {
9291 if (element_names.Contains (element_initializer.Name)) {
9292 Report.Error (1912, element_initializer.Location,
9293 "An object initializer includes more than one member `{0}' initialization",
9294 element_initializer.Name);
9295 } else {
9296 element_names.Add (element_initializer.Name);
9301 Expression e = initializer.Resolve (ec);
9302 if (e == EmptyExpressionStatement.Instance)
9303 initializers.RemoveAt (i--);
9304 else
9305 initializers [i] = e;
9308 type = ec.CurrentInitializerVariable.Type;
9309 if (is_collection_initialization) {
9310 if (TypeManager.HasElementType (type)) {
9311 Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9312 TypeManager.CSharpName (type));
9316 eclass = ExprClass.Variable;
9317 return this;
9320 public override void Emit (EmitContext ec)
9322 EmitStatement (ec);
9325 public override void EmitStatement (EmitContext ec)
9327 foreach (ExpressionStatement e in initializers)
9328 e.EmitStatement (ec);
9331 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
9333 foreach (Expression e in initializers)
9334 e.MutateHoistedGenericType (storey);
9339 // New expression with element/object initializers
9341 public class NewInitialize : New
9344 // This class serves as a proxy for variable initializer target instances.
9345 // A real variable is assigned later when we resolve left side of an
9346 // assignment
9348 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9350 NewInitialize new_instance;
9352 public InitializerTargetExpression (NewInitialize newInstance)
9354 this.type = newInstance.type;
9355 this.loc = newInstance.loc;
9356 this.eclass = newInstance.eclass;
9357 this.new_instance = newInstance;
9360 public override Expression CreateExpressionTree (EmitContext ec)
9362 // Should not be reached
9363 throw new NotSupportedException ("ET");
9366 public override Expression DoResolve (EmitContext ec)
9368 return this;
9371 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
9373 return this;
9376 public override void Emit (EmitContext ec)
9378 Expression e = (Expression) new_instance.instance;
9379 e.Emit (ec);
9382 #region IMemoryLocation Members
9384 public void AddressOf (EmitContext ec, AddressOp mode)
9386 new_instance.instance.AddressOf (ec, mode);
9389 #endregion
9392 CollectionOrObjectInitializers initializers;
9393 IMemoryLocation instance;
9395 public NewInitialize (Expression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9396 : base (requested_type, arguments, l)
9398 this.initializers = initializers;
9401 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9403 instance = base.EmitAddressOf (ec, Mode);
9405 if (!initializers.IsEmpty)
9406 initializers.Emit (ec);
9408 return instance;
9411 protected override void CloneTo (CloneContext clonectx, Expression t)
9413 base.CloneTo (clonectx, t);
9415 NewInitialize target = (NewInitialize) t;
9416 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9419 public override Expression CreateExpressionTree (EmitContext ec)
9421 Arguments args = new Arguments (2);
9422 args.Add (new Argument (base.CreateExpressionTree (ec)));
9423 if (!initializers.IsEmpty)
9424 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9426 return CreateExpressionFactoryCall (
9427 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9428 args);
9431 public override Expression DoResolve (EmitContext ec)
9433 if (eclass != ExprClass.Invalid)
9434 return this;
9436 Expression e = base.DoResolve (ec);
9437 if (type == null)
9438 return null;
9440 Expression previous = ec.CurrentInitializerVariable;
9441 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9442 initializers.Resolve (ec);
9443 ec.CurrentInitializerVariable = previous;
9444 return e;
9447 public override bool Emit (EmitContext ec, IMemoryLocation target)
9449 bool left_on_stack = base.Emit (ec, target);
9451 if (initializers.IsEmpty)
9452 return left_on_stack;
9454 LocalTemporary temp = target as LocalTemporary;
9455 if (temp == null) {
9456 if (!left_on_stack) {
9457 VariableReference vr = target as VariableReference;
9459 // FIXME: This still does not work correctly for pre-set variables
9460 if (vr != null && vr.IsRef)
9461 target.AddressOf (ec, AddressOp.Load);
9463 ((Expression) target).Emit (ec);
9464 left_on_stack = true;
9467 temp = new LocalTemporary (type);
9470 instance = temp;
9471 if (left_on_stack)
9472 temp.Store (ec);
9474 initializers.Emit (ec);
9476 if (left_on_stack) {
9477 temp.Emit (ec);
9478 temp.Release (ec);
9481 return left_on_stack;
9484 public override bool HasInitializer {
9485 get {
9486 return !initializers.IsEmpty;
9490 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
9492 base.MutateHoistedGenericType (storey);
9493 initializers.MutateHoistedGenericType (storey);
9497 public class AnonymousTypeDeclaration : Expression
9499 ArrayList parameters;
9500 readonly TypeContainer parent;
9501 static readonly ArrayList EmptyParameters = new ArrayList (0);
9503 public AnonymousTypeDeclaration (ArrayList parameters, TypeContainer parent, Location loc)
9505 this.parameters = parameters;
9506 this.parent = parent;
9507 this.loc = loc;
9510 protected override void CloneTo (CloneContext clonectx, Expression target)
9512 if (parameters == null)
9513 return;
9515 AnonymousTypeDeclaration t = (AnonymousTypeDeclaration) target;
9516 t.parameters = new ArrayList (parameters.Count);
9517 foreach (AnonymousTypeParameter atp in parameters)
9518 t.parameters.Add (atp.Clone (clonectx));
9521 AnonymousTypeClass CreateAnonymousType (ArrayList parameters)
9523 AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
9524 if (type != null)
9525 return type;
9527 type = AnonymousTypeClass.Create (parent, parameters, loc);
9528 if (type == null)
9529 return null;
9531 type.DefineType ();
9532 type.Define ();
9533 type.EmitType ();
9534 if (Report.Errors == 0)
9535 type.CloseType ();
9537 parent.Module.AddAnonymousType (type);
9538 return type;
9541 public override Expression CreateExpressionTree (EmitContext ec)
9543 throw new NotSupportedException ("ET");
9546 public override Expression DoResolve (EmitContext ec)
9548 AnonymousTypeClass anonymous_type;
9550 if (!ec.IsAnonymousMethodAllowed) {
9551 Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9552 return null;
9555 if (parameters == null) {
9556 anonymous_type = CreateAnonymousType (EmptyParameters);
9557 return new New (new TypeExpression (anonymous_type.TypeBuilder, loc),
9558 null, loc).Resolve (ec);
9561 bool error = false;
9562 Arguments arguments = new Arguments (parameters.Count);
9563 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9564 for (int i = 0; i < parameters.Count; ++i) {
9565 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9566 if (e == null) {
9567 error = true;
9568 continue;
9571 arguments.Add (new Argument (e));
9572 t_args [i] = new TypeExpression (e.Type, e.Location);
9575 if (error)
9576 return null;
9578 anonymous_type = CreateAnonymousType (parameters);
9579 if (anonymous_type == null)
9580 return null;
9582 GenericTypeExpr te = new GenericTypeExpr (anonymous_type.TypeBuilder,
9583 new TypeArguments (t_args), loc);
9585 return new New (te, arguments, loc).Resolve (ec);
9588 public override void Emit (EmitContext ec)
9590 throw new InternalErrorException ("Should not be reached");
9594 public class AnonymousTypeParameter : Expression
9596 public readonly string Name;
9597 Expression initializer;
9599 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9601 this.Name = name;
9602 this.loc = loc;
9603 this.initializer = initializer;
9606 public AnonymousTypeParameter (Parameter parameter)
9608 this.Name = parameter.Name;
9609 this.loc = parameter.Location;
9610 this.initializer = new SimpleName (Name, loc);
9613 protected override void CloneTo (CloneContext clonectx, Expression target)
9615 AnonymousTypeParameter t = (AnonymousTypeParameter) target;
9616 t.initializer = initializer.Clone (clonectx);
9619 public override Expression CreateExpressionTree (EmitContext ec)
9621 throw new NotSupportedException ("ET");
9624 public override bool Equals (object o)
9626 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9627 return other != null && Name == other.Name;
9630 public override int GetHashCode ()
9632 return Name.GetHashCode ();
9635 public override Expression DoResolve (EmitContext ec)
9637 Expression e = initializer.Resolve (ec);
9638 if (e == null)
9639 return null;
9641 if (e.eclass == ExprClass.MethodGroup) {
9642 Error_InvalidInitializer (e.ExprClassName);
9643 return null;
9646 type = e.Type;
9647 if (type == TypeManager.void_type || type == TypeManager.null_type ||
9648 type == InternalType.AnonymousMethod || type.IsPointer) {
9649 Error_InvalidInitializer (e.GetSignatureForError ());
9650 return null;
9653 return e;
9656 protected virtual void Error_InvalidInitializer (string initializer)
9658 Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
9659 Name, initializer);
9662 public override void Emit (EmitContext ec)
9664 throw new InternalErrorException ("Should not be reached");